diff --git a/.gitignore b/.gitignore index c837ee8f..2b25befd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,14 +1,6 @@ # Created by https://www.toptal.com/developers/gitignore/api/xcode,swift,cocoapods # Edit at https://www.toptal.com/developers/gitignore?templates=xcode,swift,cocoapods -### CocoaPods ### -## CocoaPods GitIgnore Template - -# CocoaPods - Only use to conserve bandwidth / Save time on Pushing -# - Also handy if you have a large number of dependant pods -# - AS PER https://guides.cocoapods.org/using/using-cocoapods.html NEVER IGNORE THE LOCK FILE -Pods/ - ### Swift ### # Xcode # @@ -100,6 +92,7 @@ iOSInjectionProject/ ### DS_Store ### .DS_Store +APIToken.plist ### APIToken ### APIToken.plist diff --git a/ChatBot/ChatBot.xcodeproj/project.pbxproj b/ChatBot/ChatBot.xcodeproj/project.pbxproj index bc17e3cd..911fc726 100644 --- a/ChatBot/ChatBot.xcodeproj/project.pbxproj +++ b/ChatBot/ChatBot.xcodeproj/project.pbxproj @@ -7,20 +7,18 @@ objects = { /* Begin PBXBuildFile section */ - C12E66D32BB3F28800F3F441 /* ChatManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66B82BB3F28800F3F441 /* ChatManager.swift */; }; + 9B91052B2BC4D852004AF740 /* ChatBotMessageCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B91052A2BC4D852004AF740 /* ChatBotMessageCell.swift */; }; + 9B9289222BBECF5B00185E35 /* APIToken.plist in Resources */ = {isa = PBXBuildFile; fileRef = 9B9289212BBECF5B00185E35 /* APIToken.plist */; }; + C12E66D32BB3F28800F3F441 /* ChatBotViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66B82BB3F28800F3F441 /* ChatBotViewModel.swift */; }; C12E66D42BB3F28800F3F441 /* ChatRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66B92BB3F28800F3F441 /* ChatRepository.swift */; }; C12E66D52BB3F28800F3F441 /* RequestChatDTO.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66BA2BB3F28800F3F441 /* RequestChatDTO.swift */; }; - C12E66D62BB3F28800F3F441 /* UserMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66BB2BB3F28800F3F441 /* UserMessage.swift */; }; + C12E66D62BB3F28800F3F441 /* Message.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66BB2BB3F28800F3F441 /* Message.swift */; }; C12E66D72BB3F28800F3F441 /* Bundle+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66BD2BB3F28800F3F441 /* Bundle+Extension.swift */; }; - C12E66D82BB3F28800F3F441 /* URLSession+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66BE2BB3F28800F3F441 /* URLSession+Extension.swift */; }; C12E66D92BB3F28800F3F441 /* ChatBotViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66C02BB3F28800F3F441 /* ChatBotViewController.swift */; }; C12E66DB2BB3F28800F3F441 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C12E66C32BB3F28800F3F441 /* Assets.xcassets */; }; - C12E66DD2BB3F28800F3F441 /* APIService.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66C62BB3F28800F3F441 /* APIService.swift */; }; C12E66DE2BB3F28800F3F441 /* APIType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66C72BB3F28800F3F441 /* APIType.swift */; }; C12E66DF2BB3F28800F3F441 /* HttpMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66C82BB3F28800F3F441 /* HttpMethod.swift */; }; - C12E66E02BB3F28800F3F441 /* NetworkError.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66C92BB3F28800F3F441 /* NetworkError.swift */; }; C12E66E12BB3F28800F3F441 /* NetworkURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66CA2BB3F28800F3F441 /* NetworkURL.swift */; }; - C12E66E22BB3F28800F3F441 /* URLSessionProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66CB2BB3F28800F3F441 /* URLSessionProtocol.swift */; }; C12E66E32BB3F28800F3F441 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66CD2BB3F28800F3F441 /* AppDelegate.swift */; }; C12E66E42BB3F28800F3F441 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66CE2BB3F28800F3F441 /* SceneDelegate.swift */; }; C12E66E52BB3F28800F3F441 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = C12E66D12BB3F28800F3F441 /* LaunchScreen.storyboard */; }; @@ -28,27 +26,36 @@ C12E66EC2BB4291A00F3F441 /* ResponseChoiceDTO.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66EB2BB4291A00F3F441 /* ResponseChoiceDTO.swift */; }; C12E66EE2BB4294300F3F441 /* Usage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66ED2BB4294300F3F441 /* Usage.swift */; }; C12E66F02BB429AA00F3F441 /* JSONNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12E66EF2BB429AA00F3F441 /* JSONNull.swift */; }; - C1A0CBCC2BB55663009A000F /* APIToken.plist in Resources */ = {isa = PBXBuildFile; fileRef = C1A0CBCB2BB55663009A000F /* APIToken.plist */; }; + C1865DB82BBE9C3400DD99C9 /* Network.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1865DB72BBE9C3400DD99C9 /* Network.swift */; }; + C1865DBA2BBE9E8600DD99C9 /* NetworkProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1865DB92BBE9E8600DD99C9 /* NetworkProvider.swift */; }; + C1865DBC2BBEB72900DD99C9 /* ChatBotNetwork.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1865DBB2BBEB72900DD99C9 /* ChatBotNetwork.swift */; }; + C1C363012BC7D357000AA2D3 /* ChatBubbleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C363002BC7D357000AA2D3 /* ChatBubbleView.swift */; }; + C1C363032BC7D3BD000AA2D3 /* MessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C363022BC7D3BD000AA2D3 /* MessageView.swift */; }; + C1C363052BC9244F000AA2D3 /* UITextField+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C363042BC9244F000AA2D3 /* UITextField+Extension.swift */; }; + C1C363072BC92539000AA2D3 /* ChatBotListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C363062BC92539000AA2D3 /* ChatBotListView.swift */; }; + C1C363092BC92BC2000AA2D3 /* ChatInputTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C363082BC92BC2000AA2D3 /* ChatInputTextView.swift */; }; + C1C3630B2BC92C45000AA2D3 /* UserBubbleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C3630A2BC92C45000AA2D3 /* UserBubbleView.swift */; }; + C1C3630D2BC92C50000AA2D3 /* SystemBubbleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1C3630C2BC92C50000AA2D3 /* SystemBubbleView.swift */; }; C1E416662BB9888C00D8C836 /* UIViewController+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1E416652BB9888C00D8C836 /* UIViewController+Extension.swift */; }; + D28AA74380D6F3CE129AC66D /* Pods_ChatBot.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8913FA7C9B8C251C7E4CD5F /* Pods_ChatBot.framework */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 6F46BD03BD10D03BC697E016 /* Pods-ChatBot.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatBot.release.xcconfig"; path = "Target Support Files/Pods-ChatBot/Pods-ChatBot.release.xcconfig"; sourceTree = ""; }; + 9B91052A2BC4D852004AF740 /* ChatBotMessageCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBotMessageCell.swift; sourceTree = ""; }; + 9B9289212BBECF5B00185E35 /* APIToken.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = APIToken.plist; sourceTree = ""; }; B4B3E2B92B42D1BB00818B3C /* ChatBot.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ChatBot.app; sourceTree = BUILT_PRODUCTS_DIR; }; - C12E66B82BB3F28800F3F441 /* ChatManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatManager.swift; sourceTree = ""; }; + C12E66B82BB3F28800F3F441 /* ChatBotViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatBotViewModel.swift; sourceTree = ""; }; C12E66B92BB3F28800F3F441 /* ChatRepository.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatRepository.swift; sourceTree = ""; }; C12E66BA2BB3F28800F3F441 /* RequestChatDTO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestChatDTO.swift; sourceTree = ""; }; - C12E66BB2BB3F28800F3F441 /* UserMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserMessage.swift; sourceTree = ""; }; + C12E66BB2BB3F28800F3F441 /* Message.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Message.swift; sourceTree = ""; }; C12E66BD2BB3F28800F3F441 /* Bundle+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Bundle+Extension.swift"; sourceTree = ""; }; - C12E66BE2BB3F28800F3F441 /* URLSession+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "URLSession+Extension.swift"; sourceTree = ""; }; C12E66C02BB3F28800F3F441 /* ChatBotViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatBotViewController.swift; sourceTree = ""; }; C12E66C32BB3F28800F3F441 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; C12E66C42BB3F28800F3F441 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - C12E66C62BB3F28800F3F441 /* APIService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = APIService.swift; sourceTree = ""; }; C12E66C72BB3F28800F3F441 /* APIType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = APIType.swift; sourceTree = ""; }; C12E66C82BB3F28800F3F441 /* HttpMethod.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HttpMethod.swift; sourceTree = ""; }; - C12E66C92BB3F28800F3F441 /* NetworkError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkError.swift; sourceTree = ""; }; C12E66CA2BB3F28800F3F441 /* NetworkURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkURL.swift; sourceTree = ""; }; - C12E66CB2BB3F28800F3F441 /* URLSessionProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLSessionProtocol.swift; sourceTree = ""; }; C12E66CD2BB3F28800F3F441 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; C12E66CE2BB3F28800F3F441 /* SceneDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; C12E66D02BB3F28800F3F441 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; @@ -56,8 +63,19 @@ C12E66EB2BB4291A00F3F441 /* ResponseChoiceDTO.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResponseChoiceDTO.swift; sourceTree = ""; }; C12E66ED2BB4294300F3F441 /* Usage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Usage.swift; sourceTree = ""; }; C12E66EF2BB429AA00F3F441 /* JSONNull.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONNull.swift; sourceTree = ""; }; - C1A0CBCB2BB55663009A000F /* APIToken.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = APIToken.plist; path = ../../../../../../Matthew/Desktop/APIToken.plist; sourceTree = ""; }; + C1865DB72BBE9C3400DD99C9 /* Network.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Network.swift; sourceTree = ""; }; + C1865DB92BBE9E8600DD99C9 /* NetworkProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkProvider.swift; sourceTree = ""; }; + C1865DBB2BBEB72900DD99C9 /* ChatBotNetwork.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBotNetwork.swift; sourceTree = ""; }; + C1C363002BC7D357000AA2D3 /* ChatBubbleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBubbleView.swift; sourceTree = ""; }; + C1C363022BC7D3BD000AA2D3 /* MessageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageView.swift; sourceTree = ""; }; + C1C363042BC9244F000AA2D3 /* UITextField+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UITextField+Extension.swift"; sourceTree = ""; }; + C1C363062BC92539000AA2D3 /* ChatBotListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBotListView.swift; sourceTree = ""; }; + C1C363082BC92BC2000AA2D3 /* ChatInputTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatInputTextView.swift; sourceTree = ""; }; + C1C3630A2BC92C45000AA2D3 /* UserBubbleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserBubbleView.swift; sourceTree = ""; }; + C1C3630C2BC92C50000AA2D3 /* SystemBubbleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemBubbleView.swift; sourceTree = ""; }; C1E416652BB9888C00D8C836 /* UIViewController+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIViewController+Extension.swift"; sourceTree = ""; }; + EF8D881E2721E9C8810C312E /* Pods-ChatBot.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ChatBot.debug.xcconfig"; path = "Target Support Files/Pods-ChatBot/Pods-ChatBot.debug.xcconfig"; sourceTree = ""; }; + F8913FA7C9B8C251C7E4CD5F /* Pods_ChatBot.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ChatBot.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -65,17 +83,37 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + D28AA74380D6F3CE129AC66D /* Pods_ChatBot.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 82CD0E3CB81B67DDFC983DD6 /* Frameworks */ = { + isa = PBXGroup; + children = ( + F8913FA7C9B8C251C7E4CD5F /* Pods_ChatBot.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9FAE753BD9621E64B55604ED /* Pods */ = { + isa = PBXGroup; + children = ( + EF8D881E2721E9C8810C312E /* Pods-ChatBot.debug.xcconfig */, + 6F46BD03BD10D03BC697E016 /* Pods-ChatBot.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; B4B3E2B02B42D1BB00818B3C = { isa = PBXGroup; children = ( B4B3E2BB2B42D1BB00818B3C /* ChatBot */, B4B3E2BA2B42D1BB00818B3C /* Products */, + 9FAE753BD9621E64B55604ED /* Pods */, + 82CD0E3CB81B67DDFC983DD6 /* Frameworks */, ); sourceTree = ""; }; @@ -91,12 +129,12 @@ isa = PBXGroup; children = ( C12E66CF2BB3F28800F3F441 /* App */, - C12E66C12BB3F28800F3F441 /* Controller */, - C12E66BF2BB3F28800F3F441 /* Extension */, C12E66BC2BB3F28800F3F441 /* Model */, + C12E66D22BB3F28800F3F441 /* View */, + C1865DBD2BBEC71B00DD99C9 /* ViewModel */, + C12E66BF2BB3F28800F3F441 /* Extension */, C12E66CC2BB3F28800F3F441 /* Network */, C12E66C52BB3F28800F3F441 /* Resource */, - C12E66D22BB3F28800F3F441 /* View */, ); path = ChatBot; sourceTree = ""; @@ -104,10 +142,8 @@ C12E66BC2BB3F28800F3F441 /* Model */ = { isa = PBXGroup; children = ( - C12E66B82BB3F28800F3F441 /* ChatManager.swift */, - C12E66B92BB3F28800F3F441 /* ChatRepository.swift */, C12E66BA2BB3F28800F3F441 /* RequestChatDTO.swift */, - C12E66BB2BB3F28800F3F441 /* UserMessage.swift */, + C12E66BB2BB3F28800F3F441 /* Message.swift */, C12E66E92BB4283100F3F441 /* ResponseChatDTO.swift */, C12E66EB2BB4291A00F3F441 /* ResponseChoiceDTO.swift */, C12E66ED2BB4294300F3F441 /* Usage.swift */, @@ -120,26 +156,18 @@ isa = PBXGroup; children = ( C12E66BD2BB3F28800F3F441 /* Bundle+Extension.swift */, - C12E66BE2BB3F28800F3F441 /* URLSession+Extension.swift */, C1E416652BB9888C00D8C836 /* UIViewController+Extension.swift */, + C1C363042BC9244F000AA2D3 /* UITextField+Extension.swift */, ); path = Extension; sourceTree = ""; }; - C12E66C12BB3F28800F3F441 /* Controller */ = { - isa = PBXGroup; - children = ( - C12E66C02BB3F28800F3F441 /* ChatBotViewController.swift */, - ); - path = Controller; - sourceTree = ""; - }; C12E66C52BB3F28800F3F441 /* Resource */ = { isa = PBXGroup; children = ( C12E66C32BB3F28800F3F441 /* Assets.xcassets */, C12E66C42BB3F28800F3F441 /* Info.plist */, - C1A0CBCB2BB55663009A000F /* APIToken.plist */, + 9B9289212BBECF5B00185E35 /* APIToken.plist */, ); path = Resource; sourceTree = ""; @@ -147,12 +175,12 @@ C12E66CC2BB3F28800F3F441 /* Network */ = { isa = PBXGroup; children = ( - C12E66C62BB3F28800F3F441 /* APIService.swift */, C12E66C72BB3F28800F3F441 /* APIType.swift */, - C12E66C82BB3F28800F3F441 /* HttpMethod.swift */, - C12E66C92BB3F28800F3F441 /* NetworkError.swift */, C12E66CA2BB3F28800F3F441 /* NetworkURL.swift */, - C12E66CB2BB3F28800F3F441 /* URLSessionProtocol.swift */, + C1865DB72BBE9C3400DD99C9 /* Network.swift */, + C12E66C82BB3F28800F3F441 /* HttpMethod.swift */, + C1865DBB2BBEB72900DD99C9 /* ChatBotNetwork.swift */, + C1865DB92BBE9E8600DD99C9 /* NetworkProvider.swift */, ); path = Network; sourceTree = ""; @@ -169,11 +197,28 @@ C12E66D22BB3F28800F3F441 /* View */ = { isa = PBXGroup; children = ( + C12E66C02BB3F28800F3F441 /* ChatBotViewController.swift */, + C1C363082BC92BC2000AA2D3 /* ChatInputTextView.swift */, + C1C363062BC92539000AA2D3 /* ChatBotListView.swift */, + 9B91052A2BC4D852004AF740 /* ChatBotMessageCell.swift */, + C1C3630A2BC92C45000AA2D3 /* UserBubbleView.swift */, + C1C3630C2BC92C50000AA2D3 /* SystemBubbleView.swift */, + C1C363002BC7D357000AA2D3 /* ChatBubbleView.swift */, + C1C363022BC7D3BD000AA2D3 /* MessageView.swift */, C12E66D12BB3F28800F3F441 /* LaunchScreen.storyboard */, ); path = View; sourceTree = ""; }; + C1865DBD2BBEC71B00DD99C9 /* ViewModel */ = { + isa = PBXGroup; + children = ( + C12E66B82BB3F28800F3F441 /* ChatBotViewModel.swift */, + C12E66B92BB3F28800F3F441 /* ChatRepository.swift */, + ); + path = ViewModel; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -181,9 +226,11 @@ isa = PBXNativeTarget; buildConfigurationList = B4B3E2CD2B42D1BC00818B3C /* Build configuration list for PBXNativeTarget "ChatBot" */; buildPhases = ( + E671F0AE038BE9FF535377E8 /* [CP] Check Pods Manifest.lock */, B4B3E2B52B42D1BB00818B3C /* Sources */, B4B3E2B62B42D1BB00818B3C /* Frameworks */, B4B3E2B72B42D1BB00818B3C /* Resources */, + CD92C4DE6D105F60783833F7 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -232,7 +279,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - C1A0CBCC2BB55663009A000F /* APIToken.plist in Resources */, + 9B9289222BBECF5B00185E35 /* APIToken.plist in Resources */, C12E66DB2BB3F28800F3F441 /* Assets.xcassets in Resources */, C12E66E52BB3F28800F3F441 /* LaunchScreen.storyboard in Resources */, ); @@ -240,31 +287,80 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + CD92C4DE6D105F60783833F7 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-ChatBot/Pods-ChatBot-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-ChatBot/Pods-ChatBot-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-ChatBot/Pods-ChatBot-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + E671F0AE038BE9FF535377E8 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-ChatBot-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ B4B3E2B52B42D1BB00818B3C /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + C1C363012BC7D357000AA2D3 /* ChatBubbleView.swift in Sources */, C12E66D92BB3F28800F3F441 /* ChatBotViewController.swift in Sources */, - C12E66E02BB3F28800F3F441 /* NetworkError.swift in Sources */, C12E66DF2BB3F28800F3F441 /* HttpMethod.swift in Sources */, + C1C3630D2BC92C50000AA2D3 /* SystemBubbleView.swift in Sources */, C12E66DE2BB3F28800F3F441 /* APIType.swift in Sources */, - C12E66DD2BB3F28800F3F441 /* APIService.swift in Sources */, + C1C363072BC92539000AA2D3 /* ChatBotListView.swift in Sources */, C12E66D72BB3F28800F3F441 /* Bundle+Extension.swift in Sources */, C12E66E12BB3F28800F3F441 /* NetworkURL.swift in Sources */, - C12E66D32BB3F28800F3F441 /* ChatManager.swift in Sources */, + C1C3630B2BC92C45000AA2D3 /* UserBubbleView.swift in Sources */, + C1C363032BC7D3BD000AA2D3 /* MessageView.swift in Sources */, + C12E66D32BB3F28800F3F441 /* ChatBotViewModel.swift in Sources */, C12E66E42BB3F28800F3F441 /* SceneDelegate.swift in Sources */, - C12E66D82BB3F28800F3F441 /* URLSession+Extension.swift in Sources */, - C12E66E22BB3F28800F3F441 /* URLSessionProtocol.swift in Sources */, + C1865DBA2BBE9E8600DD99C9 /* NetworkProvider.swift in Sources */, C12E66EE2BB4294300F3F441 /* Usage.swift in Sources */, C1E416662BB9888C00D8C836 /* UIViewController+Extension.swift in Sources */, + C1C363092BC92BC2000AA2D3 /* ChatInputTextView.swift in Sources */, + C1865DBC2BBEB72900DD99C9 /* ChatBotNetwork.swift in Sources */, C12E66D52BB3F28800F3F441 /* RequestChatDTO.swift in Sources */, + C1865DB82BBE9C3400DD99C9 /* Network.swift in Sources */, C12E66F02BB429AA00F3F441 /* JSONNull.swift in Sources */, C12E66EC2BB4291A00F3F441 /* ResponseChoiceDTO.swift in Sources */, C12E66EA2BB4283100F3F441 /* ResponseChatDTO.swift in Sources */, + 9B91052B2BC4D852004AF740 /* ChatBotMessageCell.swift in Sources */, + C1C363052BC9244F000AA2D3 /* UITextField+Extension.swift in Sources */, C12E66D42BB3F28800F3F441 /* ChatRepository.swift in Sources */, C12E66E32BB3F28800F3F441 /* AppDelegate.swift in Sources */, - C12E66D62BB3F28800F3F441 /* UserMessage.swift in Sources */, + C12E66D62BB3F28800F3F441 /* Message.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -403,12 +499,14 @@ }; B4B3E2CE2B42D1BC00818B3C /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = EF8D881E2721E9C8810C312E /* Pods-ChatBot.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = T92LV6HV88; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = ChatBot/Resource/Info.plist; "INFOPLIST_FILE[sdk=*]" = ChatBot/Resource/Info.plist; @@ -436,12 +534,14 @@ }; B4B3E2CF2B42D1BC00818B3C /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 6F46BD03BD10D03BC697E016 /* Pods-ChatBot.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = T92LV6HV88; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = ChatBot/Resource/Info.plist; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; diff --git a/ChatBot/ChatBot.xcworkspace/contents.xcworkspacedata b/ChatBot/ChatBot.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..f1bd9fb7 --- /dev/null +++ b/ChatBot/ChatBot.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ChatBot/ChatBot.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ChatBot/ChatBot.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/ChatBot/ChatBot.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ChatBot/ChatBot/App/SceneDelegate.swift b/ChatBot/ChatBot/App/SceneDelegate.swift index cfbb53c4..cc386a86 100644 --- a/ChatBot/ChatBot/App/SceneDelegate.swift +++ b/ChatBot/ChatBot/App/SceneDelegate.swift @@ -9,8 +9,7 @@ import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? - - let chatManger = ChatManager() + let chatViewModel = ChatBotViewModel(chatRepository: ChatRepository(provider: NetworkProvider())) func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard @@ -19,8 +18,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { return } window = UIWindow(windowScene: windowScene) - - let mainViewController = ChatBotViewController(chatManager: chatManger) + let mainViewController = ChatBotViewController(chatBotViewModel: chatViewModel) window?.rootViewController = mainViewController window?.makeKeyAndVisible() } diff --git a/ChatBot/ChatBot/Controller/ChatBotViewController.swift b/ChatBot/ChatBot/Controller/ChatBotViewController.swift deleted file mode 100644 index 55da037e..00000000 --- a/ChatBot/ChatBot/Controller/ChatBotViewController.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// ViewController.swift -// ChatBot -// -// Created by Tacocat on 1/1/24. -// - -import UIKit - -class ChatBotViewController: UIViewController { - private let chatManager: ChatManager? - - init(chatManager: ChatManager?) { - self.chatManager = chatManager - super.init(nibName: nil, bundle: nil) - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } -} - -// MARK: - Life Cycle -extension ChatBotViewController { - override func viewDidLoad() { - super.viewDidLoad() - configureBackground() - chatGPT(userMessage: "집에 가고싶어욧..") - } -} - -// MARK: - Private Method -private extension ChatBotViewController { - func configureBackground() { - view.backgroundColor = .white - } - - func chatGPT(userMessage: String) { - Task{ - do { - guard - let result = try await chatManager?.requestChatResultData(userMessage: userMessage) - else { - return - } - print("질문 : \(userMessage)") - print("결과 : \(result.choices[0].message.content)") - } catch { - let okAction = UIAlertAction(title: "닫기", style: .default) - showMessageAlert(message: "\(error.localizedDescription)", action: [okAction]) - } - } - } -} diff --git a/ChatBot/ChatBot/Extension/UITextField+Extension.swift b/ChatBot/ChatBot/Extension/UITextField+Extension.swift new file mode 100644 index 00000000..5dc5fe36 --- /dev/null +++ b/ChatBot/ChatBot/Extension/UITextField+Extension.swift @@ -0,0 +1,16 @@ +// +// UITextField+Extension.swift +// ChatBot +// +// Created by Matthew on 4/12/24. +// + +import UIKit + +extension UITextField { + func addLeftPadding() { + let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: self.frame.height)) + self.leftView = paddingView + self.leftViewMode = ViewMode.always + } +} diff --git a/ChatBot/ChatBot/Extension/URLSession+Extension.swift b/ChatBot/ChatBot/Extension/URLSession+Extension.swift deleted file mode 100644 index f878744f..00000000 --- a/ChatBot/ChatBot/Extension/URLSession+Extension.swift +++ /dev/null @@ -1,14 +0,0 @@ -// -// URLSession+Extension.swift -// ChatBot -// -// Created by LeeSeongYeon on 3/26/24. -// - -import Foundation - -extension URLSession: URLSessionProtocol { - func requestData(with request: URLRequest) async throws -> (Data, URLResponse) { - return try await data(for: request) - } -} diff --git a/ChatBot/ChatBot/Model/ChatManager.swift b/ChatBot/ChatBot/Model/ChatManager.swift deleted file mode 100644 index ee640110..00000000 --- a/ChatBot/ChatBot/Model/ChatManager.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// ChatManager.swift -// ChatBot -// -// Created by LeeSeongYeon on 3/27/24. -// - -import Foundation - -final class ChatManager { - var chatData: [ResponseChatDTO]? - private let chatRepository: ChatRepository = ChatRepository() -} - -extension ChatManager { - func requestChatResultData(userMessage: String) async throws -> ResponseChatDTO { - let result = try await chatRepository.requestChatResultData(userMessage: userMessage) - switch result { - case .success(let data): - self.chatData?.append(data) - return data - case .failure(let error): - throw error - } - } -} diff --git a/ChatBot/ChatBot/Model/ChatRepository.swift b/ChatBot/ChatBot/Model/ChatRepository.swift deleted file mode 100644 index d7c6049d..00000000 --- a/ChatBot/ChatBot/Model/ChatRepository.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// Repository.swift -// ChatBot -// -// Created by LeeSeongYeon on 3/26/24. -// - -import Foundation - -struct ChatRepository { - private let apiService: APIService = APIService(session: URLSession.shared) - func requestChatResultData(userMessage: String) async throws -> (Result) { - - let chat = RequestChatDTO(messages: [ - Message(role: "system", content: "너는 연애고수야"), - Message(role: "user", content: "\(userMessage)") - ]) - - guard - let urlRequest = NetworkURL.makeURLRequest(type: .chatGPT, chat: chat, httpMethod: .post) - else { - return .failure(.invalidURLRequestError) - } - - let result = try await apiService.fetchData(with: urlRequest) - switch result { - case .success(let success): - return handleDecodedData(data: success) - case .failure(let failure): - return .failure(failure) - } - } -} - -private extension ChatRepository { - func handleDecodedData(data: Data?) -> (Result) { - guard - let data = data - else { - return .failure(.noDataError) - } - do { - let decodedData = try JSONDecoder().decode(T.self, from: data) - return .success(decodedData) - } catch { - return .failure(.decodingError) - } - } -} diff --git a/ChatBot/ChatBot/Model/UserMessage.swift b/ChatBot/ChatBot/Model/Message.swift similarity index 100% rename from ChatBot/ChatBot/Model/UserMessage.swift rename to ChatBot/ChatBot/Model/Message.swift diff --git a/ChatBot/ChatBot/Network/APIService.swift b/ChatBot/ChatBot/Network/APIService.swift deleted file mode 100644 index ddffd5cf..00000000 --- a/ChatBot/ChatBot/Network/APIService.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// APIService.swift -// ChatBot -// -// Created by LeeSeongYeon on 3/26/24. -// - -import Foundation - -struct APIService { - typealias APIResult = (Result) - private let session: URLSessionProtocol - - init(session: URLSessionProtocol) { - self.session = session - } - - func fetchData(with urlRequest: URLRequest) async throws -> APIResult { - let (data, response) = try await session.requestData(with: urlRequest) - return handleDataTaskCompletion(data: data, response: response) - } -} - -private extension APIService { - func handleDataTaskCompletion(data: Data?, response: URLResponse?) -> APIResult { - guard - let httpResponse = response as? HTTPURLResponse - else { - return .failure(.invalidResponseError) - } - return self.handleHTTPResponse(data: data, httpResponse: httpResponse) - } - - func handleHTTPResponse(data: Data?, httpResponse: HTTPURLResponse) -> APIResult { - guard - let data = data - else { - return .failure(.noDataError) - } - switch httpResponse.statusCode { - case 300..<400: - return .failure(.redirectionError) - case 400..<500: - return .failure(.clientError) - case 500..<600: - return .failure(.serverError) - default: - return .success(data) - } - } -} diff --git a/ChatBot/ChatBot/Network/ChatBotNetwork.swift b/ChatBot/ChatBot/Network/ChatBotNetwork.swift new file mode 100644 index 00000000..ae2f03f1 --- /dev/null +++ b/ChatBot/ChatBot/Network/ChatBotNetwork.swift @@ -0,0 +1,22 @@ +// +// ChatBotNetwork.swift +// ChatBot +// +// Created by Matthew on 4/4/24. +// + +import Foundation +import RxSwift + +final class ChatBotNetwork { + private let network: Network + + init(network: Network) { + self.network = network + } + + func requestChatBotMessage(message: Message) -> Observable { + return network.fetchData(message: message) + } +} + diff --git a/ChatBot/ChatBot/Network/Network.swift b/ChatBot/ChatBot/Network/Network.swift new file mode 100644 index 00000000..98389be6 --- /dev/null +++ b/ChatBot/ChatBot/Network/Network.swift @@ -0,0 +1,29 @@ +// +// Network.swift +// ChatBot +// +// Created by Matthew on 4/4/24. +// + +import RxSwift +import RxAlamofire +import Foundation + +class Network { + private let queue: ConcurrentDispatchQueueScheduler + + init() { + self.queue = ConcurrentDispatchQueueScheduler(qos: .background) + } + + func fetchData(message: Message) -> Observable { + let urlRequest = NetworkURL.makeURLRequest(type: .chatGPT, chat: RequestChatDTO(messages: [message]), httpMethod: .post)! + let result = RxAlamofire.requestData(urlRequest) + .observe(on: queue) + .debug() + .map { (response, data) -> T in + return try JSONDecoder().decode(T.self, from: data) + } + return result + } +} diff --git a/ChatBot/ChatBot/Network/NetworkError.swift b/ChatBot/ChatBot/Network/NetworkError.swift deleted file mode 100644 index 49c7c809..00000000 --- a/ChatBot/ChatBot/Network/NetworkError.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// NetworkError.swift -// ChatBot -// -// Created by LeeSeongYeon on 3/26/24. -// - -import Foundation - -enum NetworkError: LocalizedError { - case invalidURLError - case invalidURLRequestError - case noDataError - case requestFailError - case invalidResponseError - case redirectionError - case clientError - case serverError - case decodingError - - var errorDescription: String? { - switch self { - case .invalidURLError: - return "잘못된 URL 주소입니다." - case .invalidURLRequestError: - return "잘못된 URL 요청입니다." - case .noDataError: - return "데이터가 존재하지 않습니다." - case .requestFailError: - return "요청에 실패 했습니다." - case .invalidResponseError: - return "잘못된 요청 입니다." - case .redirectionError: - return "리다이렉션 에러 발생" - case .clientError: - return "사용자 요청 에러 발생" - case .serverError: - return "서버 에러 발생" - case .decodingError: - return "JSON 디코딩 에러 발생" - } - } -} diff --git a/ChatBot/ChatBot/Network/NetworkProvider.swift b/ChatBot/ChatBot/Network/NetworkProvider.swift new file mode 100644 index 00000000..81b03c5c --- /dev/null +++ b/ChatBot/ChatBot/Network/NetworkProvider.swift @@ -0,0 +1,15 @@ +// +// NetworkProvider.swift +// ChatBot +// +// Created by Matthew on 4/4/24. +// + +import Foundation + +final class NetworkProvider { + func makeChatNetwork() -> ChatBotNetwork { + let network = Network() + return ChatBotNetwork(network: network) + } +} diff --git a/ChatBot/ChatBot/Network/NetworkURL.swift b/ChatBot/ChatBot/Network/NetworkURL.swift index e3819dda..0a37c795 100644 --- a/ChatBot/ChatBot/Network/NetworkURL.swift +++ b/ChatBot/ChatBot/Network/NetworkURL.swift @@ -8,8 +8,7 @@ import Foundation enum NetworkURL { - static func makeURLRequest(type: APIType, chat: RequestChatDTO, httpMethod: HttpMethod = .get) -> URLRequest? { - + static func makeURLRequest(type: APIType, chat: RequestChatDTO, httpMethod: HttpMethod = .get) -> URLRequest? { let urlComponents = makeURLComponents(type: type) guard diff --git a/ChatBot/ChatBot/Network/URLSessionProtocol.swift b/ChatBot/ChatBot/Network/URLSessionProtocol.swift deleted file mode 100644 index 16251168..00000000 --- a/ChatBot/ChatBot/Network/URLSessionProtocol.swift +++ /dev/null @@ -1,13 +0,0 @@ -// -// URLSessionProtocol.swift -// ChatBot -// -// Created by LeeSeongYeon on 3/26/24. -// - -import Foundation - -protocol URLSessionProtocol { - func requestData(with request: URLRequest) async throws -> (Data, URLResponse) -} - diff --git a/ChatBot/ChatBot/View/ChatBotListView.swift b/ChatBot/ChatBot/View/ChatBotListView.swift new file mode 100644 index 00000000..f6541886 --- /dev/null +++ b/ChatBot/ChatBot/View/ChatBotListView.swift @@ -0,0 +1,33 @@ +// +// ChatBotListView.swift +// ChatBot +// +// Created by Matthew on 4/12/24. +// + +import UIKit +import SnapKit +import Then + +final class ChatBotListView: UICollectionView { + init() { + var config = UICollectionLayoutListConfiguration(appearance: .plain) + config.showsSeparators = false + let layout = UICollectionViewCompositionalLayout.list(using: config) + layout.configuration.boundarySupplementaryItems = [] + super.init(frame: .zero, collectionViewLayout: layout) + setupCollectionView() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Private Method +private extension ChatBotListView { + func setupCollectionView() { + self.register(ChatBotMessageCell.self, forCellWithReuseIdentifier: "cell") + self.backgroundColor = .white + } +} diff --git a/ChatBot/ChatBot/View/ChatBotMessageCell.swift b/ChatBot/ChatBot/View/ChatBotMessageCell.swift new file mode 100644 index 00000000..5b6bad9f --- /dev/null +++ b/ChatBot/ChatBot/View/ChatBotMessageCell.swift @@ -0,0 +1,77 @@ +// +// ChatBotView.swift +// ChatBot +// +// Created by LeeSeongYeon on 4/9/24. +// + +import UIKit +import Then +import SnapKit + +final class ChatBotMessageCell: UICollectionViewListCell { + private let userBubbleView = UserBubbleView() + private let systemBubbleView = SystemBubbleView() + + override init(frame: CGRect) { + super.init(frame: frame) + setupConstraint() + setupUserConstraints() + setupSystemConstraints() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Public Method +extension ChatBotMessageCell { + func setupMessageText(message: Message, type: String) { + switch type { + case "user": + self.configureUser(text: message.content) + case "assistant": + self.configureSystem(text: message.content) + default: + break + } + } +} + +// MARK: - Private Method +private extension ChatBotMessageCell { + func setupConstraint() { + self.contentView.addSubview(userBubbleView) + self.contentView.addSubview(systemBubbleView) + } + + func configureUser(text: String) { + systemBubbleView.isHidden = true + userBubbleView.isHidden = false + userBubbleView.configureMessage(text: text) + } + + func configureSystem(text: String) { + systemBubbleView.isHidden = false + userBubbleView.isHidden = true + systemBubbleView.configureMessage(text: text) + } + + + func setupUserConstraints() { + userBubbleView.snp.makeConstraints { make in + make.trailing.equalToSuperview().offset(-10) + make.top.equalToSuperview().offset(5) + make.bottom.equalToSuperview().offset(-5) + } + } + + func setupSystemConstraints() { + systemBubbleView.snp.makeConstraints { make in + make.leading.equalToSuperview().offset(10) + make.top.equalToSuperview().offset(5) + make.bottom.equalToSuperview().offset(-5) + } + } +} diff --git a/ChatBot/ChatBot/View/ChatBotViewController.swift b/ChatBot/ChatBot/View/ChatBotViewController.swift new file mode 100644 index 00000000..a2e0745a --- /dev/null +++ b/ChatBot/ChatBot/View/ChatBotViewController.swift @@ -0,0 +1,125 @@ +// +// ViewController.swift +// ChatBot +// +// Created by Tacocat on 1/1/24. +// + +import UIKit +import Then +import SnapKit +import RxSwift +import RxCocoa + +final class ChatBotViewController: UIViewController { + private let chatInputTextView = ChatInputTextView() + private lazy var chatList = ChatBotListView() + private let chatBotViewModel: ChatBotViewModel + private var messageList: [Message] = [] + + let disposeBag = DisposeBag() + let chatTrigger = PublishSubject() + + init(chatBotViewModel: ChatBotViewModel) { + self.chatBotViewModel = chatBotViewModel + super.init(nibName: nil, bundle: nil) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Life Cycle +extension ChatBotViewController { + override func viewDidLoad() { + super.viewDidLoad() + chatList.dataSource = self + setupView() + setupSubview() + bindViewModel() + bindView() + addTapGesture() + setupConstraint() + } +} + +// MARK: - Private Method +private extension ChatBotViewController { + func setupView() { + view.backgroundColor = .white + } + + func addTapGesture() { + let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) + view.addGestureRecognizer(tapGesture) + } + + @objc + func handleTap(_ sender: UITapGestureRecognizer) { + view.endEditing(true) + } + + func setupSubview() { + view.addSubview(chatList) + view.addSubview(chatInputTextView) + } + + func setupConstraint() { + chatList.snp.makeConstraints { make in + make.top.leading.trailing.equalTo(view.safeAreaLayoutGuide) + make.bottom.equalTo(chatInputTextView.snp.top) + } + + chatInputTextView.snp.makeConstraints { make in + make.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) + } + } + + func bindViewModel() { + let input = ChatBotViewModel.Input(chatTigger: chatTrigger) + let output = chatBotViewModel.transform(input: input) + output.resultChat + .observe(on: MainScheduler.instance) + .bind { result in + switch result { + case .success(let data): + let message = Message(role: "assistant", content: data.choices[0].message.content) + self.messageList.append(message) + self.chatList.reloadData() + case .failure(let error): + let okAction = UIAlertAction(title: "확인", style: .default) + self.showMessageAlert(message: "\(error.localizedDescription)", action: [okAction]) + } + } + .disposed(by: disposeBag) + } + + func bindView() { + chatInputTextView.enterButton.rx.tap.bind { [weak self] _ in + guard + let userInputText = self?.chatInputTextView.inputTextField.text + else { + return + } + + let userMessage = Message(role: "user", content: userInputText) + + self?.chatTrigger.onNext(userMessage) + self?.messageList.append(userMessage) + self?.chatList.reloadData() + }.disposed(by: disposeBag) + } +} + +extension ChatBotViewController: UICollectionViewDataSource { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return self.messageList.count + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = chatList.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ChatBotMessageCell + cell.setupMessageText(message: messageList[indexPath.row], type: messageList[indexPath.row].role) + return cell + } +} diff --git a/ChatBot/ChatBot/View/ChatBubbleView.swift b/ChatBot/ChatBot/View/ChatBubbleView.swift new file mode 100644 index 00000000..6eb6a29f --- /dev/null +++ b/ChatBot/ChatBot/View/ChatBubbleView.swift @@ -0,0 +1,169 @@ +// +// ChatBubbleView.swift +// ChatBot +// +// Created by Matthew on 4/11/24. +// + +import UIKit +import Then +import SnapKit + +class ChatBubbleView: UIView { + private let messageView = MessageView() + + override init(frame: CGRect) { + super.init(frame: frame) + contentMode = .redraw + self.backgroundColor = .clear + self.configureUI() + self.setupConstraints() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func configureMessage(text: String) { + messageView.text = text + } + + func configureUI() { + self.addSubview(messageView) + } + + func setupConstraints() { + self.snp.makeConstraints { make in + make.height.equalTo(messageView.snp.height) + } + + messageView.snp.makeConstraints { make in + make.centerY.equalToSuperview() + if self is UserBubbleView { + make.trailing.equalToSuperview().offset(-10) + make.leading.greaterThanOrEqualToSuperview().offset(10) + } + else { + make.leading.equalToSuperview().offset(10) + make.trailing.lessThanOrEqualToSuperview().offset(-10) + } + make.width.lessThanOrEqualTo(UIScreen.main.bounds.width * 0.75) + } + } + + func setRightBubbleView(rect: CGRect) { + let bezierPath = UIBezierPath() + messageView.textColor = .white + let bottom = rect.height + let right = rect.width + bezierPath.move( + to: CGPoint(x: right - 22, y: bottom) + ) + bezierPath.addLine( + to: CGPoint(x: 17, y: bottom) + ) + bezierPath.addCurve( + to: CGPoint(x: 0, y: bottom - 18), + controlPoint1: CGPoint(x: 7.61, y: bottom), + controlPoint2: CGPoint(x: 0, y: bottom - 7.61) + ) + bezierPath.addLine( + to: CGPoint(x: 0, y: 17) + ) + bezierPath.addCurve( + to: CGPoint(x: 17, y: 0), + controlPoint1: CGPoint(x: 0, y: 7.61), + controlPoint2: CGPoint(x: 7.61, y: 0) + ) + bezierPath.addLine( + to: CGPoint(x: right - 21, y: 0) + ) + bezierPath.addCurve( + to: CGPoint(x: right - 4, y: 17), + controlPoint1: CGPoint(x: right - 11.61, y: 0), + controlPoint2: CGPoint(x: right - 4, y: 7.61) + ) + bezierPath.addLine( + to: CGPoint(x: right - 4, y: bottom - 11) + ) + bezierPath.addCurve( + to: CGPoint(x: right, y: bottom), + controlPoint1: CGPoint(x: right - 4, y: bottom - 1), + controlPoint2: CGPoint(x: right, y: bottom) + ) + bezierPath.addLine( + to: CGPoint(x: right + 0.05, y: bottom - 0.01) + ) + bezierPath.addCurve( + to: CGPoint(x: right - 11.04, y: bottom - 4.04), + controlPoint1: CGPoint(x: right - 4.07, y: bottom + 0.43), + controlPoint2: CGPoint(x: right - 8.16, y: bottom - 1.06) + ) + bezierPath.addCurve( + to: CGPoint(x: right - 22, y: bottom), + controlPoint1: CGPoint(x: right - 16, y: bottom), + controlPoint2: CGPoint(x: right - 19, y: bottom) + ) + bezierPath.close() + UIColor(cgColor: UIColor.systemBlue.cgColor).setFill() + bezierPath.fill() + } + + func setLeftBubbleView(rect: CGRect) { + let bezierPath = UIBezierPath() + let bottom = rect.height + let right = rect.width + + bezierPath.move( + to: CGPoint(x: 22, y: bottom) + ) + bezierPath.addLine( + to: CGPoint(x: right - 17, y: bottom) + ) + bezierPath.addCurve( + to: CGPoint(x: right, y: bottom - 18), + controlPoint1: CGPoint(x: right - 7.61, y: bottom), + controlPoint2: CGPoint(x: right, y: bottom - 7.61) + ) + bezierPath.addLine( + to: CGPoint(x: right, y: 17) + ) + bezierPath.addCurve( + to: CGPoint(x: right - 17, y: 0), + controlPoint1: CGPoint(x: right, y: 7.61), + controlPoint2: CGPoint(x: right - 7.61, y: 0) + ) + bezierPath.addLine( + to: CGPoint(x: 21, y: 0) + ) + bezierPath.addCurve( + to: CGPoint(x: 4, y: 17), + controlPoint1: CGPoint(x: 11.61, y: 0), + controlPoint2: CGPoint(x: 4, y: 7.61) + ) + bezierPath.addLine( + to: CGPoint(x: 4, y: bottom - 11) + ) + bezierPath.addCurve( + to: CGPoint(x: 0, y: bottom), + controlPoint1: CGPoint(x: 4, y: bottom - 1), + controlPoint2: CGPoint(x: 0, y: bottom) + ) + bezierPath.addLine( + to: CGPoint(x: -0.05, y: bottom - 0.01) + ) + bezierPath.addCurve( + to: CGPoint(x: 11.04, y: bottom - 4.04), + controlPoint1: CGPoint(x: 4.07, y: bottom + 0.43), + controlPoint2: CGPoint(x: 8.16, y: bottom - 1.06) + ) + bezierPath.addCurve( + to: CGPoint(x: 22, y: bottom), + controlPoint1: CGPoint(x: 16, y: bottom), + controlPoint2: CGPoint(x: 19, y: bottom) + ) + bezierPath.close() + UIColor(cgColor: UIColor.systemGray5.cgColor).setFill() + bezierPath.fill() + } +} diff --git a/ChatBot/ChatBot/View/ChatInputTextView.swift b/ChatBot/ChatBot/View/ChatInputTextView.swift new file mode 100644 index 00000000..89e45fe0 --- /dev/null +++ b/ChatBot/ChatBot/View/ChatInputTextView.swift @@ -0,0 +1,71 @@ +// +// ChatInputTextView.swift +// ChatBot +// +// Created by Matthew on 4/12/24. +// + +import UIKit +import SnapKit +import Then + +final class ChatInputTextView: UIView { + lazy var inputTextField = UITextField().then { + $0.frame = CGRect(x: 0, y: 0, width: 0, height: 30) + $0.layer.cornerRadius = $0.layer.frame.height / 2 + $0.layer.borderWidth = 1 + $0.layer.borderColor = UIColor.lightGray.cgColor + $0.layer.masksToBounds = false + $0.placeholder = "메세지를 입력해주세요." + } + + lazy var enterButton = UIButton().then { + let view = UIImageView().then { + $0.image = UIImage(systemName: "paperplane.circle.fill") + $0.tintColor = .systemBlue + } + + view.snp.makeConstraints { make in + make.height.width.equalTo(36) + } + + $0.addSubview(view) + } + + private lazy var inputStackView = UIStackView().then { + $0.axis = .horizontal + $0.alignment = .center + $0.spacing = 10 + $0.distribution = .fillProportionally + $0.addArrangedSubview(inputTextField) + $0.addArrangedSubview(enterButton) + } + + override init(frame: CGRect) { + super.init(frame: frame) + setupConstraint() + inputTextField.addLeftPadding() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Private Method +private extension ChatInputTextView { + func setupConstraint() { + self.addSubview(inputStackView) + inputTextField.snp.makeConstraints { make in + make.width.equalTo(self.snp.width).multipliedBy(0.8) + make.height.equalTo(30) + } + + inputStackView.snp.makeConstraints { make in + make.leading.equalTo(self.safeAreaLayoutGuide.snp.leading).offset(20) + make.trailing.equalTo(self.safeAreaLayoutGuide.snp.trailing).offset(-20) + make.bottom.equalTo(self.keyboardLayoutGuide.snp.top) + make.height.equalTo(self.snp.height).multipliedBy(0.07) + } + } +} diff --git a/ChatBot/ChatBot/View/MessageView.swift b/ChatBot/ChatBot/View/MessageView.swift new file mode 100644 index 00000000..2ba01c2d --- /dev/null +++ b/ChatBot/ChatBot/View/MessageView.swift @@ -0,0 +1,31 @@ +// +// MessageView.swift +// ChatBot +// +// Created by Matthew on 4/11/24. +// + +import UIKit +import Then +import SnapKit + +final class MessageView: UILabel { + override init(frame: CGRect) { + super.init(frame: frame) + configureUI() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Private Method +private extension MessageView { + func configureUI() { + self.tintColor = .black + self.backgroundColor = .clear + self.textAlignment = .left + self.numberOfLines = 0 + } +} diff --git a/ChatBot/ChatBot/View/SystemBubbleView.swift b/ChatBot/ChatBot/View/SystemBubbleView.swift new file mode 100644 index 00000000..56b076ba --- /dev/null +++ b/ChatBot/ChatBot/View/SystemBubbleView.swift @@ -0,0 +1,28 @@ +// +// SystemBubbleView.swift +// ChatBot +// +// Created by Matthew on 4/12/24. +// + +import UIKit +import Then +import SnapKit + +final class SystemBubbleView: ChatBubbleView { + override init(frame: CGRect) { + super.init(frame: frame) + contentMode = .redraw + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Public Method +extension SystemBubbleView { + override func draw(_ rect: CGRect) { + setLeftBubbleView(rect: rect) + } +} diff --git a/ChatBot/ChatBot/View/UserBubbleView.swift b/ChatBot/ChatBot/View/UserBubbleView.swift new file mode 100644 index 00000000..b3ef1006 --- /dev/null +++ b/ChatBot/ChatBot/View/UserBubbleView.swift @@ -0,0 +1,28 @@ +// +// UserBubbleView.swift +// ChatBot +// +// Created by Matthew on 4/12/24. +// + +import UIKit +import Then +import SnapKit + +final class UserBubbleView: ChatBubbleView { + override init(frame: CGRect) { + super.init(frame: frame) + contentMode = .redraw + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Public Method +extension UserBubbleView { + override func draw(_ rect: CGRect) { + setRightBubbleView(rect: rect) + } +} diff --git a/ChatBot/ChatBot/ViewModel/ChatBotViewModel.swift b/ChatBot/ChatBot/ViewModel/ChatBotViewModel.swift new file mode 100644 index 00000000..dd9e0bed --- /dev/null +++ b/ChatBot/ChatBot/ViewModel/ChatBotViewModel.swift @@ -0,0 +1,38 @@ +// +// ChatManager.swift +// ChatBot +// +// Created by LeeSeongYeon on 3/27/24. +// + +import Foundation +import RxSwift +import RxCocoa + +final class ChatBotViewModel { + private let chatRepository: ChatRepository + + init(chatRepository: ChatRepository) { + self.chatRepository = chatRepository + } + + struct Input { + let chatTigger: Observable + } + + struct Output { + let resultChat: Observable> + } + + func transform(input: Input) -> Output { + let resultChat = input.chatTigger.flatMapLatest { [unowned self] message -> Observable> in + return self.chatRepository.requestChatResultData(message: message) + .map { + return .success($0) + } + }.catch { error in + return Observable.just(.failure(error)) + } + return Output(resultChat: resultChat) + } +} diff --git a/ChatBot/ChatBot/ViewModel/ChatRepository.swift b/ChatBot/ChatBot/ViewModel/ChatRepository.swift new file mode 100644 index 00000000..beb8f083 --- /dev/null +++ b/ChatBot/ChatBot/ViewModel/ChatRepository.swift @@ -0,0 +1,23 @@ +// +// Repository.swift +// ChatBot +// +// Created by LeeSeongYeon on 3/26/24. +// + +import Foundation +import RxSwift + +struct ChatRepository { + private let chatBotNetwork: ChatBotNetwork + + init(provider: NetworkProvider) { + self.chatBotNetwork = provider.makeChatNetwork() + } + + func requestChatResultData(message: Message) -> Observable { + self.chatBotNetwork.requestChatBotMessage(message: message).map { + return $0 + } + } +} diff --git a/ChatBot/Podfile b/ChatBot/Podfile new file mode 100644 index 00000000..942af9a0 --- /dev/null +++ b/ChatBot/Podfile @@ -0,0 +1,14 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'ChatBot' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! +pod 'RxSwift', '~> 6.5.0' +pod 'RxCocoa', '~> 6.5.0' +pod 'RxAlamofire' +pod 'SnapKit', '~> 5.7.0' +pod 'Then' + # Pods for ChatBot + +end diff --git a/ChatBot/Podfile.lock b/ChatBot/Podfile.lock new file mode 100644 index 00000000..7f3fbab7 --- /dev/null +++ b/ChatBot/Podfile.lock @@ -0,0 +1,45 @@ +PODS: + - Alamofire (5.9.1) + - RxAlamofire (6.1.1): + - RxAlamofire/Core (= 6.1.1) + - RxAlamofire/Core (6.1.1): + - Alamofire (~> 5.4) + - RxSwift (~> 6.0) + - RxCocoa (6.5.0): + - RxRelay (= 6.5.0) + - RxSwift (= 6.5.0) + - RxRelay (6.5.0): + - RxSwift (= 6.5.0) + - RxSwift (6.5.0) + - SnapKit (5.7.1) + - Then (3.0.0) + +DEPENDENCIES: + - RxAlamofire + - RxCocoa (~> 6.5.0) + - RxSwift (~> 6.5.0) + - SnapKit (~> 5.7.0) + - Then + +SPEC REPOS: + trunk: + - Alamofire + - RxAlamofire + - RxCocoa + - RxRelay + - RxSwift + - SnapKit + - Then + +SPEC CHECKSUMS: + Alamofire: f36a35757af4587d8e4f4bfa223ad10be2422b8c + RxAlamofire: beb75a1c452d0de225651db4903f5d29d034a620 + RxCocoa: 94f817b71c07517321eb4f9ad299112ca8af743b + RxRelay: 1de1523e604c72b6c68feadedd1af3b1b4d0ecbd + RxSwift: 5710a9e6b17f3c3d6e40d6e559b9fa1e813b2ef8 + SnapKit: d612e99e678a2d3b95bf60b0705ed0a35c03484a + Then: 844265ae87834bbe1147d91d5d41a404da2ec27d + +PODFILE CHECKSUM: 7e0d07ea5c428039c896d73e099e3982d8244715 + +COCOAPODS: 1.14.3 diff --git a/ChatBot/Pods/Alamofire/LICENSE b/ChatBot/Pods/Alamofire/LICENSE new file mode 100644 index 00000000..cae030a0 --- /dev/null +++ b/ChatBot/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2022 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ChatBot/Pods/Alamofire/README.md b/ChatBot/Pods/Alamofire/README.md new file mode 100644 index 00000000..3a454ab1 --- /dev/null +++ b/ChatBot/Pods/Alamofire/README.md @@ -0,0 +1,269 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png) + +[![Swift](https://img.shields.io/badge/Swift-5.7_5.8_5.9-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.7_5.8_5.9-Orange?style=flat-square) +[![Platforms](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_visionOS_Linux_Windows_Android-yellowgreen?style=flat-square)](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_vision_OS_Linux_Windows_Android-Green?style=flat-square) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg?style=flat-square)](https://img.shields.io/cocoapods/v/Alamofire.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat-square)](https://github.com/Carthage/Carthage) +[![Swift Package Manager](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square) +[![Swift Forums](https://img.shields.io/badge/Swift_Forums-Alamofire-orange?style=flat-square)](https://forums.swift.org/c/related-projects/alamofire/37) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Contributing](#contributing) +- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire) + - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) +- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests-with-requestinterceptor) + - **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers) + - **Advanced Concurrency -** [Swift Concurrency](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-swift-concurrency) and [Combine](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-combine) + - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6. +- [x] Combine Support +- [x] URL / JSON Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with `URLCredential` +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) + +## Write Requests Fast! + +Alamofire's compact syntax and extensive feature set allow requests with powerful features like automatic retry to be written in just a few lines of code. + +```swift +// Automatic String to URL conversion, Swift concurrency support, and automatic retry. +let response = await AF.request("https://httpbin.org/get", interceptor: .retryPolicy) + // Automatic HTTP Basic Auth. + .authenticate(username: "user", password: "pass") + // Caching customization. + .cacheResponse(using: .cache) + // Redirect customization. + .redirect(using: .follow) + // Validate response code and Content-Type. + .validate() + // Produce a cURL command for the request. + .cURLDescription { description in + print(description) + } + // Automatic Decodable support with background parsing. + .serializingDecodable(DecodableType.self) + // Await the full response with metrics and a parsed body. + .response +// Detailed response description for easy debugging. +debugPrint(response) +``` + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +| Platform | Minimum Swift Version | Installation | Status | +| ---------------------------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------ | +| iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ | 5.7.1 / Xcode 14.1 | [CocoaPods](#cocoapods), [Carthage](#carthage), [Swift Package Manager](#swift-package-manager), [Manual](#manually) | Fully Tested | +| Linux | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | +| Windows | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | +| Android | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | + +#### Known Issues on Linux and Windows + +Alamofire builds on Linux, Windows, and Android but there are missing features and many issues in the underlying `swift-corelibs-foundation` that prevent full functionality and may cause crashes. These include: + +- `ServerTrustManager` and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support. +- Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges. +- Cache control through `CachedResponseHandler` and associated APIs is unavailable, as the underlying delegate methods aren't called. +- `URLSessionTaskMetrics` are never gathered. +- `WebSocketRequest` is not available. + +Due to these issues, Alamofire is unsupported on Linux, Windows, and Android. Please report any crashes to the [Swift bug reporter](https://bugs.swift.org). + +## Migration Guides + +- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md) +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. +- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! + +## Installation + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift` or the Package list in Xcode. + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.9.1")) +] +``` + +Normally you'll want to depend on the `Alamofire` target: + +```swift +.product(name: "Alamofire", package: "Alamofire") +``` + +But if you want to force Alamofire to be dynamically linked (do not do this unless you're sure you need it), you can depend on the `AlamofireDynamic` target: + +```swift +.product(name: "AlamofireDynamic", package: "Alamofire") +``` + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +pod 'Alamofire' +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for macOS. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS`, or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +## Contributing + +Before contributing to Alamofire, please read the instructions detailed in our [contribution guide](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md). + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in the test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. + - (Resolved): 9/1/17 in Xcode 9 beta 6. +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + - (Resolved): Just add `CFNetwork` to your linked frameworks. +- `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS + - (Resolved): Metrics now collected on watchOS 7+. + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Sponsorship + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. +Sponsoring the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate, whether once or monthly, to help us reach our goal would be greatly appreciated. + +[Sponsor Alamofire](https://github.com/sponsors/Alamofire) + +## Supporters + +[MacStadium](https://macstadium.com) provides Alamofire with a free, hosted Mac mini. + +![Powered by MacStadium](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/MacStadiumLogo.png) + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/ChatBot/Pods/Alamofire/Source/Alamofire.swift b/ChatBot/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 00000000..46071970 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,43 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2021 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation +#if canImport(FoundationNetworking) +@_exported import FoundationNetworking +#endif + +// Enforce minimum Swift version for all platforms and build systems. +#if swift(<5.7.1) +#error("Alamofire doesn't support Swift versions below 5.7.1.") +#endif + +/// Reference to `Session.default` for quick bootstrapping and examples. +public let AF = Session.default + +/// Namespace for informational Alamofire values. +public enum AFInfo { + /// Current Alamofire version. + public static let version = "5.9.1" +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/AFError.swift b/ChatBot/Pods/Alamofire/Source/Core/AFError.swift new file mode 100644 index 00000000..cb7aa40b --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/AFError.swift @@ -0,0 +1,874 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if canImport(Security) +import Security +#endif + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +public enum AFError: Error { + /// The underlying reason the `.multipartEncodingFailed` error occurred. + public enum MultipartEncodingFailureReason { + /// The `fileURL` provided for reading an encodable body part isn't a file `URL`. + case bodyPartURLInvalid(url: URL) + /// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension`. + case bodyPartFilenameInvalid(in: URL) + /// The file at the `fileURL` provided was not reachable. + case bodyPartFileNotReachable(at: URL) + /// Attempting to check the reachability of the `fileURL` provided threw an error. + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + /// The file at the `fileURL` provided is actually a directory. + case bodyPartFileIsDirectory(at: URL) + /// The size of the file at the `fileURL` provided was not returned by the system. + case bodyPartFileSizeNotAvailable(at: URL) + /// The attempt to find the size of the file at the `fileURL` provided threw an error. + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + /// An `InputStream` could not be created for the provided `fileURL`. + case bodyPartInputStreamCreationFailed(for: URL) + /// An `OutputStream` could not be created when attempting to write the encoded data to disk. + case outputStreamCreationFailed(for: URL) + /// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`. + case outputStreamFileAlreadyExists(at: URL) + /// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`. + case outputStreamURLInvalid(url: URL) + /// The attempt to write the encoded body data to disk failed with an underlying error. + case outputStreamWriteFailed(error: Error) + /// The attempt to read an encoded body part `InputStream` failed with underlying system error. + case inputStreamReadFailed(error: Error) + } + + /// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be + /// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case. + public struct UnexpectedInputStreamLength: Error { + /// The expected byte count to read. + public var bytesExpected: UInt64 + /// The actual byte count read. + public var bytesRead: UInt64 + } + + /// The underlying reason the `.parameterEncodingFailed` error occurred. + public enum ParameterEncodingFailureReason { + /// The `URLRequest` did not have a `URL` to encode. + case missingURL + /// JSON serialization failed with an underlying system error during the encoding process. + case jsonEncodingFailed(error: Error) + /// Custom parameter encoding failed due to the associated `Error`. + case customEncodingFailed(error: Error) + } + + /// The underlying reason the `.parameterEncoderFailed` error occurred. + public enum ParameterEncoderFailureReason { + /// Possible missing components. + public enum RequiredComponent { + /// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding. + case url + /// The `HTTPMethod` could not be extracted from the passed `URLRequest`. + case httpMethod(rawValue: String) + } + + /// A `RequiredComponent` was missing during encoding. + case missingRequiredComponent(RequiredComponent) + /// The underlying encoder failed with the associated error. + case encoderFailed(error: Error) + } + + /// The underlying reason the `.responseValidationFailed` error occurred. + public enum ResponseValidationFailureReason { + /// The data file containing the server response did not exist. + case dataFileNil + /// The data file containing the server response at the associated `URL` could not be read. + case dataFileReadFailed(at: URL) + /// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a + /// wildcard type. + case missingContentType(acceptableContentTypes: [String]) + /// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`. + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + /// The response status code was not acceptable. + case unacceptableStatusCode(code: Int) + /// Custom response validation failed due to the associated `Error`. + case customValidationFailed(error: Error) + } + + /// The underlying reason the response serialization error occurred. + public enum ResponseSerializationFailureReason { + /// The server response contained no data or the data was zero length. + case inputDataNilOrZeroLength + /// The file containing the server response did not exist. + case inputFileNil + /// The file containing the server response could not be read from the associated `URL`. + case inputFileReadFailed(at: URL) + /// String serialization failed using the provided `String.Encoding`. + case stringSerializationFailed(encoding: String.Encoding) + /// JSON serialization failed with an underlying system error. + case jsonSerializationFailed(error: Error) + /// A `DataDecoder` failed to decode the response due to the associated `Error`. + case decodingFailed(error: Error) + /// A custom response serializer failed due to the associated `Error`. + case customSerializationFailed(error: Error) + /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. + case invalidEmptyResponse(type: String) + } + + #if canImport(Security) + /// Underlying reason a server trust evaluation error occurred. + public enum ServerTrustFailureReason { + /// The output of a server trust evaluation. + public struct Output { + /// The host for which the evaluation was performed. + public let host: String + /// The `SecTrust` value which was evaluated. + public let trust: SecTrust + /// The `OSStatus` of evaluation operation. + public let status: OSStatus + /// The result of the evaluation operation. + public let result: SecTrustResultType + + /// Creates an `Output` value from the provided values. + init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) { + self.host = host + self.trust = trust + self.status = status + self.result = result + } + } + + /// No `ServerTrustEvaluator` was found for the associated host. + case noRequiredEvaluator(host: String) + /// No certificates were found with which to perform the trust evaluation. + case noCertificatesFound + /// No public keys were found with which to perform the trust evaluation. + case noPublicKeysFound + /// During evaluation, application of the associated `SecPolicy` failed. + case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus) + /// During evaluation, setting the associated anchor certificates failed. + case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate]) + /// During evaluation, creation of the revocation policy failed. + case revocationPolicyCreationFailed + /// `SecTrust` evaluation failed with the associated `Error`, if one was produced. + case trustEvaluationFailed(error: Error?) + /// Default evaluation failed with the associated `Output`. + case defaultEvaluationFailed(output: Output) + /// Host validation failed with the associated `Output`. + case hostValidationFailed(output: Output) + /// Revocation check failed with the associated `Output` and options. + case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options) + /// Certificate pinning failed. + case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate]) + /// Public key pinning failed. + case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey]) + /// Custom server trust evaluation failed due to the associated `Error`. + case customEvaluationFailed(error: Error) + } + #endif + + /// The underlying reason the `.urlRequestValidationFailed` error occurred. + public enum URLRequestValidationFailureReason { + /// URLRequest with GET method had body data. + case bodyDataInGETRequest(Data) + } + + /// `UploadableConvertible` threw an error in `createUploadable()`. + case createUploadableFailed(error: Error) + /// `URLRequestConvertible` threw an error in `asURLRequest()`. + case createURLRequestFailed(error: Error) + /// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL. + case downloadedFileMoveFailed(error: Error, source: URL, destination: URL) + /// `Request` was explicitly cancelled. + case explicitlyCancelled + /// `URLConvertible` type failed to create a valid `URL`. + case invalidURL(url: URLConvertible) + /// Multipart form encoding failed. + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + /// `ParameterEncoding` threw an error during the encoding process. + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + /// `ParameterEncoder` threw an error while running the encoder. + case parameterEncoderFailed(reason: ParameterEncoderFailureReason) + /// `RequestAdapter` threw an error during adaptation. + case requestAdaptationFailed(error: Error) + /// `RequestRetrier` threw an error during the request retry process. + case requestRetryFailed(retryError: Error, originalError: Error) + /// Response validation failed. + case responseValidationFailed(reason: ResponseValidationFailureReason) + /// Response serialization failed. + case responseSerializationFailed(reason: ResponseSerializationFailureReason) + #if canImport(Security) + /// `ServerTrustEvaluating` instance threw an error during trust evaluation. + case serverTrustEvaluationFailed(reason: ServerTrustFailureReason) + #endif + /// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope. + case sessionDeinitialized + /// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`. + case sessionInvalidated(error: Error?) + /// `URLSessionTask` completed with error. + case sessionTaskFailed(error: Error) + /// `URLRequest` failed validation. + case urlRequestValidationFailed(reason: URLRequestValidationFailureReason) +} + +extension Error { + /// Returns the instance cast as an `AFError`. + public var asAFError: AFError? { + self as? AFError + } + + /// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown. + public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError { + guard let afError = self as? AFError else { + fatalError(message(), file: file, line: line) + } + return afError + } + + /// Casts the instance as `AFError` or returns `defaultAFError` + func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError { + self as? AFError ?? defaultAFError() + } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the instance is `.sessionDeinitialized`. + public var isSessionDeinitializedError: Bool { + if case .sessionDeinitialized = self { return true } + return false + } + + /// Returns whether the instance is `.sessionInvalidated`. + public var isSessionInvalidatedError: Bool { + if case .sessionInvalidated = self { return true } + return false + } + + /// Returns whether the instance is `.explicitlyCancelled`. + public var isExplicitlyCancelledError: Bool { + if case .explicitlyCancelled = self { return true } + return false + } + + /// Returns whether the instance is `.invalidURL`. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncoderError: Bool { + if case .parameterEncoderFailed = self { return true } + return false + } + + /// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError` + /// properties will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestAdaptationError: Bool { + if case .requestAdaptationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } + + #if canImport(Security) + /// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isServerTrustEvaluationError: Bool { + if case .serverTrustEvaluationFailed = self { return true } + return false + } + #endif + + /// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isRequestRetryError: Bool { + if case .requestRetryFailed = self { return true } + return false + } + + /// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateUploadableError: Bool { + if case .createUploadableFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isCreateURLRequestError: Bool { + if case .createURLRequestFailed = self { return true } + return false + } + + /// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will + /// contain the associated values. + public var isDownloadedFileMoveError: Bool { + if case .downloadedFileMoveFailed = self { return true } + return false + } + + /// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isSessionTaskError: Bool { + if case .sessionTaskFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + guard case let .invalidURL(url) = self else { return nil } + return url + } + + /// The `URL` associated with the error. + public var url: URL? { + guard case let .multipartEncodingFailed(reason) = self else { return nil } + return reason.url + } + + /// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`, + /// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`, + /// `.responseSerializationFailed`, `.requestRetryFailed` errors. + public var underlyingError: Error? { + switch self { + case let .multipartEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncodingFailed(reason): + return reason.underlyingError + case let .parameterEncoderFailed(reason): + return reason.underlyingError + case let .requestAdaptationFailed(error): + return error + case let .requestRetryFailed(retryError, _): + return retryError + case let .responseValidationFailed(reason): + return reason.underlyingError + case let .responseSerializationFailed(reason): + return reason.underlyingError + #if canImport(Security) + case let .serverTrustEvaluationFailed(reason): + return reason.underlyingError + #endif + case let .sessionInvalidated(error): + return error + case let .createUploadableFailed(error): + return error + case let .createURLRequestFailed(error): + return error + case let .downloadedFileMoveFailed(error, _, _): + return error + case let .sessionTaskFailed(error): + return error + case .explicitlyCancelled, + .invalidURL, + .sessionDeinitialized, + .urlRequestValidationFailed: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.acceptableContentTypes + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseContentType + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + guard case let .responseValidationFailed(reason) = self else { return nil } + return reason.responseCode + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + guard case let .responseSerializationFailed(reason) = self else { return nil } + return reason.failedStringEncoding + } + + /// The `source` URL of a `.downloadedFileMoveFailed` error. + public var sourceURL: URL? { + guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil } + return source + } + + /// The `destination` URL of a `.downloadedFileMoveFailed` error. + public var destinationURL: URL? { + guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil } + return destination + } + + #if canImport(Security) + /// The download resume data of any underlying network error. Only produced by `DownloadRequest`s. + public var downloadResumeData: Data? { + (underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data + } + #endif +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case let .jsonEncodingFailed(error), + let .customEncodingFailed(error): + return error + case .missingURL: + return nil + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var underlyingError: Error? { + switch self { + case let .encoderFailed(error): + return error + case .missingRequiredComponent: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case let .bodyPartURLInvalid(url), + let .bodyPartFilenameInvalid(url), + let .bodyPartFileNotReachable(url), + let .bodyPartFileIsDirectory(url), + let .bodyPartFileSizeNotAvailable(url), + let .bodyPartInputStreamCreationFailed(url), + let .outputStreamCreationFailed(url), + let .outputStreamFileAlreadyExists(url), + let .outputStreamURLInvalid(url), + let .bodyPartFileNotReachableWithError(url, _), + let .bodyPartFileSizeQueryFailedWithError(url, _): + return url + case .outputStreamWriteFailed, + .inputStreamReadFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .bodyPartFileNotReachableWithError(_, error), + let .bodyPartFileSizeQueryFailedWithError(_, error), + let .outputStreamWriteFailed(error), + let .inputStreamReadFailed(error): + return error + case .bodyPartURLInvalid, + .bodyPartFilenameInvalid, + .bodyPartFileNotReachable, + .bodyPartFileIsDirectory, + .bodyPartFileSizeNotAvailable, + .bodyPartInputStreamCreationFailed, + .outputStreamCreationFailed, + .outputStreamFileAlreadyExists, + .outputStreamURLInvalid: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case let .missingContentType(types), + let .unacceptableContentType(types, _): + return types + case .dataFileNil, + .dataFileReadFailed, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseContentType: String? { + switch self { + case let .unacceptableContentType(_, responseType): + return responseType + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableStatusCode, + .customValidationFailed: + return nil + } + } + + var responseCode: Int? { + switch self { + case let .unacceptableStatusCode(code): + return code + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .customValidationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customValidationFailed(error): + return error + case .dataFileNil, + .dataFileReadFailed, + .missingContentType, + .unacceptableContentType, + .unacceptableStatusCode: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case let .stringSerializationFailed(encoding): + return encoding + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed(_), + .jsonSerializationFailed(_), + .decodingFailed(_), + .customSerializationFailed(_), + .invalidEmptyResponse: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .jsonSerializationFailed(error), + let .decodingFailed(error), + let .customSerializationFailed(error): + return error + case .inputDataNilOrZeroLength, + .inputFileNil, + .inputFileReadFailed, + .stringSerializationFailed, + .invalidEmptyResponse: + return nil + } + } +} + +#if canImport(Security) +extension AFError.ServerTrustFailureReason { + var output: AFError.ServerTrustFailureReason.Output? { + switch self { + case let .defaultEvaluationFailed(output), + let .hostValidationFailed(output), + let .revocationCheckFailed(output, _): + return output + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .trustEvaluationFailed, + .certificatePinningFailed, + .publicKeyPinningFailed, + .customEvaluationFailed: + return nil + } + } + + var underlyingError: Error? { + switch self { + case let .customEvaluationFailed(error): + return error + case let .trustEvaluationFailed(error): + return error + case .noRequiredEvaluator, + .noCertificatesFound, + .noPublicKeysFound, + .policyApplicationFailed, + .settingAnchorCertificatesFailed, + .revocationPolicyCreationFailed, + .defaultEvaluationFailed, + .hostValidationFailed, + .revocationCheckFailed, + .certificatePinningFailed, + .publicKeyPinningFailed: + return nil + } + } +} +#endif + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .explicitlyCancelled: + return "Request explicitly cancelled." + case let .invalidURL(url): + return "URL is not valid: \(url)" + case let .parameterEncodingFailed(reason): + return reason.localizedDescription + case let .parameterEncoderFailed(reason): + return reason.localizedDescription + case let .multipartEncodingFailed(reason): + return reason.localizedDescription + case let .requestAdaptationFailed(error): + return "Request adaption failed with error: \(error.localizedDescription)" + case let .responseValidationFailed(reason): + return reason.localizedDescription + case let .responseSerializationFailed(reason): + return reason.localizedDescription + case let .requestRetryFailed(retryError, originalError): + return """ + Request retry failed with retry error: \(retryError.localizedDescription), \ + original error: \(originalError.localizedDescription) + """ + case .sessionDeinitialized: + return """ + Session was invalidated without error, so it was likely deinitialized unexpectedly. \ + Be sure to retain a reference to your Session for the duration of your requests. + """ + case let .sessionInvalidated(error): + return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")" + #if canImport(Security) + case let .serverTrustEvaluationFailed(reason): + return "Server trust evaluation failed due to reason: \(reason.localizedDescription)" + #endif + case let .urlRequestValidationFailed(reason): + return "URLRequest validation failed due to reason: \(reason.localizedDescription)" + case let .createUploadableFailed(error): + return "Uploadable creation failed with error: \(error.localizedDescription)" + case let .createURLRequestFailed(error): + return "URLRequest creation failed with error: \(error.localizedDescription)" + case let .downloadedFileMoveFailed(error, source, destination): + return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)" + case let .sessionTaskFailed(error): + return "URLSessionTask failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case let .jsonEncodingFailed(error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case let .customEncodingFailed(error): + return "Custom parameter encoder failed with error: \(error.localizedDescription)" + } + } +} + +extension AFError.ParameterEncoderFailureReason { + var localizedDescription: String { + switch self { + case let .missingRequiredComponent(component): + return "Encoding failed due to a missing request component: \(component)" + case let .encoderFailed(error): + return "The underlying encoder failed with the error: \(error)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case let .bodyPartURLInvalid(url): + return "The URL provided is not a file URL: \(url)" + case let .bodyPartFilenameInvalid(url): + return "The URL provided does not have a valid filename: \(url)" + case let .bodyPartFileNotReachable(url): + return "The URL provided is not reachable: \(url)" + case let .bodyPartFileNotReachableWithError(url, error): + return """ + The system returned an error while checking the provided URL for reachability. + URL: \(url) + Error: \(error) + """ + case let .bodyPartFileIsDirectory(url): + return "The URL provided is a directory: \(url)" + case let .bodyPartFileSizeNotAvailable(url): + return "Could not fetch the file size from the provided URL: \(url)" + case let .bodyPartFileSizeQueryFailedWithError(url, error): + return """ + The system returned an error while attempting to fetch the file size from the provided URL. + URL: \(url) + Error: \(error) + """ + case let .bodyPartInputStreamCreationFailed(url): + return "Failed to create an InputStream for the provided URL: \(url)" + case let .outputStreamCreationFailed(url): + return "Failed to create an OutputStream for URL: \(url)" + case let .outputStreamFileAlreadyExists(url): + return "A file already exists at the provided URL: \(url)" + case let .outputStreamURLInvalid(url): + return "The provided OutputStream URL is invalid: \(url)" + case let .outputStreamWriteFailed(error): + return "OutputStream write failed with error: \(error)" + case let .inputStreamReadFailed(error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case let .inputFileReadFailed(url): + return "Response could not be serialized, input file could not be read: \(url)." + case let .stringSerializationFailed(encoding): + return "String could not be serialized with encoding: \(encoding)." + case let .jsonSerializationFailed(error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case let .invalidEmptyResponse(type): + return """ + Empty response could not be serialized to type: \(type). \ + Use Empty as the expected type for such responses. + """ + case let .decodingFailed(error): + return "Response could not be decoded because of error:\n\(error.localizedDescription)" + case let .customSerializationFailed(error): + return "Custom response serializer failed with error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case let .dataFileReadFailed(url): + return "Response could not be validated, data file could not be read: \(url)." + case let .missingContentType(types): + return """ + Response Content-Type was missing and acceptable content types \ + (\(types.joined(separator: ","))) do not match "*/*". + """ + case let .unacceptableContentType(acceptableTypes, responseType): + return """ + Response Content-Type "\(responseType)" does not match any acceptable types: \ + \(acceptableTypes.joined(separator: ",")). + """ + case let .unacceptableStatusCode(code): + return "Response status code was unacceptable: \(code)." + case let .customValidationFailed(error): + return "Custom response validation failed with error: \(error.localizedDescription)" + } + } +} + +#if canImport(Security) +extension AFError.ServerTrustFailureReason { + var localizedDescription: String { + switch self { + case let .noRequiredEvaluator(host): + return "A ServerTrustEvaluating value is required for host \(host) but none was found." + case .noCertificatesFound: + return "No certificates were found or provided for evaluation." + case .noPublicKeysFound: + return "No public keys were found or provided for evaluation." + case .policyApplicationFailed: + return "Attempting to set a SecPolicy failed." + case .settingAnchorCertificatesFailed: + return "Attempting to set the provided certificates as anchor certificates failed." + case .revocationPolicyCreationFailed: + return "Attempting to create a revocation policy failed." + case let .trustEvaluationFailed(error): + return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")" + case let .defaultEvaluationFailed(output): + return "Default evaluation failed for host \(output.host)." + case let .hostValidationFailed(output): + return "Host validation failed for host \(output.host)." + case let .revocationCheckFailed(output, _): + return "Revocation check failed for host \(output.host)." + case let .certificatePinningFailed(host, _, _, _): + return "Certificate pinning failed for host \(host)." + case let .publicKeyPinningFailed(host, _, _, _): + return "Public key pinning failed for host \(host)." + case let .customEvaluationFailed(error): + return "Custom trust evaluation failed with error: \(error.localizedDescription)" + } + } +} +#endif + +extension AFError.URLRequestValidationFailureReason { + var localizedDescription: String { + switch self { + case let .bodyDataInGETRequest(data): + return """ + Invalid URLRequest: Requests with GET method cannot have body data: + \(String(decoding: data, as: UTF8.self)) + """ + } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/DataRequest.swift b/ChatBot/Pods/Alamofire/Source/Core/DataRequest.swift new file mode 100644 index 00000000..e282ee53 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/DataRequest.swift @@ -0,0 +1,448 @@ +// +// DataRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`. +public class DataRequest: Request { + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: URLRequestConvertible + /// `Data` read from the server so far. + public var data: Data? { dataMutableState.data } + + private struct DataMutableState { + var data: Data? + var httpResponseHandler: (queue: DispatchQueue, + handler: (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)? + } + + private let dataMutableState = Protected(DataMutableState()) + + /// Creates a `DataRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + dataMutableState.write { mutableState in + mutableState.data = nil + } + } + + /// Called when `Data` is received by this instance. + /// + /// - Note: Also calls `updateDownloadProgress`. + /// + /// - Parameter data: The `Data` received. + func didReceive(data: Data) { + dataMutableState.write { mutableState in + if mutableState.data == nil { + mutableState.data = data + } else { + mutableState.data?.append(data) + } + } + + updateDownloadProgress() + } + + func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + dataMutableState.read { dataMutableState in + guard let httpResponseHandler = dataMutableState.httpResponseHandler else { + underlyingQueue.async { completionHandler(.allow) } + return + } + + httpResponseHandler.queue.async { + httpResponseHandler.handler(response) { disposition in + if disposition == .cancel { + self.mutableState.write { mutableState in + mutableState.state = .cancelled + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + } + + self.underlyingQueue.async { + completionHandler(disposition.sessionDisposition) + } + } + } + } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + /// Called to update the `downloadProgress` of the instance. + func updateDownloadProgress() { + let totalBytesReceived = Int64(data?.count ?? 0) + let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + downloadProgress.totalUnitCount = totalBytesExpected + downloadProgress.completedUnitCount = totalBytesReceived + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure used to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response else { return } + + let result = validation(request, response, data) + + if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + data: data, + withResult: result) + } + + validators.write { $0.append(validator) } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion + /// handler to return a `ResponseDisposition` value. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided + /// MUST be called, otherwise the request will never complete. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse( + on queue: DispatchQueue = .main, + perform handler: @escaping (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void + ) -> Self { + dataMutableState.write { mutableState in + mutableState.httpResponseHandler = (queue, handler) + } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(on queue: DispatchQueue = .main, + perform handler: @escaping (HTTPURLResponse) -> Void) -> Self { + onHTTPResponse(on: queue) { response, completionHandler in + handler(response) + completionHandler(.allow) + } + + return self + } + + // MARK: Response Serialization + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.data, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serialize(request: self.request, + response: self.response, + data: self.data, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DataResponse(request: self.request, + response: self.response, + data: self.data, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDataResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } + + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDataResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/DataStreamRequest.swift b/ChatBot/Pods/Alamofire/Source/Core/DataStreamRequest.swift new file mode 100644 index 00000000..fd11ca00 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/DataStreamRequest.swift @@ -0,0 +1,584 @@ +// +// DataStreamRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure. +public final class DataStreamRequest: Request { + /// Closure type handling `DataStreamRequest.Stream` values. + public typealias Handler = (Stream) throws -> Void + + /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used + /// to stop the stream at any time. + public struct Stream { + /// Latest `Event` from the stream. + public let event: Event + /// Token used to cancel the stream. + public let token: CancellationToken + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + token.cancel() + } + } + + /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed + /// `Data` or the completion of the stream. + public enum Event { + /// Output produced every time the instance receives additional `Data`. The associated value contains the + /// `Result` of processing the incoming `Data`. + case stream(Result) + /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error. + /// Associated `Completion` value contains the final state. + case complete(Completion) + } + + /// Value containing the state of a `DataStreamRequest` when the stream was completed. + public struct Completion { + /// Last `URLRequest` issued by the instance. + public let request: URLRequest? + /// Last `HTTPURLResponse` received by the instance. + public let response: HTTPURLResponse? + /// Last `URLSessionTaskMetrics` produced for the instance. + public let metrics: URLSessionTaskMetrics? + /// `AFError` produced for the instance, if any. + public let error: AFError? + } + + /// Type used to cancel an ongoing stream. + public struct CancellationToken { + weak var request: DataStreamRequest? + + init(_ request: DataStreamRequest) { + self.request = request + } + + /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`. + public func cancel() { + request?.cancel() + } + } + + /// `URLRequestConvertible` value used to create `URLRequest`s for this instance. + public let convertible: URLRequestConvertible + /// Whether or not the instance will be cancelled if stream parsing encounters an error. + public let automaticallyCancelOnStreamError: Bool + + /// Internal mutable state specific to this type. + struct StreamMutableState { + /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called. + var outputStream: OutputStream? + /// Stream closures called as `Data` is received. + var streams: [(_ data: Data) -> Void] = [] + /// Number of currently executing streams. Used to ensure completions are only fired after all streams are + /// enqueued. + var numberOfExecutingStreams = 0 + /// Completion calls enqueued while streams are still executing. + var enqueuedCompletionEvents: [() -> Void] = [] + /// Handler for any `HTTPURLResponse`s received. + var httpResponseHandler: (queue: DispatchQueue, + handler: (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)? + } + + let streamMutableState = Protected(StreamMutableState()) + + /// Creates a `DataStreamRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` + /// by default. + /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this + /// instance. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error` + /// is thrown while serializing stream `Data`. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default + /// targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by + /// the `Request`. + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + automaticallyCancelOnStreamError: Bool, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + let copiedRequest = request + return session.dataTask(with: copiedRequest) + } + + override func finish(error: AFError? = nil) { + streamMutableState.write { state in + state.outputStream?.close() + } + + super.finish(error: error) + } + + func didReceive(data: Data) { + streamMutableState.write { state in + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + if let stream = state.outputStream { + underlyingQueue.async { + var bytes = Array(data) + stream.write(&bytes, maxLength: bytes.count) + } + } + #endif + state.numberOfExecutingStreams += state.streams.count + let localState = state + underlyingQueue.async { localState.streams.forEach { $0(data) } } + } + } + + func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + streamMutableState.read { dataMutableState in + guard let httpResponseHandler = dataMutableState.httpResponseHandler else { + underlyingQueue.async { completionHandler(.allow) } + return + } + + httpResponseHandler.queue.async { + httpResponseHandler.handler(response) { disposition in + if disposition == .cancel { + self.mutableState.write { mutableState in + mutableState.state = .cancelled + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + } + + self.underlyingQueue.async { + completionHandler(disposition.sessionDisposition) + } + } + } + } + } + + /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure. + /// + /// - Parameter validation: `Validation` closure used to validate the request and response. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response else { return } + + let result = validation(request, response) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + withResult: result) + } + + validators.write { $0.append(validator) } + + return self + } + + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + /// Produces an `InputStream` that receives the `Data` received by the instance. + /// + /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`. + /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or + /// not the creating session has `startRequestsImmediately` set to `true`. + /// + /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`. + /// + /// - Returns: The `InputStream` bound to the internal `OutboundStream`. + public func asInputStream(bufferSize: Int = 1024) -> InputStream? { + defer { resume() } + + var inputStream: InputStream? + streamMutableState.write { state in + Foundation.Stream.getBoundStreams(withBufferSize: bufferSize, + inputStream: &inputStream, + outputStream: &state.outputStream) + state.outputStream?.open() + } + + return inputStream + } + #endif + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion + /// handler to return a `ResponseDisposition` value. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided + /// MUST be called, otherwise the request will never complete. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse( + on queue: DispatchQueue = .main, + perform handler: @escaping (_ response: HTTPURLResponse, + _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void + ) -> Self { + streamMutableState.write { mutableState in + mutableState.httpResponseHandler = (queue, handler) + } + + return self + } + + /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default. + /// - handler: Closure called when the instance produces an `HTTPURLResponse`. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(on queue: DispatchQueue = .main, + perform handler: @escaping (HTTPURLResponse) -> Void) -> Self { + onHTTPResponse(on: queue) { response, completionHandler in + handler(response) + completionHandler(.allow) + } + + return self + } + + func capturingError(from closure: () throws -> Void) { + do { + try closure() + } catch { + self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + cancel() + } + } + + func appendStreamCompletion(on queue: DispatchQueue, + stream: @escaping Handler) { + appendResponseSerializer { + self.underlyingQueue.async { + self.responseSerializerDidComplete { + self.streamMutableState.write { state in + guard state.numberOfExecutingStreams == 0 else { + state.enqueuedCompletionEvents.append { + self.enqueueCompletion(on: queue, stream: stream) + } + + return + } + + self.enqueueCompletion(on: queue, stream: stream) + } + } + } + } + } + + func enqueueCompletion(on queue: DispatchQueue, + stream: @escaping Handler) { + queue.async { + do { + let completion = Completion(request: self.request, + response: self.response, + metrics: self.metrics, + error: self.error) + try stream(.init(event: .complete(completion), token: .init(self))) + } catch { + // Ignore error, as errors on Completion can't be handled anyway. + } + } + } + + // MARK: Response Serialization + + /// Adds a `StreamHandler` which performs no parsing on incoming `Data`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(data)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + + streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStream(using serializer: Serializer, + on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let result = Result { try serializer.serialize(data) } + .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) } + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: result) + + if result.isFailure, self.automaticallyCancelOnStreamError { + self.cancel() + } + + queue.async { + self.capturingError { + try stream(.init(event: .stream(result), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStreamString(on queue: DispatchQueue = .main, + stream: @escaping Handler) -> Self { + let parser = { [unowned self] (data: Data) in + serializationQueue.async { + // Start work on serialization queue. + let string = String(decoding: data, as: UTF8.self) + // End work on serialization queue. + self.underlyingQueue.async { + self.eventMonitor?.request(self, didParseStream: .success(string)) + + queue.async { + self.capturingError { + try stream(.init(event: .stream(.success(string)), token: .init(self))) + } + + self.updateAndCompleteIfPossible() + } + } + } + } + + streamMutableState.write { $0.streams.append(parser) } + appendStreamCompletion(on: queue, stream: stream) + + return self + } + + private func updateAndCompleteIfPossible() { + streamMutableState.write { state in + state.numberOfExecutingStreams -= 1 + + guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return } + + let completionEvents = state.enqueuedCompletionEvents + self.underlyingQueue.async { completionEvents.forEach { $0() } } + state.enqueuedCompletionEvents.removeAll() + } + } + + /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`. + /// + /// - Parameters: + /// - type: `Decodable` type to parse incoming `Data` into. + /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure. + /// - decoder: `DataDecoder` used to decode the incoming `Data`. + /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`. + /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times. + /// + /// - Returns: The `DataStreamRequest`. + @discardableResult + public func responseStreamDecodable(of type: T.Type = T.self, + on queue: DispatchQueue = .main, + using decoder: DataDecoder = JSONDecoder(), + preprocessor: DataPreprocessor = PassthroughPreprocessor(), + stream: @escaping Handler) -> Self { + responseStream(using: DecodableStreamSerializer(decoder: decoder, dataPreprocessor: preprocessor), + stream: stream) + } +} + +extension DataStreamRequest.Stream { + /// Incoming `Result` values from `Event.stream`. + public var result: Result? { + guard case let .stream(result) = event else { return nil } + + return result + } + + /// `Success` value of the instance, if any. + public var value: Success? { + guard case let .success(value) = result else { return nil } + + return value + } + + /// `Failure` value of the instance, if any. + public var error: Failure? { + guard case let .failure(error) = result else { return nil } + + return error + } + + /// `Completion` value of the instance, if any. + public var completion: DataStreamRequest.Completion? { + guard case let .complete(completion) = event else { return nil } + + return completion + } +} + +// MARK: - Serialization + +/// A type which can serialize incoming `Data`. +public protocol DataStreamSerializer { + /// Type produced from the serialized `Data`. + associatedtype SerializedObject + + /// Serializes incoming `Data` into a `SerializedObject` value. + /// + /// - Parameter data: `Data` to be serialized. + /// + /// - Throws: Any error produced during serialization. + func serialize(_ data: Data) throws -> SerializedObject +} + +/// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`. +public struct DecodableStreamSerializer: DataStreamSerializer { + /// `DataDecoder` used to decode incoming `Data`. + public let decoder: DataDecoder + /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`. + public let dataPreprocessor: DataPreprocessor + + /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`. + /// - Parameters: + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public init(decoder: DataDecoder = JSONDecoder(), dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) { + self.decoder = decoder + self.dataPreprocessor = dataPreprocessor + } + + public func serialize(_ data: Data) throws -> T { + let processedData = try dataPreprocessor.preprocess(data) + do { + return try decoder.decode(T.self, from: processedData) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +/// `DataStreamSerializer` which performs no serialization on incoming `Data`. +public struct PassthroughStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> Data { data } +} + +/// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values. +public struct StringStreamSerializer: DataStreamSerializer { + /// Creates an instance. + public init() {} + + public func serialize(_ data: Data) throws -> String { + String(decoding: data, as: UTF8.self) + } +} + +extension DataStreamSerializer { + /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from stream data. + /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default. + /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the + /// `decoder`. `PassthroughPreprocessor()` by default. + public static func decodable(of type: T.Type, + decoder: DataDecoder = JSONDecoder(), + dataPreprocessor: DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer { + DecodableStreamSerializer(decoder: decoder, dataPreprocessor: dataPreprocessor) + } +} + +extension DataStreamSerializer where Self == PassthroughStreamSerializer { + /// Provides a `PassthroughStreamSerializer` instance. + public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() } +} + +extension DataStreamSerializer where Self == StringStreamSerializer { + /// Provides a `StringStreamSerializer` instance. + public static var string: StringStreamSerializer { StringStreamSerializer() } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/DownloadRequest.swift b/ChatBot/Pods/Alamofire/Source/Core/DownloadRequest.swift new file mode 100644 index 00000000..556c43ea --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/DownloadRequest.swift @@ -0,0 +1,588 @@ +// +// DownloadRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`. +public final class DownloadRequest: Request { + /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination + /// `URL`. + public struct Options: OptionSet { + /// Specifies that intermediate directories for the destination URL should be created. + public static let createIntermediateDirectories = Options(rawValue: 1 << 0) + /// Specifies that any previous file at the destination `URL` should be removed. + public static let removePreviousFile = Options(rawValue: 1 << 1) + + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + } + + // MARK: Destination + + /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + /// + /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not + /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory. + public typealias Destination = (_ temporaryURL: URL, + _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - Parameters: + /// - directory: The search path directory. `.documentDirectory` by default. + /// - domain: The search path domain mask. `.userDomainMask` by default. + /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by + /// default. + /// - Returns: The `Destination` closure. + public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask, + options: Options = []) -> Destination { + { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL + + return (url, options) + } + } + + /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends + /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files + /// with this destination must be additionally moved if they should survive the system reclamation of temporary + /// space. + static let defaultDestination: Destination = { url, _ in + (defaultDestinationURL(url), []) + } + + /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the + /// provided file name. + static let defaultDestinationURL: (URL) -> URL = { url in + let filename = "Alamofire_\(url.lastPathComponent)" + let destination = url.deletingLastPathComponent().appendingPathComponent(filename) + + return destination + } + + // MARK: Downloadable + + /// Type describing the source used to create the underlying `URLSessionDownloadTask`. + public enum Downloadable { + /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. + case request(URLRequestConvertible) + /// Download should be started from the associated resume `Data` value. + case resumeData(Data) + } + + // MARK: Mutable State + + /// Type containing all mutable state for `DownloadRequest` instances. + private struct DownloadRequestMutableState { + /// Possible resume `Data` produced when cancelling the instance. + var resumeData: Data? + /// `URL` to which `Data` is being downloaded. + var fileURL: URL? + } + + /// Protected mutable state specific to `DownloadRequest`. + private let mutableDownloadState = Protected(DownloadRequestMutableState()) + + /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download + /// using the `download(resumingWith data:)` API. + /// + /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel). + public var resumeData: Data? { + #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation. + return mutableDownloadState.resumeData ?? error?.downloadResumeData + #else + return mutableDownloadState.resumeData + #endif + } + + /// If the download is successful, the `URL` where the file was downloaded. + public var fileURL: URL? { mutableDownloadState.fileURL } + + // MARK: Initial State + + /// `Downloadable` value used for this instance. + public let downloadable: Downloadable + /// The `Destination` to which the downloaded file is moved. + let destination: Destination + + /// Creates a `DownloadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request` + /// - destination: `Destination` closure used to move the downloaded file to its final location. + init(id: UUID = UUID(), + downloadable: Downloadable, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate, + destination: @escaping Destination) { + self.downloadable = downloadable + self.destination = destination + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func reset() { + super.reset() + + mutableDownloadState.write { + $0.resumeData = nil + $0.fileURL = nil + } + } + + /// Called when a download has finished. + /// + /// - Parameters: + /// - task: `URLSessionTask` that finished the download. + /// - result: `Result` of the automatic move to `destination`. + func didFinishDownloading(using task: URLSessionTask, with result: Result) { + eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result) + + switch result { + case let .success(url): mutableDownloadState.fileURL = url + case let .failure(error): self.error = error + } + } + + /// Updates the `downloadProgress` using the provided values. + /// + /// - Parameters: + /// - bytesWritten: Total bytes written so far. + /// - totalBytesExpectedToWrite: Total bytes expected to write. + func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) { + downloadProgress.totalUnitCount = totalBytesExpectedToWrite + downloadProgress.completedUnitCount += bytesWritten + + downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) } + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + session.downloadTask(with: request) + } + + /// Creates a `URLSessionTask` from the provided resume data. + /// + /// - Parameters: + /// - data: `Data` used to resume the download. + /// - session: `URLSession` used to create the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask { + session.downloadTask(withResumeData: data) + } + + /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended. + /// + /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use + /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`. + /// + /// - Returns: The instance. + @discardableResult + override public func cancel() -> Self { + cancel(producingResumeData: false) + } + + /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be + /// resumed or suspended. + /// + /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if + /// available. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self { + cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil) + } + + /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed + /// or suspended. + /// + /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData` + /// property. + /// + /// - Parameter completionHandler: The completion handler that is called when the download has been successfully + /// cancelled. It is not guaranteed to be called on a particular queue, so you may + /// want use an appropriate queue to perform your work. + /// + /// - Returns: The instance. + @discardableResult + public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self { + cancel(optionallyProducingResumeData: completionHandler) + } + + /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed, + /// cancellation is performed without producing resume data. + /// + /// - Parameter completionHandler: Optional resume data handler. + /// + /// - Returns: The instance. + private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + if let completionHandler { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel { resumeData in + self.mutableDownloadState.resumeData = resumeData + self.underlyingQueue.async { self.didCancelTask(task) } + completionHandler(resumeData) + } + } else { + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + self.underlyingQueue.async { self.didCancelTask(task) } + } + } + + return self + } + + /// Validates the request, using the specified closure. + /// + /// - Note: If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter validation: `Validation` closure to validate the response. + /// + /// - Returns: The instance. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validator: () -> Void = { [unowned self] in + guard error == nil, let response else { return } + + let result = validation(request, response, fileURL) + + if case let .failure(error) = result { + self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) + } + + eventMonitor?.request(self, + didValidateRequest: request, + response: response, + fileURL: fileURL, + withResult: result) + } + + validators.write { $0.append(validator) } + + return self + } + + // MARK: - Response Serialization + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let result = AFResult(value: self.fileURL, error: self.error) + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: 0, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + } + } + + return self + } + + private func _response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + appendResponseSerializer { + // Start work that should be on the serialization queue. + let start = ProcessInfo.processInfo.systemUptime + let result: AFResult = Result { + try responseSerializer.serializeDownload(request: self.request, + response: self.response, + fileURL: self.fileURL, + error: self.error) + }.mapError { error in + error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error))) + } + let end = ProcessInfo.processInfo.systemUptime + // End work that should be on the serialization queue. + + self.underlyingQueue.async { + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + self.eventMonitor?.request(self, didParseResponse: response) + + guard let serializerError = result.failure, let delegate = self.delegate else { + self.responseSerializerDidComplete { queue.async { completionHandler(response) } } + return + } + + delegate.retryResult(for: self, dueTo: serializerError) { retryResult in + var didComplete: (() -> Void)? + + defer { + if let didComplete { + self.responseSerializerDidComplete { queue.async { didComplete() } } + } + } + + switch retryResult { + case .doNotRetry: + didComplete = { completionHandler(response) } + + case let .doNotRetryWithError(retryError): + let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + + let response = DownloadResponse(request: self.request, + response: self.response, + fileURL: self.fileURL, + resumeData: self.resumeData, + metrics: self.metrics, + serializationDuration: end - start, + result: result) + + didComplete = { completionHandler(response) } + + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - responseSerializer: The response serializer responsible for serializing the request, response, and data + /// contained in the destination `URL`. + /// - completionHandler: The code to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func response(queue: DispatchQueue = .main, + responseSerializer: Serializer, + completionHandler: @escaping (AFDownloadResponse) -> Void) + -> Self { + _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) + } + + /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseURL(queue: DispatchQueue = .main, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler) + } + + /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is called. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseData(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseString(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } + + /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments` + /// by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.") + @discardableResult + public func responseJSON(queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options), + completionHandler: completionHandler) + } + + /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - queue: The queue on which the completion handler is dispatched. `.main` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// `completionHandler`. `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// - completionHandler: A closure to be executed once the request has finished. + /// + /// - Returns: The request. + @discardableResult + public func responseDecodable(of type: T.Type = T.self, + queue: DispatchQueue = .main, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods, + completionHandler: @escaping (AFDownloadResponse) -> Void) -> Self { + response(queue: queue, + responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + completionHandler: completionHandler) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/HTTPHeaders.swift b/ChatBot/Pods/Alamofire/Source/Core/HTTPHeaders.swift new file mode 100644 index 00000000..29ca43f6 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/HTTPHeaders.swift @@ -0,0 +1,466 @@ +// +// HTTPHeaders.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An order-preserving and case-insensitive representation of HTTP headers. +public struct HTTPHeaders: Equatable, Hashable, Sendable { + private var headers: [HTTPHeader] = [] + + /// Creates an empty instance. + public init() {} + + /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last + /// name and value encountered. + public init(_ headers: [HTTPHeader]) { + headers.forEach { update($0) } + } + + /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name + /// and value encountered. + public init(_ dictionary: [String: String]) { + dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) } + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader` value. + public mutating func add(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func add(_ header: HTTPHeader) { + update(header) + } + + /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`. + /// + /// - Parameters: + /// - name: The `HTTPHeader` name. + /// - value: The `HTTPHeader` value. + public mutating func update(name: String, value: String) { + update(HTTPHeader(name: name, value: value)) + } + + /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance. + /// + /// - Parameter header: The `HTTPHeader` to update or append. + public mutating func update(_ header: HTTPHeader) { + guard let index = headers.index(of: header.name) else { + headers.append(header) + return + } + + headers.replaceSubrange(index...index, with: [header]) + } + + /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance. + /// + /// - Parameter name: The name of the `HTTPHeader` to remove. + public mutating func remove(name: String) { + guard let index = headers.index(of: name) else { return } + + headers.remove(at: index) + } + + /// Sort the current instance by header name, case insensitively. + public mutating func sort() { + headers.sort { $0.name.lowercased() < $1.name.lowercased() } + } + + /// Returns an instance sorted by header name. + /// + /// - Returns: A copy of the current instance sorted by name. + public func sorted() -> HTTPHeaders { + var headers = self + headers.sort() + + return headers + } + + /// Case-insensitively find a header's value by name. + /// + /// - Parameter name: The name of the header to search for, case-insensitively. + /// + /// - Returns: The value of header, if it exists. + public func value(for name: String) -> String? { + guard let index = headers.index(of: name) else { return nil } + + return headers[index].value + } + + /// Case-insensitively access the header with the given name. + /// + /// - Parameter name: The name of the header. + public subscript(_ name: String) -> String? { + get { value(for: name) } + set { + if let value = newValue { + update(name: name, value: value) + } else { + remove(name: name) + } + } + } + + /// The dictionary representation of all headers. + /// + /// This representation does not preserve the current order of the instance. + public var dictionary: [String: String] { + let namesAndValues = headers.map { ($0.name, $0.value) } + + return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last }) + } +} + +extension HTTPHeaders: ExpressibleByDictionaryLiteral { + public init(dictionaryLiteral elements: (String, String)...) { + elements.forEach { update(name: $0.0, value: $0.1) } + } +} + +extension HTTPHeaders: ExpressibleByArrayLiteral { + public init(arrayLiteral elements: HTTPHeader...) { + self.init(elements) + } +} + +extension HTTPHeaders: Sequence { + public func makeIterator() -> IndexingIterator<[HTTPHeader]> { + headers.makeIterator() + } +} + +extension HTTPHeaders: Collection { + public var startIndex: Int { + headers.startIndex + } + + public var endIndex: Int { + headers.endIndex + } + + public subscript(position: Int) -> HTTPHeader { + headers[position] + } + + public func index(after i: Int) -> Int { + headers.index(after: i) + } +} + +extension HTTPHeaders: CustomStringConvertible { + public var description: String { + headers.map(\.description) + .joined(separator: "\n") + } +} + +// MARK: - HTTPHeader + +/// A representation of a single HTTP header's name / value pair. +public struct HTTPHeader: Equatable, Hashable, Sendable { + /// Name of the header. + public let name: String + + /// Value of the header. + public let value: String + + /// Creates an instance from the given `name` and `value`. + /// + /// - Parameters: + /// - name: The name of the header. + /// - value: The value of the header. + public init(name: String, value: String) { + self.name = name + self.value = value + } +} + +extension HTTPHeader: CustomStringConvertible { + public var description: String { + "\(name): \(value)" + } +} + +extension HTTPHeader { + /// Returns an `Accept` header. + /// + /// - Parameter value: The `Accept` value. + /// - Returns: The header. + public static func accept(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept", value: value) + } + + /// Returns an `Accept-Charset` header. + /// + /// - Parameter value: The `Accept-Charset` value. + /// - Returns: The header. + public static func acceptCharset(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Charset", value: value) + } + + /// Returns an `Accept-Language` header. + /// + /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages. + /// Use `HTTPHeader.defaultAcceptLanguage`. + /// + /// - Parameter value: The `Accept-Language` value. + /// + /// - Returns: The header. + public static func acceptLanguage(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Language", value: value) + } + + /// Returns an `Accept-Encoding` header. + /// + /// Alamofire offers a default accept encoding value that provides the most common values. Use + /// `HTTPHeader.defaultAcceptEncoding`. + /// + /// - Parameter value: The `Accept-Encoding` value. + /// + /// - Returns: The header + public static func acceptEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Accept-Encoding", value: value) + } + + /// Returns a `Basic` `Authorization` header using the `username` and `password` provided. + /// + /// - Parameters: + /// - username: The username of the header. + /// - password: The password of the header. + /// + /// - Returns: The header. + public static func authorization(username: String, password: String) -> HTTPHeader { + let credential = Data("\(username):\(password)".utf8).base64EncodedString() + + return authorization("Basic \(credential)") + } + + /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided. + /// + /// - Parameter bearerToken: The bearer token. + /// + /// - Returns: The header. + public static func authorization(bearerToken: String) -> HTTPHeader { + authorization("Bearer \(bearerToken)") + } + + /// Returns an `Authorization` header. + /// + /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use + /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use + /// `HTTPHeader.authorization(bearerToken:)`. + /// + /// - Parameter value: The `Authorization` value. + /// + /// - Returns: The header. + public static func authorization(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Authorization", value: value) + } + + /// Returns a `Content-Disposition` header. + /// + /// - Parameter value: The `Content-Disposition` value. + /// + /// - Returns: The header. + public static func contentDisposition(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Disposition", value: value) + } + + /// Returns a `Content-Encoding` header. + /// + /// - Parameter value: The `Content-Encoding`. + /// + /// - Returns: The header. + public static func contentEncoding(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Encoding", value: value) + } + + /// Returns a `Content-Type` header. + /// + /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not + /// be necessary to manually set this value. + /// + /// - Parameter value: The `Content-Type` value. + /// + /// - Returns: The header. + public static func contentType(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Content-Type", value: value) + } + + /// Returns a `User-Agent` header. + /// + /// - Parameter value: The `User-Agent` value. + /// + /// - Returns: The header. + public static func userAgent(_ value: String) -> HTTPHeader { + HTTPHeader(name: "User-Agent", value: value) + } + + /// Returns a `Sec-WebSocket-Protocol` header. + /// + /// - Parameter value: The `Sec-WebSocket-Protocol` value. + /// - Returns: The header. + public static func websocketProtocol(_ value: String) -> HTTPHeader { + HTTPHeader(name: "Sec-WebSocket-Protocol", value: value) + } +} + +extension [HTTPHeader] { + /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists. + func index(of name: String) -> Int? { + let lowercasedName = name.lowercased() + return firstIndex { $0.name.lowercased() == lowercasedName } + } +} + +// MARK: - Defaults + +extension HTTPHeaders { + /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and + /// `User-Agent`. + public static let `default`: HTTPHeaders = [.defaultAcceptEncoding, + .defaultAcceptLanguage, + .defaultUserAgent] +} + +extension HTTPHeader { + /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS + /// versions. + /// + /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) . + public static let defaultAcceptEncoding: HTTPHeader = { + let encodings: [String] + if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) { + encodings = ["br", "gzip", "deflate"] + } else { + encodings = ["gzip", "deflate"] + } + + return .acceptEncoding(encodings.qualityEncoded()) + }() + + /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's + /// `preferredLanguages`. + /// + /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5). + public static let defaultAcceptLanguage: HTTPHeader = .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded()) + + /// Returns Alamofire's default `User-Agent` header. + /// + /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3). + /// + /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0` + public static let defaultUserAgent: HTTPHeader = { + let info = Bundle.main.infoDictionary + let executable = (info?["CFBundleExecutable"] as? String) ?? + (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ?? + "Unknown" + let bundle = info?["CFBundleIdentifier"] as? String ?? "Unknown" + let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info?["CFBundleVersion"] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + let osName: String = { + #if os(iOS) + #if targetEnvironment(macCatalyst) + return "macOS(Catalyst)" + #else + return "iOS" + #endif + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + #if targetEnvironment(macCatalyst) + return "macOS(Catalyst)" + #else + return "macOS" + #endif + #elseif swift(>=5.9.2) && os(visionOS) + return "visionOS" + #elseif os(Linux) + return "Linux" + #elseif os(Windows) + return "Windows" + #elseif os(Android) + return "Android" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion = "Alamofire/\(AFInfo.version)" + + let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + + return .userAgent(userAgent) + }() +} + +extension Collection { + func qualityEncoded() -> String { + enumerated().map { index, encoding in + let quality = 1.0 - (Double(index) * 0.1) + return "\(encoding);q=\(quality)" + }.joined(separator: ", ") + } +} + +// MARK: - System Type Extensions + +extension URLRequest { + /// Returns `allHTTPHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() } + set { allHTTPHeaderFields = newValue.dictionary } + } +} + +extension HTTPURLResponse { + /// Returns `allHeaderFields` as `HTTPHeaders`. + public var headers: HTTPHeaders { + (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() + } +} + +extension URLSessionConfiguration { + /// Returns `httpAdditionalHeaders` as `HTTPHeaders`. + public var headers: HTTPHeaders { + get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() } + set { httpAdditionalHeaders = newValue.dictionary } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/HTTPMethod.swift b/ChatBot/Pods/Alamofire/Source/Core/HTTPMethod.swift new file mode 100644 index 00000000..ed51b689 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/HTTPMethod.swift @@ -0,0 +1,56 @@ +// +// HTTPMethod.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so +/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public struct HTTPMethod: RawRepresentable, Equatable, Hashable, Sendable { + /// `CONNECT` method. + public static let connect = HTTPMethod(rawValue: "CONNECT") + /// `DELETE` method. + public static let delete = HTTPMethod(rawValue: "DELETE") + /// `GET` method. + public static let get = HTTPMethod(rawValue: "GET") + /// `HEAD` method. + public static let head = HTTPMethod(rawValue: "HEAD") + /// `OPTIONS` method. + public static let options = HTTPMethod(rawValue: "OPTIONS") + /// `PATCH` method. + public static let patch = HTTPMethod(rawValue: "PATCH") + /// `POST` method. + public static let post = HTTPMethod(rawValue: "POST") + /// `PUT` method. + public static let put = HTTPMethod(rawValue: "PUT") + /// `QUERY` method. + public static let query = HTTPMethod(rawValue: "QUERY") + /// `TRACE` method. + public static let trace = HTTPMethod(rawValue: "TRACE") + + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/Notifications.swift b/ChatBot/Pods/Alamofire/Source/Core/Notifications.swift new file mode 100644 index 00000000..66434b6e --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/Notifications.swift @@ -0,0 +1,115 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. + public static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") + /// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`. + public static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend") + /// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`. + public static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel") + /// Posted when a `Request` is finished. The `Notification` contains the completed `Request`. + public static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish") + + /// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask") + /// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask") + /// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask") + /// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`. + public static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask") +} + +// MARK: - + +extension Notification { + /// The `Request` contained by the instance's `userInfo`, `nil` otherwise. + public var request: Request? { + userInfo?[String.requestKey] as? Request + } + + /// Convenience initializer for a `Notification` containing a `Request` payload. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + init(name: Notification.Name, request: Request) { + self.init(name: name, object: nil, userInfo: [String.requestKey: request]) + } +} + +extension NotificationCenter { + /// Convenience function for posting notifications with `Request` payloads. + /// + /// - Parameters: + /// - name: The name of the notification. + /// - request: The `Request` payload. + func postNotification(named name: Notification.Name, with request: Request) { + let notification = Notification(name: name, request: request) + post(notification) + } +} + +extension String { + /// User info dictionary key representing the `Request` associated with the notification. + fileprivate static let requestKey = "org.alamofire.notification.key.request" +} + +/// `EventMonitor` that provides Alamofire's notifications. +public final class AlamofireNotifications: EventMonitor { + public func requestDidResume(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request) + } + + public func requestDidSuspend(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request) + } + + public func requestDidCancel(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request) + } + + public func requestDidFinish(_ request: Request) { + NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request) + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/ParameterEncoder.swift b/ChatBot/Pods/Alamofire/Source/Core/ParameterEncoder.swift new file mode 100644 index 00000000..3d30c3f3 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/ParameterEncoder.swift @@ -0,0 +1,213 @@ +// +// ParameterEncoder.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that can encode any `Encodable` type into a `URLRequest`. +public protocol ParameterEncoder { + /// Encode the provided `Encodable` parameters into `request`. + /// + /// - Parameters: + /// - parameters: The `Encodable` parameter value. + /// - request: The `URLRequest` into which to encode the parameters. + /// + /// - Returns: A `URLRequest` with the result of the encoding. + /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of + /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`. + func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest +} + +/// A `ParameterEncoder` that encodes types as JSON body data. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`. +open class JSONParameterEncoder: ParameterEncoder { + /// Returns an encoder with default parameters. + public static var `default`: JSONParameterEncoder { JSONParameterEncoder() } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`. + public static var prettyPrinted: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .prettyPrinted + + return JSONParameterEncoder(encoder: encoder) + } + + /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`. + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public static var sortedKeys: JSONParameterEncoder { + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + + return JSONParameterEncoder(encoder: encoder) + } + + /// `JSONEncoder` used to encode parameters. + public let encoder: JSONEncoder + + /// Creates an instance with the provided `JSONEncoder`. + /// + /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default. + public init(encoder: JSONEncoder = JSONEncoder()) { + self.encoder = encoder + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters else { return request } + + var request = request + + do { + let data = try encoder.encode(parameters) + request.httpBody = data + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/json")) + } + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return request + } +} + +extension ParameterEncoder where Self == JSONParameterEncoder { + /// Provides a default `JSONParameterEncoder` instance. + public static var json: JSONParameterEncoder { JSONParameterEncoder() } + + /// Creates a `JSONParameterEncoder` using the provided `JSONEncoder`. + /// + /// - Parameter encoder: `JSONEncoder` used to encode parameters. `JSONEncoder()` by default. + /// - Returns: The `JSONParameterEncoder`. + public static func json(encoder: JSONEncoder = JSONEncoder()) -> JSONParameterEncoder { + JSONParameterEncoder(encoder: encoder) + } +} + +/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending +/// on the `Destination` set. +/// +/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer. +open class URLEncodedFormParameterEncoder: ParameterEncoder { + /// Defines where the URL-encoded string should be set for each `URLRequest`. + public enum Destination { + /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request. + /// Sets it to the `httpBody` for all other methods. + case methodDependent + /// Applies the encoded query string to any existing query string from the `URLRequest`. + case queryString + /// Applies the encoded query string to the `httpBody` of the `URLRequest`. + case httpBody + + /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`. + /// + /// - Parameter method: The `HTTPMethod`. + /// + /// - Returns: Whether the URL-encoded string should be applied to a `URL`. + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Returns an encoder with default parameters. + public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// The `URLEncodedFormEncoder` to use. + public let encoder: URLEncodedFormEncoder + + /// The `Destination` for the URL-encoded string. + public let destination: Destination + + /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value. + /// + /// - Parameters: + /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default. + /// - destination: The `Destination`. `.methodDependent` by default. + public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) { + self.encoder = encoder + self.destination = destination + } + + open func encode(_ parameters: Parameters?, + into request: URLRequest) throws -> URLRequest { + guard let parameters else { return request } + + var request = request + + guard let url = request.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + guard let method = request.method else { + let rawValue = request.method?.rawValue ?? "nil" + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue))) + } + + if destination.encodesParametersInURL(for: method), + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { + let query: String = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands() + components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString + + guard let newURL = components.url else { + throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url)) + } + + request.url = newURL + } else { + if request.headers["Content-Type"] == nil { + request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + request.httpBody = try Result { try encoder.encode(parameters) } + .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get() + } + + return request + } +} + +extension ParameterEncoder where Self == URLEncodedFormParameterEncoder { + /// Provides a default `URLEncodedFormParameterEncoder` instance. + public static var urlEncodedForm: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } + + /// Creates a `URLEncodedFormParameterEncoder` with the provided encoder and destination. + /// + /// - Parameters: + /// - encoder: `URLEncodedFormEncoder` used to encode the parameters. `URLEncodedFormEncoder()` by default. + /// - destination: `Destination` to which to encode the parameters. `.methodDependent` by default. + /// - Returns: The `URLEncodedFormParameterEncoder`. + public static func urlEncodedForm(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), + destination: URLEncodedFormParameterEncoder.Destination = .methodDependent) -> URLEncodedFormParameterEncoder { + URLEncodedFormParameterEncoder(encoder: encoder, destination: destination) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/ParameterEncoding.swift b/ChatBot/Pods/Alamofire/Source/Core/ParameterEncoding.swift new file mode 100644 index 00000000..5b7d680c --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/ParameterEncoding.swift @@ -0,0 +1,349 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. + /// - parameters: `Parameters` to encode onto the request. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during parameter encoding. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default the convention of appending +/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for +/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +public struct URLEncoding: ParameterEncoding { + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + public enum Destination { + /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and + /// sets as the HTTP body for requests with any other HTTP method. + case methodDependent + /// Sets or appends encoded query string result to existing query string. + case queryString + /// Sets encoded query string result as the HTTP body of the URL request. + case httpBody + + func encodesParametersInURL(for method: HTTPMethod) -> Bool { + switch self { + case .methodDependent: return [.get, .head, .delete].contains(method) + case .queryString: return true + case .httpBody: return false + } + } + } + + /// Configures how `Array` parameters are encoded. + public enum ArrayEncoding { + /// An empty set of square brackets is appended to the key for every value. This is the default behavior. + case brackets + /// No brackets are appended. The key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((_ key: String, _ index: Int) -> String) + + func encode(key: String, atIndex index: Int) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + case .indexInBrackets: + return "\(key)[\(index)]" + case let .custom(encoding): + return encoding(key, index) + } + } + } + + /// Configures how `Bool` parameters are encoded. + public enum BoolEncoding { + /// Encode `true` as `1` and `false` as `0`. This is the default behavior. + case numeric + /// Encode `true` and `false` as string literals. + case literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + return value ? "1" : "0" + case .literal: + return value ? "true" : "false" + } + } + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. + public static var `default`: URLEncoding { URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + /// The encoding to use for `Array` parameters. + public let arrayEncoding: ArrayEncoding + + /// The encoding to use for `Bool` parameters. + public let boolEncoding: BoolEncoding + + // MARK: Initialization + + /// Creates an instance using the specified parameters. + /// + /// - Parameters: + /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by + /// default. + /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. + public init(destination: Destination = .methodDependent, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters else { return urlRequest } + + if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8")) + } + + urlRequest.httpBody = Data(query(parameters).utf8) + } + + return urlRequest + } + + /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. + /// + /// - Parameters: + /// - key: Key of the query component. + /// - value: Value of the query component. + /// + /// - Returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + switch value { + case let dictionary as [String: Any]: + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + case let array as [Any]: + for (index, value) in array.enumerated() { + components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value) + } + case let number as NSNumber: + if number.isBool { + components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue)))) + } else { + components.append((escape(key), escape("\(number)"))) + } + case let bool as Bool: + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) + default: + components.append((escape(key), escape("\(value)"))) + } + return components + } + + /// Creates a percent-escaped string following RFC 3986 for a query string key or value. + /// + /// - Parameter string: `String` to be percent-escaped. + /// + /// - Returns: The percent-escaped `String`. + public func escape(_ string: String) -> String { + string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string + } + + private func query(_ parameters: [String: Any]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + /// Error produced by `JSONEncoding`. + public enum Error: Swift.Error { + /// `JSONEncoding` attempted to encode an invalid JSON object. Usually this means the value included types not + /// representable in Objective-C. See `JSONSerialization.isValidJSONObject` for details. + case invalidJSONObject + } + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates an instance using the specified `WritingOptions`. + /// + /// - Parameter options: `JSONSerialization.WritingOptions` to use. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(parameters) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Encodes any JSON compatible object into a `URLRequest`. + /// + /// - Parameters: + /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. + /// - jsonObject: `Any` value (must be JSON compatible) to be encoded into the `URLRequest`. `nil` by default. + /// + /// - Returns: The encoded `URLRequest`. + /// - Throws: Any `Error` produced during encoding. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject else { return urlRequest } + + guard JSONSerialization.isValidJSONObject(jsonObject) else { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject)) + } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.headers["Content-Type"] == nil { + urlRequest.headers.update(.contentType("application/json")) + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +extension JSONEncoding.Error { + public var localizedDescription: String { + """ + Invalid JSON object provided for parameter or object encoding. \ + This is most likely due to a value which can't be represented in Objective-C. + """ + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { + // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of + // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22). + String(cString: objCType) == "c" + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/Protected.swift b/ChatBot/Pods/Alamofire/Source/Core/Protected.swift new file mode 100644 index 00000000..67560454 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/Protected.swift @@ -0,0 +1,168 @@ +// +// Protected.swift +// +// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +private protocol Lock { + func lock() + func unlock() +} + +extension Lock { + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value the closure generated. + func around(_ closure: () throws -> T) rethrows -> T { + lock(); defer { unlock() } + return try closure() + } + + /// Execute a closure while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + func around(_ closure: () throws -> Void) rethrows { + lock(); defer { unlock() } + try closure() + } +} + +#if canImport(Darwin) +/// An `os_unfair_lock` wrapper. +final class UnfairLock: Lock { + private let unfairLock: os_unfair_lock_t + + init() { + unfairLock = .allocate(capacity: 1) + unfairLock.initialize(to: os_unfair_lock()) + } + + deinit { + unfairLock.deinitialize(count: 1) + unfairLock.deallocate() + } + + fileprivate func lock() { + os_unfair_lock_lock(unfairLock) + } + + fileprivate func unlock() { + os_unfair_lock_unlock(unfairLock) + } +} + +#elseif canImport(Foundation) +extension NSLock: Lock {} +#else +#error("This platform needs a Lock-conforming type without Foundation.") +#endif + +/// A thread-safe wrapper around a value. +@dynamicMemberLookup +final class Protected { + #if canImport(Darwin) + private let lock = UnfairLock() + #elseif canImport(Foundation) + private let lock = NSLock() + #else + #error("This platform needs a Lock-conforming type without Foundation.") + #endif + private var value: Value + + init(_ value: Value) { + self.value = value + } + + /// Synchronously read or transform the contained value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The return value of the closure passed. + func read(_ closure: (Value) throws -> U) rethrows -> U { + try lock.around { try closure(self.value) } + } + + /// Synchronously modify the protected value. + /// + /// - Parameter closure: The closure to execute. + /// + /// - Returns: The modified value. + @discardableResult + func write(_ closure: (inout Value) throws -> U) rethrows -> U { + try lock.around { try closure(&self.value) } + } + + /// Synchronously update the protected value. + /// + /// - Parameter value: The `Value`. + func write(_ value: Value) { + write { $0 = value } + } + + subscript(dynamicMember keyPath: WritableKeyPath) -> Property { + get { lock.around { value[keyPath: keyPath] } } + set { lock.around { value[keyPath: keyPath] = newValue } } + } + + subscript(dynamicMember keyPath: KeyPath) -> Property { + lock.around { value[keyPath: keyPath] } + } +} + +extension Protected where Value == Request.MutableState { + /// Attempts to transition to the passed `State`. + /// + /// - Parameter state: The `State` to attempt transition to. + /// + /// - Returns: Whether the transition occurred. + func attemptToTransitionTo(_ state: Request.State) -> Bool { + lock.around { + guard value.state.canTransitionTo(state) else { return false } + + value.state = state + + return true + } + } + + /// Perform a closure while locked with the provided `Request.State`. + /// + /// - Parameter perform: The closure to perform while locked. + func withState(perform: (Request.State) -> Void) { + lock.around { perform(value.state) } + } +} + +extension Protected: Equatable where Value: Equatable { + static func ==(lhs: Protected, rhs: Protected) -> Bool { + lhs.read { left in rhs.read { right in left == right }} + } +} + +extension Protected: Hashable where Value: Hashable { + func hash(into hasher: inout Hasher) { + read { hasher.combine($0) } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/Request.swift b/ChatBot/Pods/Alamofire/Source/Core/Request.swift new file mode 100644 index 00000000..e1df52e1 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/Request.swift @@ -0,0 +1,1090 @@ +// +// Request.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback +/// handling. +public class Request { + /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or + /// `cancel()` on the `Request`. + public enum State { + /// Initial state of the `Request`. + case initialized + /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on + /// them in this state. + case resumed + /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on + /// them in this state. + case suspended + /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on + /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition + /// to any other state. + case cancelled + /// `State` set when all response serialization completion closures have been cleared on the `Request` and + /// enqueued on their respective queues. + case finished + + /// Determines whether `self` can be transitioned to the provided `State`. + func canTransitionTo(_ state: State) -> Bool { + switch (self, state) { + case (.initialized, _): + return true + case (_, .initialized), (.cancelled, _), (.finished, _): + return false + case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed): + return true + case (.suspended, .suspended), (.resumed, .resumed): + return false + case (_, .finished): + return true + } + } + } + + // MARK: - Initial State + + /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances. + public let id: UUID + /// The serial queue for all internal async actions. + public let underlyingQueue: DispatchQueue + /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`. + public let serializationQueue: DispatchQueue + /// `EventMonitor` used for event callbacks. + public let eventMonitor: EventMonitor? + /// The `Request`'s interceptor. + public let interceptor: RequestInterceptor? + /// The `Request`'s delegate. + public private(set) weak var delegate: RequestDelegate? + + // MARK: - Mutable State + + /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`. + struct MutableState { + /// State of the `Request`. + var state: State = .initialized + /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks. + var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks. + var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? + /// `RedirectHandler` provided for to handle request redirection. + var redirectHandler: RedirectHandler? + /// `CachedResponseHandler` provided to handle response caching. + var cachedResponseHandler: CachedResponseHandler? + /// Queue and closure called when the `Request` is able to create a cURL description of itself. + var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)? + /// Queue and closure called when the `Request` creates a `URLRequest`. + var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)? + /// Queue and closure called when the `Request` creates a `URLSessionTask`. + var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)? + /// Response serialization closures that handle response parsing. + var responseSerializers: [() -> Void] = [] + /// Response serialization completion closures executed once all response serializers are complete. + var responseSerializerCompletions: [() -> Void] = [] + /// Whether response serializer processing is finished. + var responseSerializerProcessingFinished = false + /// `URLCredential` used for authentication challenges. + var credential: URLCredential? + /// All `URLRequest`s created by Alamofire on behalf of the `Request`. + var requests: [URLRequest] = [] + /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`. + var tasks: [URLSessionTask] = [] + /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond + /// exactly the the `tasks` created. + var metrics: [URLSessionTaskMetrics] = [] + /// Number of times any retriers provided retried the `Request`. + var retryCount = 0 + /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`. + var error: AFError? + /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a + /// representation in the state machine in the future. + var isFinishing = false + /// Actions to run when requests are finished. Use for concurrency support. + var finishHandlers: [() -> Void] = [] + } + + /// Protected `MutableState` value that provides thread-safe access to state values. + let mutableState = Protected(MutableState()) + + /// `State` of the `Request`. + public var state: State { mutableState.state } + /// Returns whether `state` is `.initialized`. + public var isInitialized: Bool { state == .initialized } + /// Returns whether `state` is `.resumed`. + public var isResumed: Bool { state == .resumed } + /// Returns whether `state` is `.suspended`. + public var isSuspended: Bool { state == .suspended } + /// Returns whether `state` is `.cancelled`. + public var isCancelled: Bool { state == .cancelled } + /// Returns whether `state` is `.finished`. + public var isFinished: Bool { state == .finished } + + // MARK: Progress + + /// Closure type executed when monitoring the upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried. + public let uploadProgress = Progress(totalUnitCount: 0) + /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried. + public let downloadProgress = Progress(totalUnitCount: 0) + /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`. + public internal(set) var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { mutableState.uploadProgressHandler } + set { mutableState.uploadProgressHandler = newValue } + } + + /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`. + public internal(set) var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? { + get { mutableState.downloadProgressHandler } + set { mutableState.downloadProgressHandler = newValue } + } + + // MARK: Redirect Handling + + /// `RedirectHandler` set on the instance. + public internal(set) var redirectHandler: RedirectHandler? { + get { mutableState.redirectHandler } + set { mutableState.redirectHandler = newValue } + } + + // MARK: Cached Response Handling + + /// `CachedResponseHandler` set on the instance. + public internal(set) var cachedResponseHandler: CachedResponseHandler? { + get { mutableState.cachedResponseHandler } + set { mutableState.cachedResponseHandler = newValue } + } + + // MARK: URLCredential + + /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods. + public internal(set) var credential: URLCredential? { + get { mutableState.credential } + set { mutableState.credential = newValue } + } + + // MARK: Validators + + /// `Validator` callback closures that store the validation calls enqueued. + let validators = Protected<[() -> Void]>([]) + + // MARK: URLRequests + + /// All `URLRequest`s created on behalf of the `Request`, including original and adapted requests. + public var requests: [URLRequest] { mutableState.requests } + /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed. + public var firstRequest: URLRequest? { requests.first } + /// Last `URLRequest` created on behalf of the `Request`. + public var lastRequest: URLRequest? { requests.last } + /// Current `URLRequest` created on behalf of the `Request`. + public var request: URLRequest? { lastRequest } + + /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from + /// `requests` due to `URLSession` manipulation. + public var performedRequests: [URLRequest] { mutableState.read { $0.tasks.compactMap(\.currentRequest) } } + + // MARK: HTTPURLResponse + + /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the + /// last `URLSessionTask`. + public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse } + + // MARK: Tasks + + /// All `URLSessionTask`s created on behalf of the `Request`. + public var tasks: [URLSessionTask] { mutableState.tasks } + /// First `URLSessionTask` created on behalf of the `Request`. + public var firstTask: URLSessionTask? { tasks.first } + /// Last `URLSessionTask` created on behalf of the `Request`. + public var lastTask: URLSessionTask? { tasks.last } + /// Current `URLSessionTask` created on behalf of the `Request`. + public var task: URLSessionTask? { lastTask } + + // MARK: Metrics + + /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created. + public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics } + /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first } + /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last } + /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`. + public var metrics: URLSessionTaskMetrics? { lastMetrics } + + // MARK: Retry Count + + /// Number of times the `Request` has been retried. + public var retryCount: Int { mutableState.retryCount } + + // MARK: Error + + /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed. + public internal(set) var error: AFError? { + get { mutableState.error } + set { mutableState.error = newValue } + } + + /// Default initializer for the `Request` superclass. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.id = id + self.underlyingQueue = underlyingQueue + self.serializationQueue = serializationQueue + self.eventMonitor = eventMonitor + self.interceptor = interceptor + self.delegate = delegate + } + + // MARK: - Internal Event API + + // All API must be called from underlyingQueue. + + /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active, + /// the `URLRequest` will be adapted before being issued. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateInitialURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.requests.append(request) } + + eventMonitor?.request(self, didCreateInitialURLRequest: request) + } + + /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. + /// + /// - Note: Triggers retry. + /// + /// - Parameter error: `AFError` thrown from the failed creation. + func didFailToCreateURLRequest(with error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToCreateURLRequestWithError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`. + /// + /// - Parameters: + /// - initialRequest: The `URLRequest` that was adapted. + /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`. + func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.requests.append(adaptedRequest) } + + eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest) + } + + /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. + /// + /// - Note: Triggers retry. + /// + /// - Parameters: + /// - request: The `URLRequest` the adapter was called with. + /// - error: The `AFError` returned by the `RequestAdapter`. + func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error) + + callCURLHandlerIfNecessary() + + retryOrFinish(error: error) + } + + /// Final `URLRequest` has been created for the instance. + /// + /// - Parameter request: The `URLRequest` created. + func didCreateURLRequest(_ request: URLRequest) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.read { state in + state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) } + } + + eventMonitor?.request(self, didCreateURLRequest: request) + + callCURLHandlerIfNecessary() + } + + /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`. + private func callCURLHandlerIfNecessary() { + mutableState.write { mutableState in + guard let cURLHandler = mutableState.cURLHandler else { return } + + cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) } + + mutableState.cURLHandler = nil + } + } + + /// Called when a `URLSessionTask` is created on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` created. + func didCreateTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { state in + state.tasks.append(task) + + guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return } + + urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) } + } + + eventMonitor?.request(self, didCreateTask: task) + } + + /// Called when resumption is completed. + func didResume() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidResume(self) + } + + /// Called when a `URLSessionTask` is resumed on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` resumed. + func didResumeTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didResumeTask: task) + } + + /// Called when suspension is completed. + func didSuspend() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.requestDidSuspend(self) + } + + /// Called when a `URLSessionTask` is suspended on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` suspended. + func didSuspendTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didSuspendTask: task) + } + + /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`. + func didCancel() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { mutableState in + mutableState.error = mutableState.error ?? AFError.explicitlyCancelled + } + + eventMonitor?.requestDidCancel(self) + } + + /// Called when a `URLSessionTask` is cancelled on behalf of the instance. + /// + /// - Parameter task: The `URLSessionTask` cancelled. + func didCancelTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + eventMonitor?.request(self, didCancelTask: task) + } + + /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance. + /// + /// - Parameter metrics: The `URLSessionTaskMetrics` gathered. + func didGatherMetrics(_ metrics: URLSessionTaskMetrics) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.metrics.append(metrics) } + + eventMonitor?.request(self, didGatherMetrics: metrics) + } + + /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which failed. + /// - error: The early failure `AFError`. + func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = error + + // Task will still complete, so didCompleteTask(_:with:) will handle retry. + eventMonitor?.request(self, didFailTask: task, earlyWithError: error) + } + + /// Called when a `URLSessionTask` completes. All tasks will eventually call this method. + /// + /// - Note: Response validation is synchronously triggered in this step. + /// + /// - Parameters: + /// - task: The `URLSessionTask` which completed. + /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this + /// value is ignored. + func didCompleteTask(_ task: URLSessionTask, with error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + self.error = self.error ?? error + + let validators = validators.read { $0 } + validators.forEach { $0() } + + eventMonitor?.request(self, didCompleteTask: task, with: error) + + retryOrFinish(error: self.error) + } + + /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`. + func prepareForRetry() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { $0.retryCount += 1 } + + reset() + + eventMonitor?.requestIsRetrying(self) + } + + /// Called to determine whether retry will be triggered for the particular error, or whether the instance should + /// call `finish()`. + /// + /// - Parameter error: The possible `AFError` which may trigger retry. + func retryOrFinish(error: AFError?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !isCancelled, let error, let delegate else { finish(); return } + + delegate.retryResult(for: self, dueTo: error) { retryResult in + switch retryResult { + case .doNotRetry: + self.finish() + case let .doNotRetryWithError(retryError): + self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError")) + case .retry, .retryWithDelay: + delegate.retryRequest(self, withDelay: retryResult.delay) + } + } + } + + /// Finishes this `Request` and starts the response serializers. + /// + /// - Parameter error: The possible `Error` with which the instance will finish. + func finish(error: AFError? = nil) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + guard !mutableState.isFinishing else { return } + + mutableState.isFinishing = true + + if let error { self.error = error } + + // Start response handlers + processNextResponseSerializer() + + eventMonitor?.requestDidFinish(self) + } + + /// Appends the response serialization closure to the instance. + /// + /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. + /// + /// - Parameter closure: The closure containing the response serialization call. + func appendResponseSerializer(_ closure: @escaping () -> Void) { + mutableState.write { mutableState in + mutableState.responseSerializers.append(closure) + + if mutableState.state == .finished { + mutableState.state = .resumed + } + + if mutableState.responseSerializerProcessingFinished { + underlyingQueue.async { self.processNextResponseSerializer() } + } + + if mutableState.state.canTransitionTo(.resumed) { + underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } } + } + } + } + + /// Returns the next response serializer closure to execute if there's one left. + /// + /// - Returns: The next response serialization closure, if there is one. + func nextResponseSerializer() -> (() -> Void)? { + var responseSerializer: (() -> Void)? + + mutableState.write { mutableState in + let responseSerializerIndex = mutableState.responseSerializerCompletions.count + + if responseSerializerIndex < mutableState.responseSerializers.count { + responseSerializer = mutableState.responseSerializers[responseSerializerIndex] + } + } + + return responseSerializer + } + + /// Processes the next response serializer and calls all completions if response serialization is complete. + func processNextResponseSerializer() { + guard let responseSerializer = nextResponseSerializer() else { + // Execute all response serializer completions and clear them + var completions: [() -> Void] = [] + + mutableState.write { mutableState in + completions = mutableState.responseSerializerCompletions + + // Clear out all response serializers and response serializer completions in mutable state since the + // request is complete. It's important to do this prior to calling the completion closures in case + // the completions call back into the request triggering a re-processing of the response serializers. + // An example of how this can happen is by calling cancel inside a response completion closure. + mutableState.responseSerializers.removeAll() + mutableState.responseSerializerCompletions.removeAll() + + if mutableState.state.canTransitionTo(.finished) { + mutableState.state = .finished + } + + mutableState.responseSerializerProcessingFinished = true + mutableState.isFinishing = false + } + + completions.forEach { $0() } + + // Cleanup the request + cleanup() + + return + } + + serializationQueue.async { responseSerializer() } + } + + /// Notifies the `Request` that the response serializer is complete. + /// + /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers + /// are complete. + func responseSerializerDidComplete(completion: @escaping () -> Void) { + mutableState.write { $0.responseSerializerCompletions.append(completion) } + processNextResponseSerializer() + } + + /// Resets all task and response serializer related state for retry. + func reset() { + error = nil + + uploadProgress.totalUnitCount = 0 + uploadProgress.completedUnitCount = 0 + downloadProgress.totalUnitCount = 0 + downloadProgress.completedUnitCount = 0 + + mutableState.write { state in + state.isFinishing = false + state.responseSerializerCompletions = [] + } + } + + /// Called when updating the upload progress. + /// + /// - Parameters: + /// - totalBytesSent: Total bytes sent so far. + /// - totalBytesExpectedToSend: Total bytes expected to send. + func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } + } + + /// Perform a closure on the current `state` while locked. + /// + /// - Parameter perform: The closure to perform. + func withState(perform: (State) -> Void) { + mutableState.withState(perform: perform) + } + + // MARK: Task Creation + + /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override. + /// + /// - Parameters: + /// - request: `URLRequest` to use to create the `URLSessionTask`. + /// - session: `URLSession` which creates the `URLSessionTask`. + /// + /// - Returns: The `URLSessionTask` created. + func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + fatalError("Subclasses must override.") + } + + // MARK: - Public API + + // These APIs are callable from any queue. + + // MARK: State + + /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended. + /// + /// - Returns: The instance. + @discardableResult + public func cancel() -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didCancel() } + + guard let task = mutableState.tasks.last, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + underlyingQueue.async { self.didCancelTask(task) } + } + + return self + } + + /// Suspends the instance. + /// + /// - Returns: The instance. + @discardableResult + public func suspend() -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.suspended) else { return } + + mutableState.state = .suspended + + underlyingQueue.async { self.didSuspend() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.suspend() + underlyingQueue.async { self.didSuspendTask(task) } + } + + return self + } + + /// Resumes the instance. + /// + /// - Returns: The instance. + @discardableResult + public func resume() -> Self { + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.resumed) else { return } + + mutableState.state = .resumed + + underlyingQueue.async { self.didResume() } + + guard let task = mutableState.tasks.last, task.state != .completed else { return } + + task.resume() + underlyingQueue.async { self.didResumeTask(task) } + } + + return self + } + + // MARK: - Closure API + + /// Associates a credential using the provided values with the instance. + /// + /// - Parameters: + /// - username: The username. + /// - password: The password. + /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { + let credential = URLCredential(user: username, password: password, persistence: persistence) + + return authenticate(with: credential) + } + + /// Associates the provided credential with the instance. + /// + /// - Parameter credential: The `URLCredential`. + /// + /// - Returns: The instance. + @discardableResult + public func authenticate(with credential: URLCredential) -> Self { + mutableState.credential = credential + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is read from the server. + /// + /// - Returns: The instance. + @discardableResult + public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + mutableState.downloadProgressHandler = (handler: closure, queue: queue) + + return self + } + + /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server. + /// + /// - Note: Only the last closure provided is used. + /// + /// - Parameters: + /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default. + /// - closure: The closure to be executed periodically as data is sent to the server. + /// + /// - Returns: The instance. + @discardableResult + public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { + mutableState.uploadProgressHandler = (handler: closure, queue: queue) + + return self + } + + // MARK: Redirects + + /// Sets the redirect handler for the instance which will be used if a redirect response is encountered. + /// + /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `RedirectHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func redirect(using handler: RedirectHandler) -> Self { + mutableState.write { mutableState in + precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.") + mutableState.redirectHandler = handler + } + + return self + } + + // MARK: Cached Responses + + /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response. + /// + /// - Note: Attempting to set the cache handler more than once is a logic error and will crash. + /// + /// - Parameter handler: The `CachedResponseHandler`. + /// + /// - Returns: The instance. + @discardableResult + public func cacheResponse(using handler: CachedResponseHandler) -> Self { + mutableState.write { mutableState in + precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.") + mutableState.cachedResponseHandler = handler + } + + return self + } + + // MARK: - Lifetime APIs + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. + /// - handler: Closure to be called when the cURL description is available. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self { + mutableState.write { mutableState in + if mutableState.requests.last != nil { + queue.async { handler(self.cURLDescription()) } + } else { + mutableState.cURLHandler = (queue, handler) + } + } + + return self + } + + /// Sets a handler to be called when the cURL description of the request is available. + /// + /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. + /// + /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's + /// `underlyingQueue` by default. + /// + /// - Returns: The instance. + @discardableResult + public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self { + cURLDescription(on: underlyingQueue, calling: handler) + + return self + } + + /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance. + /// + /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when a `URLRequest` is available. + /// + /// - Returns: The instance. + @discardableResult + public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self { + mutableState.write { state in + if let request = state.requests.last { + queue.async { handler(request) } + } + + state.urlRequestHandler = (queue, handler) + } + + return self + } + + /// Sets a closure to be called whenever the instance creates a `URLSessionTask`. + /// + /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It + /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features. + /// Additionally, this closure may be called multiple times if the instance is retried. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default. + /// - handler: Closure to be called when the `URLSessionTask` is available. + /// + /// - Returns: The instance. + @discardableResult + public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self { + mutableState.write { state in + if let task = state.tasks.last { + queue.async { handler(task) } + } + + state.urlSessionTaskHandler = (queue, handler) + } + + return self + } + + // MARK: Cleanup + + /// Adds a `finishHandler` closure to be called when the request completes. + /// + /// - Parameter closure: Closure to be called when the request finishes. + func onFinish(perform finishHandler: @escaping () -> Void) { + guard !isFinished else { finishHandler(); return } + + mutableState.write { state in + state.finishHandlers.append(finishHandler) + } + } + + /// Final cleanup step executed when the instance finishes response serialization. + func cleanup() { + let handlers = mutableState.finishHandlers + handlers.forEach { $0() } + mutableState.write { state in + state.finishHandlers.removeAll() + } + + delegate?.cleanup(after: self) + } +} + +extension Request { + /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`. + public enum ResponseDisposition { + /// Allow the request to continue normally. + case allow + /// Cancel the request, similar to calling `cancel()`. + case cancel + + var sessionDisposition: URLSession.ResponseDisposition { + switch self { + case .allow: return .allow + case .cancel: return .cancel + } + } + } +} + +// MARK: - Protocol Conformances + +extension Request: Equatable { + public static func ==(lhs: Request, rhs: Request) -> Bool { + lhs.id == rhs.id + } +} + +extension Request: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + } +} + +extension Request: CustomStringConvertible { + /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been + /// created, as well as the response status code, if a response has been received. + public var description: String { + guard let request = performedRequests.last ?? lastRequest, + let url = request.url, + let method = request.httpMethod else { return "No request created yet." } + + let requestDescription = "\(method) \(url.absoluteString)" + + return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription + } +} + +extension Request { + /// cURL representation of the instance. + /// + /// - Returns: The cURL equivalent of the instance. + public func cURLDescription() -> String { + guard + let request = lastRequest, + let url = request.url, + let host = url.host, + let method = request.httpMethod else { return "$ curl command could not be created" } + + var components = ["$ curl -v"] + + components.append("-X \(method)") + + if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace(host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies { + if + let cookieStorage = configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { + let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";") + + components.append("-b \"\(allCookies)\"") + } + } + + var headers = HTTPHeaders() + + if let sessionHeaders = delegate?.sessionConfiguration.headers { + for header in sessionHeaders where header.name != "Cookie" { + headers[header.name] = header.value + } + } + + for header in request.headers where header.name != "Cookie" { + headers[header.name] = header.value + } + + for header in headers { + let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"") + components.append("-H \"\(header.name): \(escapedValue)\"") + } + + if let httpBodyData = request.httpBody { + let httpBody = String(decoding: httpBodyData, as: UTF8.self) + var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") + escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(url.absoluteString)\"") + + return components.joined(separator: " \\\n\t") + } +} + +/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`. +public protocol RequestDelegate: AnyObject { + /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s. + var sessionConfiguration: URLSessionConfiguration { get } + + /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler. + var startImmediately: Bool { get } + + /// Notifies the delegate the `Request` has reached a point where it needs cleanup. + /// + /// - Parameter request: The `Request` to cleanup after. + func cleanup(after request: Request) + + /// Asynchronously ask the delegate whether a `Request` will be retried. + /// + /// - Parameters: + /// - request: `Request` which failed. + /// - error: `Error` which produced the failure. + /// - completion: Closure taking the `RetryResult` for evaluation. + func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) + + /// Asynchronously retry the `Request`. + /// + /// - Parameters: + /// - request: `Request` which will be retried. + /// - timeDelay: `TimeInterval` after which the retry will be triggered. + func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/RequestTaskMap.swift b/ChatBot/Pods/Alamofire/Source/Core/RequestTaskMap.swift new file mode 100644 index 00000000..e49e564a --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/RequestTaskMap.swift @@ -0,0 +1,150 @@ +// +// RequestTaskMap.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s. +struct RequestTaskMap { + private typealias Events = (completed: Bool, metricsGathered: Bool) + + private var tasksToRequests: [URLSessionTask: Request] + private var requestsToTasks: [Request: URLSessionTask] + private var taskEvents: [URLSessionTask: Events] + + var requests: [Request] { + Array(tasksToRequests.values) + } + + init(tasksToRequests: [URLSessionTask: Request] = [:], + requestsToTasks: [Request: URLSessionTask] = [:], + taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) { + self.tasksToRequests = tasksToRequests + self.requestsToTasks = requestsToTasks + self.taskEvents = taskEvents + } + + subscript(_ request: Request) -> URLSessionTask? { + get { requestsToTasks[request] } + set { + guard let newValue else { + guard let task = requestsToTasks[request] else { + fatalError("RequestTaskMap consistency error: no task corresponding to request found.") + } + + requestsToTasks.removeValue(forKey: request) + tasksToRequests.removeValue(forKey: task) + taskEvents.removeValue(forKey: task) + + return + } + + requestsToTasks[request] = newValue + tasksToRequests[newValue] = request + taskEvents[newValue] = (completed: false, metricsGathered: false) + } + } + + subscript(_ task: URLSessionTask) -> Request? { + get { tasksToRequests[task] } + set { + guard let newValue else { + guard let request = tasksToRequests[task] else { + fatalError("RequestTaskMap consistency error: no request corresponding to task found.") + } + + tasksToRequests.removeValue(forKey: task) + requestsToTasks.removeValue(forKey: request) + taskEvents.removeValue(forKey: task) + + return + } + + tasksToRequests[task] = newValue + requestsToTasks[newValue] = task + taskEvents[task] = (completed: false, metricsGathered: false) + } + } + + var count: Int { + precondition(tasksToRequests.count == requestsToTasks.count, + "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") + + return tasksToRequests.count + } + + var eventCount: Int { + precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") + + return taskEvents.count + } + + var isEmpty: Bool { + precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty, + "RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)") + + return tasksToRequests.isEmpty + } + + var isEventsEmpty: Bool { + precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)") + + return taskEvents.isEmpty + } + + mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.") + case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false + case (true, false): self[task] = nil; return true + } + } + + mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool { + guard let events = taskEvents[task] else { + fatalError("RequestTaskMap consistency error: no events corresponding to task found.") + } + + switch (events.completed, events.metricsGathered) { + case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.") + // swift-corelibs-foundation doesn't gather metrics, so unconditionally remove the reference and return true. + #if canImport(FoundationNetworking) + default: self[task] = nil; return true + #else + case (false, false): + if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) { + taskEvents[task] = (completed: true, metricsGathered: false); return false + } else { + // watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true. + self[task] = nil; return true + } + case (false, true): + self[task] = nil; return true + #endif + } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/Response.swift b/ChatBot/Pods/Alamofire/Source/Core/Response.swift new file mode 100644 index 00000000..8a9f089a --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/Response.swift @@ -0,0 +1,453 @@ +// +// Response.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDataResponse = DataResponse +/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFDownloadResponse = DownloadResponse + +/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - data: The `Data` returned by the server. + /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.data = data + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes (if available) a summary + /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the + /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and + /// the `Result` of serialization. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + + let responseDescription = response.map { response in + let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers) + + return """ + \(DebugDescription.description(of: response)) + \(responseBodyDescription.indentingNewlines()) + """ + } ?? "[Response]: None" + + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse { + DataResponse(request: request, + response: response, + data: data, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The final destination URL of the data returned from the server after it is moved. + public let fileURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The final metrics of the response. + /// + /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` + /// + public let metrics: URLSessionTaskMetrics? + + /// The time taken to serialize the response. + public let serializationDuration: TimeInterval + + /// The result of response serialization. + public let result: Result + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Success? { result.success } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Failure? { result.failure } + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - Parameters: + /// - request: The `URLRequest` sent to the server. + /// - response: The `HTTPURLResponse` from the server. + /// - fileURL: The final destination URL of the data returned from the server after it is moved. + /// - resumeData: The resume `Data` generated if the request was cancelled. + /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. + /// - serializationDuration: The duration taken by serialization. + /// - result: The `Result` of response serialization. + public init(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + resumeData: Data?, + metrics: URLSessionTaskMetrics?, + serializationDuration: TimeInterval, + result: Result) { + self.request = request + self.response = response + self.fileURL = fileURL + self.resumeData = resumeData + self.metrics = metrics + self.serializationDuration = serializationDuration + self.result = result + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + "\(result)" + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization + /// actions, and the response serialization result. + public var debugDescription: String { + guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } + + let requestDescription = DebugDescription.description(of: urlRequest) + let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None" + let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" + let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" + + return """ + \(requestDescription) + \(responseDescription) + [File URL]: \(fileURL?.path ?? "None") + [Resume Data]: \(resumeDataDescription) + [Network Duration]: \(networkDuration) + [Serialization Duration]: \(serializationDuration)s + [Result]: \(result) + """ + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.map(transform)) + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMap(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.mapError(transform)) + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse { + DownloadResponse(request: request, + response: response, + fileURL: fileURL, + resumeData: resumeData, + metrics: metrics, + serializationDuration: serializationDuration, + result: result.tryMapError(transform)) + } +} + +private enum DebugDescription { + static func description(of request: URLRequest) -> String { + let requestSummary = "\(request.httpMethod!) \(request)" + let requestHeadersDescription = DebugDescription.description(for: request.headers) + let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers) + + return """ + [Request]: \(requestSummary) + \(requestHeadersDescription.indentingNewlines()) + \(requestBodyDescription.indentingNewlines()) + """ + } + + static func description(of response: HTTPURLResponse) -> String { + """ + [Response]: + [Status Code]: \(response.statusCode) + \(DebugDescription.description(for: response.headers).indentingNewlines()) + """ + } + + static func description(for headers: HTTPHeaders) -> String { + guard !headers.isEmpty else { return "[Headers]: None" } + + let headerDescription = "\(headers.sorted())".indentingNewlines() + return """ + [Headers]: + \(headerDescription) + """ + } + + static func description(for data: Data?, + headers: HTTPHeaders, + allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"], + maximumLength: Int = 100_000) -> String { + guard let data, !data.isEmpty else { return "[Body]: None" } + + guard + data.count <= maximumLength, + printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true) + else { return "[Body]: \(data.count) bytes" } + + return """ + [Body]: + \(String(decoding: data, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + .indentingNewlines()) + """ + } +} + +extension String { + fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String { + let spaces = String(repeating: " ", count: spaceCount) + return replacingOccurrences(of: "\n", with: "\n\(spaces)") + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/Session.swift b/ChatBot/Pods/Alamofire/Source/Core/Session.swift new file mode 100644 index 00000000..0518dcab --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/Session.swift @@ -0,0 +1,1350 @@ +// +// Session.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common +/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response +/// cache handling. +open class Session { + /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified. + public static let `default` = Session() + + /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's + /// `delegate` handles `URLSessionDelegate` callbacks. + /// + /// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will + /// break internal Alamofire logic that tracks those tasks. + /// + public let session: URLSession + /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction. + public let delegate: SessionDelegate + /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue. + public let rootQueue: DispatchQueue + /// Value determining whether this instance automatically calls `resume()` on all created `Request`s. + public let startRequestsImmediately: Bool + /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its + /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile + /// and test before introducing an additional queue. + public let requestQueue: DispatchQueue + /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this + /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined + /// to be a bottleneck. Always profile and test before introducing an additional queue. + public let serializationQueue: DispatchQueue + /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a + /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value. + public let interceptor: RequestInterceptor? + /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning. + public let serverTrustManager: ServerTrustManager? + /// `RedirectHandler` instance used to provide customization for request redirection. + public let redirectHandler: RedirectHandler? + /// `CachedResponseHandler` instance used to provide customization of cached response handling. + public let cachedResponseHandler: CachedResponseHandler? + /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s. + public let eventMonitor: CompositeEventMonitor + /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default. + public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()] + + /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them. + var requestTaskMap = RequestTaskMap() + /// `Set` of currently active `Request`s. + var activeRequests: Set = [] + /// Completion events awaiting `URLSessionTaskMetrics`. + var waitingCompletions: [URLSessionTask: () -> Void] = [:] + + /// Creates a `Session` from a `URLSession` and other parameters. + /// + /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and + /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer. + /// + /// - Parameters: + /// - session: Underlying `URLSession` for this instance. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public init(session: URLSession, + delegate: SessionDelegate, + rootQueue: DispatchQueue, + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(session.configuration.identifier == nil, + "Alamofire does not support background URLSessionConfigurations.") + precondition(session.delegateQueue.underlyingQueue === rootQueue, + "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.") + + self.session = session + self.delegate = delegate + self.rootQueue = rootQueue + self.startRequestsImmediately = startRequestsImmediately + self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue) + self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue) + self.interceptor = interceptor + self.serverTrustManager = serverTrustManager + self.redirectHandler = redirectHandler + self.cachedResponseHandler = cachedResponseHandler + eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors) + delegate.eventMonitor = eventMonitor + delegate.stateProvider = self + } + + /// Creates a `Session` from a `URLSessionConfiguration`. + /// + /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its + /// `delegateQueue`, and is the recommended initializer for most uses. + /// + /// - Parameters: + /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes + /// to this value after being passed to this initializer will have no effect. + /// `URLSessionConfiguration.af.default` by default. + /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request` + /// interaction. `SessionDelegate()` by default. + /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a + /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default. + /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true` + /// by default. If set to `false`, all `Request`s created must have `.resume()` called. + /// on them for them to start. + /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue + /// will use the `rootQueue` as its `target`. A separate queue can be used if it's + /// determined request creation is a bottleneck, but that should only be done after + /// careful testing and profiling. `nil` by default. + /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this + /// queue will use the `rootQueue` as its `target`. A separate queue can be used if + /// it's determined response serialization is a bottleneck, but that should only be + /// done after careful testing and profiling. `nil` by default. + /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil` + /// by default. + /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil` + /// by default. + /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by + /// default. + /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance. + /// `nil` by default. + /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a + /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default. + public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default, + delegate: SessionDelegate = SessionDelegate(), + rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"), + startRequestsImmediately: Bool = true, + requestQueue: DispatchQueue? = nil, + serializationQueue: DispatchQueue? = nil, + interceptor: RequestInterceptor? = nil, + serverTrustManager: ServerTrustManager? = nil, + redirectHandler: RedirectHandler? = nil, + cachedResponseHandler: CachedResponseHandler? = nil, + eventMonitors: [EventMonitor] = []) { + precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.") + + // Retarget the incoming rootQueue for safety, unless it's the main queue, which we know is safe. + let serialRootQueue = (rootQueue === DispatchQueue.main) ? rootQueue : DispatchQueue(label: rootQueue.label, + target: rootQueue) + let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: serialRootQueue, name: "\(serialRootQueue.label).sessionDelegate") + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue) + + self.init(session: session, + delegate: delegate, + rootQueue: serialRootQueue, + startRequestsImmediately: startRequestsImmediately, + requestQueue: requestQueue, + serializationQueue: serializationQueue, + interceptor: interceptor, + serverTrustManager: serverTrustManager, + redirectHandler: redirectHandler, + cachedResponseHandler: cachedResponseHandler, + eventMonitors: eventMonitors) + } + + deinit { + finishRequestsForDeinit() + session.invalidateAndCancel() + } + + // MARK: - All Requests API + + /// Perform an action on all active `Request`s. + /// + /// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and + /// be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`, + /// so care should be taken that actions are fast. Once the work on the `Request`s is complete, any + /// additional work should be performed on another queue. + /// + /// - Parameters: + /// - action: Closure to perform with all `Request`s. + public func withAllRequests(perform action: @escaping (Set) -> Void) { + rootQueue.async { + action(self.activeRequests) + } + } + + /// Cancel all active `Request`s, optionally calling a completion handler when complete. + /// + /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled + /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to + /// completion when cancelled. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default. + /// - completion: Closure to be called when all `Request`s have been cancelled. + public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) { + withAllRequests { requests in + requests.forEach { $0.cancel() } + queue.async { + completion?() + } + } + } + + // MARK: - DataRequest + + /// Closure which provides a `URLRequest` for mutation. + public typealias RequestModifier = (inout URLRequest) throws -> Void + + struct RequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoding: ParameterEncoding + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try encoding.encode(request, with: parameters) + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncoding.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + struct RequestEncodableConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let parameters: Parameters? + let encoder: ParameterEncoder + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return try parameters.map { try encoder.encode($0, into: request) } ?? request + } + } + + /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return request(convertible, interceptor: interceptor) + } + + /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// + /// - Returns: The created `DataRequest`. + open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest { + let request = DataRequest(convertible: convertible, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + // MARK: - DataStreamRequest + + /// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the + /// `URLRequest`. + /// `URLEncodedFormParameterEncoder.default` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from + /// the provided parameters. `nil` by default. + /// + /// - Returns: The created `DataStream` request. + open func streamRequest(_ convertible: URLConvertible, + method: HTTPMethod = .get, + headers: HTTPHeaders? = nil, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil) -> DataStreamRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: Empty?.none, + encoder: URLEncodedFormParameterEncoder.default, + headers: headers, + requestModifier: requestModifier) + + return streamRequest(convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + interceptor: interceptor) + } + + /// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error` + /// is thrown while serializing stream `Data`. `false` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` + /// by default. + /// + /// - Returns: The created `DataStreamRequest`. + open func streamRequest(_ convertible: URLRequestConvertible, + automaticallyCancelOnStreamError: Bool = false, + interceptor: RequestInterceptor? = nil) -> DataStreamRequest { + let request = DataStreamRequest(convertible: convertible, + automaticallyCancelOnStreamError: automaticallyCancelOnStreamError, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + #if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(WebSocket) open func webSocketRequest( + to url: URLConvertible, + configuration: WebSocketRequest.Configuration = .default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil + ) -> WebSocketRequest { + webSocketRequest( + to: url, + configuration: configuration, + parameters: Empty?.none, + encoder: URLEncodedFormParameterEncoder.default, + headers: headers, + interceptor: interceptor, + requestModifier: requestModifier + ) + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(WebSocket) open func webSocketRequest( + to url: URLConvertible, + configuration: WebSocketRequest.Configuration = .default, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil + ) -> WebSocketRequest where Parameters: Encodable { + let convertible = RequestEncodableConvertible(url: url, + method: .get, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + let request = WebSocketRequest(convertible: convertible, + configuration: configuration, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + @_spi(WebSocket) open func webSocketRequest(performing convertible: URLRequestConvertible, + configuration: WebSocketRequest.Configuration = .default, + interceptor: RequestInterceptor? = nil) -> WebSocketRequest { + let request = WebSocketRequest(convertible: convertible, + configuration: configuration, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self) + + perform(request) + + return request + } + #endif + + // MARK: - DownloadRequest + + /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and + /// `Destination`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by + /// default. + /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncoding.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestConvertible(url: convertible, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and + /// a `RequestInterceptor`. + /// + /// - Parameters: + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default. + /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default. + /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. + /// Defaults to `URLEncodedFormParameterEncoder.default`. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + requestModifier: RequestModifier? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let convertible = RequestEncodableConvertible(url: convertible, + method: method, + parameters: parameters, + encoder: encoder, + headers: headers, + requestModifier: requestModifier) + + return download(convertible, interceptor: interceptor, to: destination) + } + + /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`. + /// + /// - Parameters: + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(_ convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .request(convertible), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as + /// well as a `RequestInterceptor`, and a `Destination`. + /// + /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by + /// Alamofire. The file will not be deleted until the system purges the temporary files. + /// + /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1), + /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` + /// generation logic where the data is written incorrectly and will always fail to resume the download. For more + /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462). + /// + /// - Parameters: + /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file + /// should be moved. `nil` by default. + /// + /// - Returns: The created `DownloadRequest`. + open func download(resumingWith data: Data, + interceptor: RequestInterceptor? = nil, + to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { + let request = DownloadRequest(downloadable: .resumeData(data), + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: self, + destination: destination ?? DownloadRequest.defaultDestination) + + perform(request) + + return request + } + + // MARK: - UploadRequest + + struct ParameterlessRequestConvertible: URLRequestConvertible { + let url: URLConvertible + let method: HTTPMethod + let headers: HTTPHeaders? + let requestModifier: RequestModifier? + + func asURLRequest() throws -> URLRequest { + var request = try URLRequest(url: url, method: method, headers: headers) + try requestModifier?(&request) + + return request + } + } + + struct Upload: UploadConvertible { + let request: URLRequestConvertible + let uploadable: UploadableConvertible + + func createUploadable() throws -> UploadRequest.Uploadable { + try uploadable.createUploadable() + } + + func asURLRequest() throws -> URLRequest { + try request.asURLRequest() + } + } + + // MARK: Data + + /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`. + /// + /// - Parameters: + /// - data: The `Data` to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ data: Data, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: File + + /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided + /// components and `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - fileURL: The `URL` of the file to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ fileURL: URL, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided + /// parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + to convertible: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: convertible, + method: method, + headers: headers, + requestModifier: requestModifier) + + return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and + /// `RequestInterceptor`. + /// + /// - Parameters: + /// - stream: The `InputStream` that provides the data to upload. + /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(_ stream: InputStream, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: MultipartFormData + + /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided + /// `URLRequest` components and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: convertible, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible` + /// value, and a `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` building closure. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let formData = MultipartFormData(fileManager: fileManager) + multipartFormData(formData) + + return upload(multipartFormData: formData, + with: request, + usingThreshold: encodingMemoryThreshold, + interceptor: interceptor, + fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components + /// and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default. + /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is + /// written to disk before being uploaded. `.default` instance by default. + /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the + /// provided parameters. `nil` by default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + to url: URLConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default, + requestModifier: RequestModifier? = nil) -> UploadRequest { + let convertible = ParameterlessRequestConvertible(url: url, + method: method, + headers: headers, + requestModifier: requestModifier) + + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: convertible, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible` + /// value and `RequestInterceptor`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// - Parameters: + /// - multipartFormData: `MultipartFormData` instance to upload. + /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`. + /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or + /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by + /// default. + /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by + /// default. + /// + /// - Returns: The created `UploadRequest`. + open func upload(multipartFormData: MultipartFormData, + with request: URLRequestConvertible, + usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold, + interceptor: RequestInterceptor? = nil, + fileManager: FileManager = .default) -> UploadRequest { + let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold, + request: request, + multipartFormData: multipartFormData) + + return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager) + } + + // MARK: - Internal API + + // MARK: Uploadable + + func upload(_ uploadable: UploadRequest.Uploadable, + with convertible: URLRequestConvertible, + interceptor: RequestInterceptor?, + fileManager: FileManager) -> UploadRequest { + let uploadable = Upload(request: convertible, uploadable: uploadable) + + return upload(uploadable, interceptor: interceptor, fileManager: fileManager) + } + + func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest { + let request = UploadRequest(convertible: upload, + underlyingQueue: rootQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + fileManager: fileManager, + delegate: self) + + perform(request) + + return request + } + + // MARK: Perform + + /// Starts performing the provided `Request`. + /// + /// - Parameter request: The `Request` to perform. + func perform(_ request: Request) { + rootQueue.async { + guard !request.isCancelled else { return } + + self.activeRequests.insert(request) + + self.requestQueue.async { + // Leaf types must come first, otherwise they will cast as their superclass. + switch request { + case let r as UploadRequest: self.performUploadRequest(r) // UploadRequest must come before DataRequest due to subtype relationship. + case let r as DataRequest: self.performDataRequest(r) + case let r as DownloadRequest: self.performDownloadRequest(r) + case let r as DataStreamRequest: self.performDataStreamRequest(r) + default: + #if canImport(Darwin) && !canImport(FoundationNetworking) + if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *), + let request = request as? WebSocketRequest { + self.performWebSocketRequest(request) + } else { + fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + } + #else + fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))") + #endif + } + } + } + } + + func performDataRequest(_ request: DataRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + func performDataStreamRequest(_ request: DataStreamRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + + #if canImport(Darwin) && !canImport(FoundationNetworking) + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + func performWebSocketRequest(_ request: WebSocketRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) + } + #endif + + func performUploadRequest(_ request: UploadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + performSetupOperations(for: request, convertible: request.convertible) { + do { + let uploadable = try request.upload.createUploadable() + self.rootQueue.async { request.didCreateUploadable(uploadable) } + return true + } catch { + self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) } + return false + } + } + } + + func performDownloadRequest(_ request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + switch request.downloadable { + case let .request(convertible): + performSetupOperations(for: request, convertible: convertible) + case let .resumeData(resumeData): + rootQueue.async { self.didReceiveResumeData(resumeData, for: request) } + } + } + + func performSetupOperations(for request: Request, + convertible: URLRequestConvertible, + shouldCreateTask: @escaping () -> Bool = { true }) { + dispatchPrecondition(condition: .onQueue(requestQueue)) + + let initialRequest: URLRequest + + do { + initialRequest = try convertible.asURLRequest() + try initialRequest.validate() + } catch { + rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) } + return + } + + rootQueue.async { request.didCreateInitialURLRequest(initialRequest) } + + guard !request.isCancelled else { return } + + guard let adapter = adapter(for: request) else { + guard shouldCreateTask() else { return } + rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) } + return + } + + let adapterState = RequestAdapterState(requestID: request.id, session: self) + + adapter.adapt(initialRequest, using: adapterState) { result in + do { + let adaptedRequest = try result.get() + try adaptedRequest.validate() + + self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) } + + guard shouldCreateTask() else { return } + + self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) } + } catch { + self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) } + } + } + } + + // MARK: - Task Handling + + func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.didCreateURLRequest(urlRequest) + + guard !request.isCancelled else { return } + + let task = request.task(for: urlRequest, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func didReceiveResumeData(_ data: Data, for request: DownloadRequest) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + guard !request.isCancelled else { return } + + let task = request.task(forResumeData: data, using: session) + requestTaskMap[request] = task + request.didCreateTask(task) + + updateStatesForTask(task, request: request) + } + + func updateStatesForTask(_ task: URLSessionTask, request: Request) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + request.withState { state in + switch state { + case .initialized, .finished: + // Do nothing. + break + case .resumed: + task.resume() + rootQueue.async { request.didResumeTask(task) } + case .suspended: + task.suspend() + rootQueue.async { request.didSuspendTask(task) } + case .cancelled: + // Resume to ensure metrics are gathered. + task.resume() + task.cancel() + rootQueue.async { request.didCancelTask(task) } + } + } + } + + // MARK: - Adapters and Retriers + + func adapter(for request: Request) -> RequestAdapter? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(adapters: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + func retrier(for request: Request) -> RequestRetrier? { + if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor { + return Interceptor(retriers: [requestInterceptor, sessionInterceptor]) + } else { + return request.interceptor ?? interceptor + } + } + + // MARK: - Invalidation + + func finishRequestsForDeinit() { + for request in requestTaskMap.requests { + rootQueue.async { + request.finish(error: AFError.sessionDeinitialized) + } + } + } +} + +// MARK: - RequestDelegate + +extension Session: RequestDelegate { + public var sessionConfiguration: URLSessionConfiguration { + session.configuration + } + + public var startImmediately: Bool { startRequestsImmediately } + + public func cleanup(after request: Request) { + activeRequests.remove(request) + } + + public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) { + guard let retrier = retrier(for: request) else { + rootQueue.async { completion(.doNotRetry) } + return + } + + retrier.retry(request, for: self, dueTo: error) { retryResult in + self.rootQueue.async { + guard let retryResultError = retryResult.error else { completion(retryResult); return } + + let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error) + completion(.doNotRetryWithError(retryError)) + } + } + } + + public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) { + rootQueue.async { + let retry: () -> Void = { + guard !request.isCancelled else { return } + + request.prepareForRetry() + self.perform(request) + } + + if let retryDelay = timeDelay { + self.rootQueue.after(retryDelay) { retry() } + } else { + retry() + } + } + } +} + +// MARK: - SessionStateProvider + +extension Session: SessionStateProvider { + func request(for task: URLSessionTask) -> Request? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task] + } + + func didGatherMetricsForTask(_ task: URLSessionTask) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task) + + if didDisassociate { + waitingCompletions[task]?() + waitingCompletions[task] = nil + } + } + + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task) + + if didDisassociate { + completion() + } else { + waitingCompletions[task] = completion + } + } + + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + return requestTaskMap[task]?.credential ?? + session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace) + } + + func cancelRequestsForSessionInvalidation(with error: Error?) { + dispatchPrecondition(condition: .onQueue(rootQueue)) + + requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/SessionDelegate.swift b/ChatBot/Pods/Alamofire/Source/Core/SessionDelegate.swift new file mode 100644 index 00000000..de0fcbb7 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/SessionDelegate.swift @@ -0,0 +1,387 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. +open class SessionDelegate: NSObject { + private let fileManager: FileManager + + weak var stateProvider: SessionStateProvider? + var eventMonitor: EventMonitor? + + /// Creates an instance from the given `FileManager`. + /// + /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. + /// `.default` by default. + public init(fileManager: FileManager = .default) { + self.fileManager = fileManager + } + + /// Internal method to find and cast requests while maintaining some integrity checking. + /// + /// - Parameters: + /// - task: The `URLSessionTask` for which to find the associated `Request`. + /// - type: The `Request` subclass type to cast any `Request` associate with `task`. + func request(for task: URLSessionTask, as type: R.Type) -> R? { + guard let provider = stateProvider else { + assertionFailure("StateProvider is nil for task \(task.taskIdentifier).") + return nil + } + + return provider.request(for: task) as? R + } +} + +/// Type which provides various `Session` state values. +protocol SessionStateProvider: AnyObject { + var serverTrustManager: ServerTrustManager? { get } + var redirectHandler: RedirectHandler? { get } + var cachedResponseHandler: CachedResponseHandler? { get } + + func request(for task: URLSessionTask) -> Request? + func didGatherMetricsForTask(_ task: URLSessionTask) + func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) + func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? + func cancelRequestsForSessionInvalidation(with error: Error?) +} + +// MARK: URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) + + stateProvider?.cancelRequestsForSessionInvalidation(with: error) + } +} + +// MARK: URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Result of a `URLAuthenticationChallenge` evaluation. + typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + eventMonitor?.urlSession(session, task: task, didReceive: challenge) + + let evaluation: ChallengeEvaluation + switch challenge.protectionSpace.authenticationMethod { + case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, + NSURLAuthenticationMethodNegotiate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #if canImport(Security) + case NSURLAuthenticationMethodServerTrust: + evaluation = attemptServerTrustAuthentication(with: challenge) + case NSURLAuthenticationMethodClientCertificate: + evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) + #endif + default: + evaluation = (.performDefaultHandling, nil, nil) + } + + if let error = evaluation.error { + stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) + } + + completionHandler(evaluation.disposition, evaluation.credential) + } + + #if canImport(Security) + /// Evaluates the server trust `URLAuthenticationChallenge` received. + /// + /// - Parameter challenge: The `URLAuthenticationChallenge`. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { + let host = challenge.protectionSpace.host + + guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, + let trust = challenge.protectionSpace.serverTrust + else { + return (.performDefaultHandling, nil, nil) + } + + do { + guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { + return (.performDefaultHandling, nil, nil) + } + + try evaluator.evaluate(trust, forHost: host) + + return (.useCredential, URLCredential(trust: trust), nil) + } catch { + return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) + } + } + #endif + + /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. + /// + /// - Parameters: + /// - challenge: The `URLAuthenticationChallenge`. + /// - task: The `URLSessionTask` which received the challenge. + /// + /// - Returns: The `ChallengeEvaluation`. + func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, + belongingTo task: URLSessionTask) -> ChallengeEvaluation { + guard challenge.previousFailureCount == 0 else { + return (.rejectProtectionSpace, nil, nil) + } + + guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { + return (.performDefaultHandling, nil, nil) + } + + return (.useCredential, credential, nil) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + eventMonitor?.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + + stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { + eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) + + guard let request = request(for: task, as: UploadRequest.self) else { + assertionFailure("needNewBodyStream did not find UploadRequest.") + completionHandler(nil) + return + } + + completionHandler(request.inputStream()) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { + eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) + + if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { + redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) + } else { + completionHandler(request) + } + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) + + stateProvider?.request(for: task)?.didGatherMetrics(metrics) + + stateProvider?.didGatherMetricsForTask(task) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { +// NSLog("URLSession: \(session), task: \(task), didCompleteWithError: \(error)") + eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) + + let request = stateProvider?.request(for: task) + + stateProvider?.didCompleteTask(task) { + request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) + } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) + } +} + +// MARK: URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: response) + + guard let response = response as? HTTPURLResponse else { completionHandler(.allow); return } + + if let request = request(for: dataTask, as: DataRequest.self) { + request.didReceiveResponse(response, completionHandler: completionHandler) + } else if let request = request(for: dataTask, as: DataStreamRequest.self) { + request.didReceiveResponse(response, completionHandler: completionHandler) + } else { + assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive response") + completionHandler(.allow) + return + } + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) + + if let request = request(for: dataTask, as: DataRequest.self) { + request.didReceive(data: data) + } else if let request = request(for: dataTask, as: DataStreamRequest.self) { + request.didReceive(data: data) + } else { + assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive data") + return + } + } + + open func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) { + eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) + + if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { + handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: URLSessionWebSocketDelegate + +#if canImport(Darwin) && !canImport(FoundationNetworking) + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension SessionDelegate: URLSessionWebSocketDelegate { + open func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { + // TODO: Add event monitor method. +// NSLog("URLSession: \(session), webSocketTask: \(webSocketTask), didOpenWithProtocol: \(`protocol` ?? "None")") + guard let request = request(for: webSocketTask, as: WebSocketRequest.self) else { + return + } + + request.didConnect(protocol: `protocol`) + } + + open func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + // TODO: Add event monitor method. +// NSLog("URLSession: \(session), webSocketTask: \(webSocketTask), didCloseWithCode: \(closeCode.rawValue), reason: \(reason ?? Data())") + guard let request = request(for: webSocketTask, as: WebSocketRequest.self) else { + return + } + + // On 2021 OSes and above, empty reason is returned as empty Data rather than nil, so make it nil always. + let reason = (reason?.isEmpty == true) ? nil : reason + request.didDisconnect(closeCode: closeCode, reason: reason) + } +} + +#endif + +// MARK: URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, + totalBytesExpectedToWrite: expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + eventMonitor?.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + + guard let request = request(for: downloadTask, as: DownloadRequest.self) else { + assertionFailure("downloadTask did not find DownloadRequest.") + return + } + + let (destination, options): (URL, DownloadRequest.Options) + if let response = request.response { + (destination, options) = request.destination(location, response) + } else { + // If there's no response this is likely a local file download, so generate the temporary URL directly. + (destination, options) = (DownloadRequest.defaultDestinationURL(location), []) + } + + eventMonitor?.request(request, didCreateDestinationURL: destination) + + do { + if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { + try fileManager.removeItem(at: destination) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destination.deletingLastPathComponent() + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try fileManager.moveItem(at: location, to: destination) + + request.didFinishDownloading(using: downloadTask, with: .success(destination)) + } catch { + request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, + source: location, + destination: destination))) + } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/URLConvertible+URLRequestConvertible.swift b/ChatBot/Pods/Alamofire/Source/Core/URLConvertible+URLRequestConvertible.swift new file mode 100644 index 00000000..4f3e6ec2 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/URLConvertible+URLRequestConvertible.swift @@ -0,0 +1,105 @@ +// +// URLConvertible+URLRequestConvertible.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct `URL`s, which can then be used to construct +/// `URLRequest`s. +public protocol URLConvertible { + /// Returns a `URL` from the conforming instance or throws. + /// + /// - Returns: The `URL` created from the instance. + /// - Throws: Any error thrown while creating the `URL`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a `URL` if `self` can be used to initialize a `URL` instance, otherwise throws. + /// + /// - Returns: The `URL` initialized with `self`. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + + return url + } +} + +extension URL: URLConvertible { + /// Returns `self`. + public func asURL() throws -> URL { self } +} + +extension URLComponents: URLConvertible { + /// Returns a `URL` if the `self`'s `url` is not nil, otherwise throws. + /// + /// - Returns: The `URL` from the `url` property. + /// - Throws: An `AFError.invalidURL` instance. + public func asURL() throws -> URL { + guard let url else { throw AFError.invalidURL(url: self) } + + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to safely construct `URLRequest`s. +public protocol URLRequestConvertible { + /// Returns a `URLRequest` or throws if an `Error` was encountered. + /// + /// - Returns: A `URLRequest`. + /// - Throws: Any error thrown while constructing the `URLRequest`. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The `URLRequest` returned by discarding any `Error` encountered. + public var urlRequest: URLRequest? { try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns `self`. + public func asURLRequest() throws -> URLRequest { self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `url`, `method`, and `headers`. + /// + /// - Parameters: + /// - url: The `URLConvertible` value. + /// - method: The `HTTPMethod`. + /// - headers: The `HTTPHeaders`, `nil` by default. + /// - Throws: Any error thrown while converting the `URLConvertible` to a `URL`. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + allHTTPHeaderFields = headers?.dictionary + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Core/UploadRequest.swift b/ChatBot/Pods/Alamofire/Source/Core/UploadRequest.swift new file mode 100644 index 00000000..854373b5 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/UploadRequest.swift @@ -0,0 +1,174 @@ +// +// UploadRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`. +public final class UploadRequest: DataRequest { + /// Type describing the origin of the upload, whether `Data`, file, or stream. + public enum Uploadable { + /// Upload from the provided `Data` value. + case data(Data) + /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be + /// automatically removed once uploaded. + case file(URL, shouldRemove: Bool) + /// Upload from the provided `InputStream`. + case stream(InputStream) + } + + // MARK: Initial State + + /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance. + public let upload: UploadableConvertible + + /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written + /// to disk. + public let fileManager: FileManager + + // MARK: Mutable State + + /// `Uploadable` value used by the instance. + public var uploadable: Uploadable? + + /// Creates an `UploadRequest` using the provided parameters. + /// + /// - Parameters: + /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default. + /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed. + /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed. + /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets + /// `underlyingQueue`, but can be passed another queue from a `Session`. + /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions. + /// - interceptor: `RequestInterceptor` used throughout the request lifecycle. + /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form + /// encoded payloads written to disk. + /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`. + init(id: UUID = UUID(), + convertible: UploadConvertible, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + fileManager: FileManager, + delegate: RequestDelegate) { + upload = convertible + self.fileManager = fileManager + + super.init(id: id, + convertible: convertible, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + /// Called when the `Uploadable` value has been created from the `UploadConvertible`. + /// + /// - Parameter uploadable: The `Uploadable` that was created. + func didCreateUploadable(_ uploadable: Uploadable) { + self.uploadable = uploadable + + eventMonitor?.request(self, didCreateUploadable: uploadable) + } + + /// Called when the `Uploadable` value could not be created. + /// + /// - Parameter error: `AFError` produced by the failure. + func didFailToCreateUploadable(with error: AFError) { + self.error = error + + eventMonitor?.request(self, didFailToCreateUploadableWithError: error) + + retryOrFinish(error: error) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + guard let uploadable else { + fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.") + } + + switch uploadable { + case let .data(data): return session.uploadTask(with: request, from: data) + case let .file(url, _): return session.uploadTask(with: request, fromFile: url) + case .stream: return session.uploadTask(withStreamedRequest: request) + } + } + + override func reset() { + // Uploadable must be recreated on every retry. + uploadable = nil + + super.reset() + } + + /// Produces the `InputStream` from `uploadable`, if it can. + /// + /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash. + /// + /// - Returns: The `InputStream`. + func inputStream() -> InputStream { + guard let uploadable else { + fatalError("Attempting to access the input stream but the uploadable doesn't exist.") + } + + guard case let .stream(stream) = uploadable else { + fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.") + } + + eventMonitor?.request(self, didProvideInputStream: stream) + + return stream + } + + override public func cleanup() { + defer { super.cleanup() } + + guard + let uploadable, + case let .file(url, shouldRemove) = uploadable, + shouldRemove + else { return } + + try? fileManager.removeItem(at: url) + } +} + +/// A type that can produce an `UploadRequest.Uploadable` value. +public protocol UploadableConvertible { + /// Produces an `UploadRequest.Uploadable` value from the instance. + /// + /// - Returns: The `UploadRequest.Uploadable`. + /// - Throws: Any `Error` produced during creation. + func createUploadable() throws -> UploadRequest.Uploadable +} + +extension UploadRequest.Uploadable: UploadableConvertible { + public func createUploadable() throws -> UploadRequest.Uploadable { + self + } +} + +/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`. +public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {} diff --git a/ChatBot/Pods/Alamofire/Source/Core/WebSocketRequest.swift b/ChatBot/Pods/Alamofire/Source/Core/WebSocketRequest.swift new file mode 100644 index 00000000..12b6c708 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Core/WebSocketRequest.swift @@ -0,0 +1,564 @@ +// +// WebSocketRequest.swift +// +// Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask. + +import Foundation + +/// `Request` subclass which manages a WebSocket connection using `URLSessionWebSocketTask`. +/// +/// - Note: This type is currently experimental. There will be breaking changes before the final public release, +/// especially around adoption of the typed throws feature in Swift 6. Please report any missing features or +/// bugs to https://github.com/Alamofire/Alamofire/issues. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +@_spi(WebSocket) public final class WebSocketRequest: Request { + enum IncomingEvent { + case connected(protocol: String?) + case receivedMessage(URLSessionWebSocketTask.Message) + case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) + case completed(Completion) + } + + public struct Event { + public enum Kind { + case connected(protocol: String?) + case receivedMessage(Success) + case serializerFailed(Failure) + // Only received if the server disconnects or we cancel with code, not if we do a simple cancel or error. + case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) + case completed(Completion) + } + + weak var socket: WebSocketRequest? + + public let kind: Kind + public var message: Success? { + guard case let .receivedMessage(message) = kind else { return nil } + + return message + } + + init(socket: WebSocketRequest, kind: Kind) { + self.socket = socket + self.kind = kind + } + + public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) { + socket?.close(sending: closeCode, reason: reason) + } + + public func cancel() { + socket?.cancel() + } + + public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping (PingResponse) -> Void) { + socket?.sendPing(respondingOn: queue, onResponse: onResponse) + } + } + + public struct Completion { + /// Last `URLRequest` issued by the instance. + public let request: URLRequest? + /// Last `HTTPURLResponse` received by the instance. + public let response: HTTPURLResponse? + /// Last `URLSessionTaskMetrics` produced for the instance. + public let metrics: URLSessionTaskMetrics? + /// `AFError` produced for the instance, if any. + public let error: AFError? + } + + public struct Configuration { + public static var `default`: Self { Self() } + + public static func `protocol`(_ protocol: String) -> Self { + Self(protocol: `protocol`) + } + + public static func maximumMessageSize(_ maximumMessageSize: Int) -> Self { + Self(maximumMessageSize: maximumMessageSize) + } + + public static func pingInterval(_ pingInterval: TimeInterval) -> Self { + Self(pingInterval: pingInterval) + } + + public let `protocol`: String? + public let maximumMessageSize: Int + public let pingInterval: TimeInterval? + + init(protocol: String? = nil, maximumMessageSize: Int = 1_048_576, pingInterval: TimeInterval? = nil) { + self.protocol = `protocol` + self.maximumMessageSize = maximumMessageSize + self.pingInterval = pingInterval + } + } + + /// Response to a sent ping. + public enum PingResponse { + public struct Pong { + let start: Date + let end: Date + let latency: TimeInterval + } + + /// Received a pong with the associated state. + case pong(Pong) + /// Received an error. + case error(Error) + /// Did not send the ping, the request is cancelled or suspended. + case unsent + } + + struct SocketMutableState { + var enqueuedSends: [(message: URLSessionWebSocketTask.Message, + queue: DispatchQueue, + completionHandler: (Result) -> Void)] = [] + var handlers: [(queue: DispatchQueue, handler: (_ event: IncomingEvent) -> Void)] = [] + var pingTimerItem: DispatchWorkItem? + } + + let socketMutableState = Protected(SocketMutableState()) + + var socket: URLSessionWebSocketTask? { + task as? URLSessionWebSocketTask + } + + public let convertible: URLRequestConvertible + public let configuration: Configuration + + init(id: UUID = UUID(), + convertible: URLRequestConvertible, + configuration: Configuration, + underlyingQueue: DispatchQueue, + serializationQueue: DispatchQueue, + eventMonitor: EventMonitor?, + interceptor: RequestInterceptor?, + delegate: RequestDelegate) { + self.convertible = convertible + self.configuration = configuration + + super.init(id: id, + underlyingQueue: underlyingQueue, + serializationQueue: serializationQueue, + eventMonitor: eventMonitor, + interceptor: interceptor, + delegate: delegate) + } + + override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask { + var copiedRequest = request + let task: URLSessionWebSocketTask + if let `protocol` = configuration.protocol { + copiedRequest.headers.update(.websocketProtocol(`protocol`)) + task = session.webSocketTask(with: copiedRequest) + } else { + task = session.webSocketTask(with: copiedRequest) + } + task.maximumMessageSize = configuration.maximumMessageSize + + return task + } + + override func didCreateTask(_ task: URLSessionTask) { + super.didCreateTask(task) + + guard let webSocketTask = task as? URLSessionWebSocketTask else { + fatalError("Invalid task of type \(task.self) created for WebSocketRequest.") + } + // TODO: What about the any old tasks? Reset their receive? + listen(to: webSocketTask) + + // Empty pending messages. + socketMutableState.write { state in + guard !state.enqueuedSends.isEmpty else { return } + + let sends = state.enqueuedSends + self.underlyingQueue.async { + for send in sends { + webSocketTask.send(send.message) { error in + send.queue.async { + send.completionHandler(Result(value: (), error: error)) + } + } + } + } + + state.enqueuedSends = [] + } + } + + func didClose() { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + mutableState.write { mutableState in + // Check whether error is cancellation or other websocket closing error. + // If so, remove it. + // Otherwise keep it. + if case let .sessionTaskFailed(error) = mutableState.error, (error as? URLError)?.code == .cancelled { + mutableState.error = nil + } + } + + // TODO: Still issue this event? + eventMonitor?.requestDidCancel(self) + } + + @discardableResult + public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) -> Self { + cancelAutomaticPing() + + mutableState.write { mutableState in + guard mutableState.state.canTransitionTo(.cancelled) else { return } + + mutableState.state = .cancelled + + underlyingQueue.async { self.didClose() } + + guard let task = mutableState.tasks.last, task.state != .completed else { + underlyingQueue.async { self.finish() } + return + } + + // Resume to ensure metrics are gathered. + task.resume() + // Cast from state directly, not the property, otherwise the lock is recursive. + (mutableState.tasks.last as? URLSessionWebSocketTask)?.cancel(with: closeCode, reason: reason) + underlyingQueue.async { self.didCancelTask(task) } + } + + return self + } + + @discardableResult + override public func cancel() -> Self { + cancelAutomaticPing() + + return super.cancel() + } + + func didConnect(protocol: String?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + socketMutableState.read { state in + // TODO: Capture HTTPURLResponse here too? + for handler in state.handlers { + // Saved handler calls out to serializationQueue immediately, then to handler's queue. + handler.handler(.connected(protocol: `protocol`)) + } + } + + if let pingInterval = configuration.pingInterval { + startAutomaticPing(every: pingInterval) + } + } + + public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping (PingResponse) -> Void) { + guard isResumed else { + queue.async { onResponse(.unsent) } + return + } + + let start = Date() + let startTimestamp = ProcessInfo.processInfo.systemUptime + socket?.sendPing { error in + // Calls back on delegate queue / rootQueue / underlyingQueue + if let error { + queue.async { + onResponse(.error(error)) + } + // TODO: What to do with failed ping? Configure for failure, auto retry, or stop pinging? + } else { + let end = Date() + let endTimestamp = ProcessInfo.processInfo.systemUptime + let pong = PingResponse.Pong(start: start, end: end, latency: endTimestamp - startTimestamp) + + queue.async { + onResponse(.pong(pong)) + } + } + } + } + + func startAutomaticPing(every pingInterval: TimeInterval) { + socketMutableState.write { mutableState in + guard isResumed else { + // Defer out of lock. + defer { cancelAutomaticPing() } + return + } + + let item = DispatchWorkItem { [weak self] in + guard let self, self.isResumed else { return } + + self.sendPing(respondingOn: self.underlyingQueue) { response in + guard case .pong = response else { return } + + self.startAutomaticPing(every: pingInterval) + } + } + + mutableState.pingTimerItem = item + underlyingQueue.asyncAfter(deadline: .now() + pingInterval, execute: item) + } + } + + #if swift(>=5.8) + @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) + func startAutomaticPing(every duration: Duration) { + let interval = TimeInterval(duration.components.seconds) + (Double(duration.components.attoseconds) / 1e18) + startAutomaticPing(every: interval) + } + #endif + + func cancelAutomaticPing() { + socketMutableState.write { mutableState in + mutableState.pingTimerItem?.cancel() + mutableState.pingTimerItem = nil + } + } + + func didDisconnect(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + dispatchPrecondition(condition: .onQueue(underlyingQueue)) + + cancelAutomaticPing() + socketMutableState.read { state in + for handler in state.handlers { + // Saved handler calls out to serializationQueue immediately, then to handler's queue. + handler.handler(.disconnected(closeCode: closeCode, reason: reason)) + } + } + } + + private func listen(to task: URLSessionWebSocketTask) { + // TODO: Do we care about the cycle while receiving? + task.receive { result in + switch result { + case let .success(message): + self.socketMutableState.read { state in + for handler in state.handlers { + // Saved handler calls out to serializationQueue immediately, then to handler's queue. + handler.handler(.receivedMessage(message)) + } + } + + self.listen(to: task) + case .failure: + // It doesn't seem like any relevant errors are received here, just incorrect garbage, like errors when + // the socket disconnects. + break + } + } + } + + @discardableResult + public func streamSerializer( + _ serializer: Serializer, + on queue: DispatchQueue = .main, + handler: @escaping (_ event: Event) -> Void + ) -> Self where Serializer: WebSocketMessageSerializer, Serializer.Failure == Error { + forIncomingEvent(on: queue) { incomingEvent in + let event: Event + switch incomingEvent { + case let .connected(`protocol`): + event = .init(socket: self, kind: .connected(protocol: `protocol`)) + case let .receivedMessage(message): + do { + let serializedMessage = try serializer.decode(message) + event = .init(socket: self, kind: .receivedMessage(serializedMessage)) + } catch { + event = .init(socket: self, kind: .serializerFailed(error)) + } + case let .disconnected(closeCode, reason): + event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason)) + case let .completed(completion): + event = .init(socket: self, kind: .completed(completion)) + } + + queue.async { handler(event) } + } + } + + @discardableResult + public func streamDecodableEvents( + _ type: Value.Type = Value.self, + on queue: DispatchQueue = .main, + using decoder: DataDecoder = JSONDecoder(), + handler: @escaping (_ event: Event) -> Void + ) -> Self where Value: Decodable { + streamSerializer(DecodableWebSocketMessageDecoder(decoder: decoder), on: queue, handler: handler) + } + + @discardableResult + public func streamDecodable( + _ type: Value.Type = Value.self, + on queue: DispatchQueue = .main, + using decoder: DataDecoder = JSONDecoder(), + handler: @escaping (_ value: Value) -> Void + ) -> Self where Value: Decodable { + streamDecodableEvents(Value.self, on: queue) { event in + event.message.map(handler) + } + } + + @discardableResult + public func streamMessageEvents( + on queue: DispatchQueue = .main, + handler: @escaping (_ event: Event) -> Void + ) -> Self { + forIncomingEvent(on: queue) { incomingEvent in + let event: Event + switch incomingEvent { + case let .connected(`protocol`): + event = .init(socket: self, kind: .connected(protocol: `protocol`)) + case let .receivedMessage(message): + event = .init(socket: self, kind: .receivedMessage(message)) + case let .disconnected(closeCode, reason): + event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason)) + case let .completed(completion): + event = .init(socket: self, kind: .completed(completion)) + } + + queue.async { handler(event) } + } + } + + @discardableResult + public func streamMessages( + on queue: DispatchQueue = .main, + handler: @escaping (_ message: URLSessionWebSocketTask.Message) -> Void + ) -> Self { + streamMessageEvents(on: queue) { event in + event.message.map(handler) + } + } + + func forIncomingEvent(on queue: DispatchQueue, handler: @escaping (IncomingEvent) -> Void) -> Self { + socketMutableState.write { state in + state.handlers.append((queue: queue, handler: { incomingEvent in + self.serializationQueue.async { + handler(incomingEvent) + } + })) + } + + appendResponseSerializer { + self.responseSerializerDidComplete { + self.serializationQueue.async { + handler(.completed(.init(request: self.request, + response: self.response, + metrics: self.metrics, + error: self.error))) + } + } + } + + return self + } + + public func send(_ message: URLSessionWebSocketTask.Message, + queue: DispatchQueue = .main, + completionHandler: @escaping (Result) -> Void) { + guard !(isCancelled || isFinished) else { return } + + guard let socket else { + // URLSessionWebSocketTask not created yet, enqueue the send. + socketMutableState.write { mutableState in + mutableState.enqueuedSends.append((message, queue, completionHandler)) + } + + return + } + + socket.send(message) { error in + queue.async { + completionHandler(Result(value: (), error: error)) + } + } + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public protocol WebSocketMessageSerializer { + associatedtype Output + associatedtype Failure: Error = Error + + func decode(_ message: URLSessionWebSocketTask.Message) throws -> Output +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension WebSocketMessageSerializer { + public static func json( + decoding _: Value.Type = Value.self, + using decoder: JSONDecoder = JSONDecoder() + ) -> DecodableWebSocketMessageDecoder where Self == DecodableWebSocketMessageDecoder { + Self(decoder: decoder) + } + + static var passthrough: PassthroughWebSocketMessageDecoder { + PassthroughWebSocketMessageDecoder() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +struct PassthroughWebSocketMessageDecoder: WebSocketMessageSerializer { + public typealias Failure = Never + + public func decode(_ message: URLSessionWebSocketTask.Message) -> URLSessionWebSocketTask.Message { + message + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DecodableWebSocketMessageDecoder: WebSocketMessageSerializer { + public enum Error: Swift.Error { + case decoding(Swift.Error) + case unknownMessage(description: String) + } + + public let decoder: DataDecoder + + public init(decoder: DataDecoder) { + self.decoder = decoder + } + + public func decode(_ message: URLSessionWebSocketTask.Message) throws -> Value { + let data: Data + switch message { + case let .data(messageData): + data = messageData + case let .string(string): + data = Data(string.utf8) + @unknown default: + throw Error.unknownMessage(description: String(describing: message)) + } + + do { + return try decoder.decode(Value.self, from: data) + } catch { + throw Error.decoding(error) + } + } +} + +#endif diff --git a/ChatBot/Pods/Alamofire/Source/Extensions/DispatchQueue+Alamofire.swift b/ChatBot/Pods/Alamofire/Source/Extensions/DispatchQueue+Alamofire.swift new file mode 100644 index 00000000..10cd273e --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Extensions/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Dispatch +import Foundation + +extension DispatchQueue { + /// Execute the provided closure after a `TimeInterval`. + /// + /// - Parameters: + /// - delay: `TimeInterval` to delay execution. + /// - closure: Closure to execute. + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Extensions/OperationQueue+Alamofire.swift b/ChatBot/Pods/Alamofire/Source/Extensions/OperationQueue+Alamofire.swift new file mode 100644 index 00000000..b06a0ccc --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Extensions/OperationQueue+Alamofire.swift @@ -0,0 +1,49 @@ +// +// OperationQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension OperationQueue { + /// Creates an instance using the provided parameters. + /// + /// - Parameters: + /// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default. + /// - maxConcurrentOperationCount: Maximum concurrent operations. + /// `OperationQueue.defaultMaxConcurrentOperationCount` by default. + /// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default. + /// - name: Name for the queue. `nil` by default. + /// - startSuspended: Whether the queue starts suspended. `false` by default. + convenience init(qualityOfService: QualityOfService = .default, + maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, + underlyingQueue: DispatchQueue? = nil, + name: String? = nil, + startSuspended: Bool = false) { + self.init() + self.qualityOfService = qualityOfService + self.maxConcurrentOperationCount = maxConcurrentOperationCount + self.underlyingQueue = underlyingQueue + self.name = name + isSuspended = startSuspended + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Extensions/Result+Alamofire.swift b/ChatBot/Pods/Alamofire/Source/Extensions/Result+Alamofire.swift new file mode 100644 index 00000000..0a28a69d --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Extensions/Result+Alamofire.swift @@ -0,0 +1,120 @@ +// +// Result+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Default type of `Result` returned by Alamofire, with an `AFError` `Failure` type. +public typealias AFResult = Result + +// MARK: - Internal APIs + +extension Result { + /// Returns whether the instance is `.success`. + var isSuccess: Bool { + guard case .success = self else { return false } + return true + } + + /// Returns whether the instance is `.failure`. + var isFailure: Bool { + !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + var success: Success? { + guard case let .success(value) = self else { return nil } + return value + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + var failure: Failure? { + guard case let .failure(error) = self else { return nil } + return error + } + + /// Initializes a `Result` from value or error. Returns `.failure` if the error is non-nil, `.success` otherwise. + /// + /// - Parameters: + /// - value: A value. + /// - error: An `Error`. + init(value: Success, error: Failure?) { + if let error { + self = .failure(error) + } else { + self = .success(value) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `tryMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + func tryMap(_ transform: (Success) throws -> NewSuccess) -> Result { + switch self { + case let .success(value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case let .failure(error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `tryMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.tryMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same success. + func tryMapError(_ transform: (Failure) throws -> NewFailure) -> Result { + switch self { + case let .failure(error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case let .success(value): + return .success(value) + } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Extensions/StringEncoding+Alamofire.swift b/ChatBot/Pods/Alamofire/Source/Extensions/StringEncoding+Alamofire.swift new file mode 100644 index 00000000..8fa61333 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Extensions/StringEncoding+Alamofire.swift @@ -0,0 +1,55 @@ +// +// StringEncoding+Alamofire.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension String.Encoding { + /// Creates an encoding from the IANA charset name. + /// + /// - Notes: These mappings match those [provided by CoreFoundation](https://opensource.apple.com/source/CF/CF-476.18/CFStringUtilities.c.auto.html) + /// + /// - Parameter name: IANA charset name. + init?(ianaCharsetName name: String) { + switch name.lowercased() { + case "utf-8": + self = .utf8 + case "iso-8859-1": + self = .isoLatin1 + case "unicode-1-1", "iso-10646-ucs-2", "utf-16": + self = .utf16 + case "utf-16be": + self = .utf16BigEndian + case "utf-16le": + self = .utf16LittleEndian + case "utf-32": + self = .utf32 + case "utf-32be": + self = .utf32BigEndian + case "utf-32le": + self = .utf32LittleEndian + default: + return nil + } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Extensions/URLRequest+Alamofire.swift b/ChatBot/Pods/Alamofire/Source/Extensions/URLRequest+Alamofire.swift new file mode 100644 index 00000000..ab72fb53 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Extensions/URLRequest+Alamofire.swift @@ -0,0 +1,39 @@ +// +// URLRequest+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension URLRequest { + /// Returns the `httpMethod` as Alamofire's `HTTPMethod` type. + public var method: HTTPMethod? { + get { httpMethod.map(HTTPMethod.init) } + set { httpMethod = newValue?.rawValue } + } + + public func validate() throws { + if method == .get, let bodyData = httpBody { + throw AFError.urlRequestValidationFailed(reason: .bodyDataInGETRequest(bodyData)) + } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Extensions/URLSessionConfiguration+Alamofire.swift b/ChatBot/Pods/Alamofire/Source/Extensions/URLSessionConfiguration+Alamofire.swift new file mode 100644 index 00000000..292a8fe7 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Extensions/URLSessionConfiguration+Alamofire.swift @@ -0,0 +1,46 @@ +// +// URLSessionConfiguration+Alamofire.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension URLSessionConfiguration: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: URLSessionConfiguration { + /// Alamofire's default configuration. Same as `URLSessionConfiguration.default` but adds Alamofire default + /// `Accept-Language`, `Accept-Encoding`, and `User-Agent` headers. + public static var `default`: URLSessionConfiguration { + let configuration = URLSessionConfiguration.default + configuration.headers = .default + + return configuration + } + + /// `.ephemeral` configuration with Alamofire's default `Accept-Language`, `Accept-Encoding`, and `User-Agent` + /// headers. + public static var ephemeral: URLSessionConfiguration { + let configuration = URLSessionConfiguration.ephemeral + configuration.headers = .default + + return configuration + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/AlamofireExtended.swift b/ChatBot/Pods/Alamofire/Source/Features/AlamofireExtended.swift new file mode 100644 index 00000000..280c6de9 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/AlamofireExtended.swift @@ -0,0 +1,61 @@ +// +// AlamofireExtended.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +/// Type that acts as a generic extension point for all `AlamofireExtended` types. +public struct AlamofireExtension { + /// Stores the type or meta-type of any extended type. + public private(set) var type: ExtendedType + + /// Create an instance from the provided value. + /// + /// - Parameter type: Instance being extended. + public init(_ type: ExtendedType) { + self.type = type + } +} + +/// Protocol describing the `af` extension points for Alamofire extended types. +public protocol AlamofireExtended { + /// Type being extended. + associatedtype ExtendedType + + /// Static Alamofire extension point. + static var af: AlamofireExtension.Type { get set } + /// Instance Alamofire extension point. + var af: AlamofireExtension { get set } +} + +extension AlamofireExtended { + /// Static Alamofire extension point. + public static var af: AlamofireExtension.Type { + get { AlamofireExtension.self } + set {} + } + + /// Instance Alamofire extension point. + public var af: AlamofireExtension { + get { AlamofireExtension(self) } + set {} + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/AuthenticationInterceptor.swift b/ChatBot/Pods/Alamofire/Source/Features/AuthenticationInterceptor.swift new file mode 100644 index 00000000..7a33f10f --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/AuthenticationInterceptor.swift @@ -0,0 +1,402 @@ +// +// AuthenticationInterceptor.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Types adopting the `AuthenticationCredential` protocol can be used to authenticate `URLRequest`s. +/// +/// One common example of an `AuthenticationCredential` is an OAuth2 credential containing an access token used to +/// authenticate all requests on behalf of a user. The access token generally has an expiration window of 60 minutes +/// which will then require a refresh of the credential using the refresh token to generate a new access token. +public protocol AuthenticationCredential { + /// Whether the credential requires a refresh. This property should always return `true` when the credential is + /// expired. It is also wise to consider returning `true` when the credential will expire in several seconds or + /// minutes depending on the expiration window of the credential. + /// + /// For example, if the credential is valid for 60 minutes, then it would be wise to return `true` when the + /// credential is only valid for 5 minutes or less. That ensures the credential will not expire as it is passed + /// around backend services. + var requiresRefresh: Bool { get } +} + +// MARK: - + +/// Types adopting the `Authenticator` protocol can be used to authenticate `URLRequest`s with an +/// `AuthenticationCredential` as well as refresh the `AuthenticationCredential` when required. +public protocol Authenticator: AnyObject { + /// The type of credential associated with the `Authenticator` instance. + associatedtype Credential: AuthenticationCredential + + /// Applies the `Credential` to the `URLRequest`. + /// + /// In the case of OAuth2, the access token of the `Credential` would be added to the `URLRequest` as a Bearer + /// token to the `Authorization` header. + /// + /// - Parameters: + /// - credential: The `Credential`. + /// - urlRequest: The `URLRequest`. + func apply(_ credential: Credential, to urlRequest: inout URLRequest) + + /// Refreshes the `Credential` and executes the `completion` closure with the `Result` once complete. + /// + /// Refresh can be called in one of two ways. It can be called before the `Request` is actually executed due to + /// a `requiresRefresh` returning `true` during the adapt portion of the `Request` creation process. It can also + /// be triggered by a failed `Request` where the authentication server denied access due to an expired or + /// invalidated access token. + /// + /// In the case of OAuth2, this method would use the refresh token of the `Credential` to generate a new + /// `Credential` using the authentication service. Once complete, the `completion` closure should be called with + /// the new `Credential`, or the error that occurred. + /// + /// In general, if the refresh call fails with certain status codes from the authentication server (commonly a 401), + /// the refresh token in the `Credential` can no longer be used to generate a valid `Credential`. In these cases, + /// you will need to reauthenticate the user with their username / password. + /// + /// Please note, these are just general examples of common use cases. They are not meant to solve your specific + /// authentication server challenges. Please work with your authentication server team to ensure your + /// `Authenticator` logic matches their expectations. + /// + /// - Parameters: + /// - credential: The `Credential` to refresh. + /// - session: The `Session` requiring the refresh. + /// - completion: The closure to be executed once the refresh is complete. + func refresh(_ credential: Credential, for session: Session, completion: @escaping (Result) -> Void) + + /// Determines whether the `URLRequest` failed due to an authentication error based on the `HTTPURLResponse`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `false` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then you + /// will need to work with your authentication server team to understand how to identify when this occurs. + /// + /// In the case of OAuth2, where an authentication server can invalidate credentials, you will need to inspect the + /// `HTTPURLResponse` or possibly the `Error` for when this occurs. This is commonly handled by the authentication + /// server returning a 401 status code and some additional header to indicate an OAuth2 failure occurred. + /// + /// It is very important to understand how your authentication server works to be able to implement this correctly. + /// For example, if your authentication server returns a 401 when an OAuth2 error occurs, and your downstream + /// service also returns a 401 when you are not authorized to perform that operation, how do you know which layer + /// of the backend returned you a 401? You do not want to trigger a refresh unless you know your authentication + /// server is actually the layer rejecting the request. Again, work with your authentication server team to understand + /// how to identify an OAuth2 401 error vs. a downstream 401 error to avoid endless refresh loops. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - response: The `HTTPURLResponse`. + /// - error: The `Error`. + /// + /// - Returns: `true` if the `URLRequest` failed due to an authentication error, `false` otherwise. + func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: Error) -> Bool + + /// Determines whether the `URLRequest` is authenticated with the `Credential`. + /// + /// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `true` + /// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then + /// read on. + /// + /// When an authentication server can invalidate credentials, it means that you may have a non-expired credential + /// that appears to be valid, but will be rejected by the authentication server when used. Generally when this + /// happens, a number of requests are all sent when the application is foregrounded, and all of them will be + /// rejected by the authentication server in the order they are received. The first failed request will trigger a + /// refresh internally, which will update the credential, and then retry all the queued requests with the new + /// credential. However, it is possible that some of the original requests will not return from the authentication + /// server until the refresh has completed. This is where this method comes in. + /// + /// When the authentication server rejects a credential, we need to check to make sure we haven't refreshed the + /// credential while the request was in flight. If it has already refreshed, then we don't need to trigger an + /// additional refresh. If it hasn't refreshed, then we need to refresh. + /// + /// Now that it is understood how the result of this method is used in the refresh lifecyle, let's walk through how + /// to implement it. You should return `true` in this method if the `URLRequest` is authenticated in a way that + /// matches the values in the `Credential`. In the case of OAuth2, this would mean that the Bearer token in the + /// `Authorization` header of the `URLRequest` matches the access token in the `Credential`. If it matches, then we + /// know the `Credential` was used to authenticate the `URLRequest` and should return `true`. If the Bearer token + /// did not match the access token, then you should return `false`. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest`. + /// - credential: The `Credential`. + /// + /// - Returns: `true` if the `URLRequest` is authenticated with the `Credential`, `false` otherwise. + func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: Credential) -> Bool +} + +// MARK: - + +/// Represents various authentication failures that occur when using the `AuthenticationInterceptor`. All errors are +/// still vended from Alamofire as `AFError` types. The `AuthenticationError` instances will be embedded within +/// `AFError` `.requestAdaptationFailed` or `.requestRetryFailed` cases. +public enum AuthenticationError: Error { + /// The credential was missing so the request could not be authenticated. + case missingCredential + /// The credential was refreshed too many times within the `RefreshWindow`. + case excessiveRefresh +} + +// MARK: - + +/// The `AuthenticationInterceptor` class manages the queuing and threading complexity of authenticating requests. +/// It relies on an `Authenticator` type to handle the actual `URLRequest` authentication and `Credential` refresh. +public class AuthenticationInterceptor: RequestInterceptor where AuthenticatorType: Authenticator { + // MARK: Typealiases + + /// Type of credential used to authenticate requests. + public typealias Credential = AuthenticatorType.Credential + + // MARK: Helper Types + + /// Type that defines a time window used to identify excessive refresh calls. When enabled, prior to executing a + /// refresh, the `AuthenticationInterceptor` compares the timestamp history of previous refresh calls against the + /// `RefreshWindow`. If more refreshes have occurred within the refresh window than allowed, the refresh is + /// cancelled and an `AuthorizationError.excessiveRefresh` error is thrown. + public struct RefreshWindow { + /// `TimeInterval` defining the duration of the time window before the current time in which the number of + /// refresh attempts is compared against `maximumAttempts`. For example, if `interval` is 30 seconds, then the + /// `RefreshWindow` represents the past 30 seconds. If more attempts occurred in the past 30 seconds than + /// `maximumAttempts`, an `.excessiveRefresh` error will be thrown. + public let interval: TimeInterval + + /// Total refresh attempts allowed within `interval` before throwing an `.excessiveRefresh` error. + public let maximumAttempts: Int + + /// Creates a `RefreshWindow` instance from the specified `interval` and `maximumAttempts`. + /// + /// - Parameters: + /// - interval: `TimeInterval` defining the duration of the time window before the current time. + /// - maximumAttempts: The maximum attempts allowed within the `TimeInterval`. + public init(interval: TimeInterval = 30.0, maximumAttempts: Int = 5) { + self.interval = interval + self.maximumAttempts = maximumAttempts + } + } + + private struct AdaptOperation { + let urlRequest: URLRequest + let session: Session + let completion: (Result) -> Void + } + + private enum AdaptResult { + case adapt(Credential) + case doNotAdapt(AuthenticationError) + case adaptDeferred + } + + private struct MutableState { + var credential: Credential? + + var isRefreshing = false + var refreshTimestamps: [TimeInterval] = [] + var refreshWindow: RefreshWindow? + + var adaptOperations: [AdaptOperation] = [] + var requestsToRetry: [(RetryResult) -> Void] = [] + } + + // MARK: Properties + + /// The `Credential` used to authenticate requests. + public var credential: Credential? { + get { mutableState.credential } + set { mutableState.credential = newValue } + } + + let authenticator: AuthenticatorType + let queue = DispatchQueue(label: "org.alamofire.authentication.inspector") + + private let mutableState: Protected + + // MARK: Initialization + + /// Creates an `AuthenticationInterceptor` instance from the specified parameters. + /// + /// A `nil` `RefreshWindow` will result in the `AuthenticationInterceptor` not checking for excessive refresh calls. + /// It is recommended to always use a `RefreshWindow` to avoid endless refresh cycles. + /// + /// - Parameters: + /// - authenticator: The `Authenticator` type. + /// - credential: The `Credential` if it exists. `nil` by default. + /// - refreshWindow: The `RefreshWindow` used to identify excessive refresh calls. `RefreshWindow()` by default. + public init(authenticator: AuthenticatorType, + credential: Credential? = nil, + refreshWindow: RefreshWindow? = RefreshWindow()) { + self.authenticator = authenticator + mutableState = Protected(MutableState(credential: credential, refreshWindow: refreshWindow)) + } + + // MARK: Adapt + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + let adaptResult: AdaptResult = mutableState.write { mutableState in + // Queue the adapt operation if a refresh is already in place. + guard !mutableState.isRefreshing else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + return .adaptDeferred + } + + // Throw missing credential error is the credential is missing. + guard let credential = mutableState.credential else { + let error = AuthenticationError.missingCredential + return .doNotAdapt(error) + } + + // Queue the adapt operation and trigger refresh operation if credential requires refresh. + guard !credential.requiresRefresh else { + let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion) + mutableState.adaptOperations.append(operation) + refresh(credential, for: session, insideLock: &mutableState) + return .adaptDeferred + } + + return .adapt(credential) + } + + switch adaptResult { + case let .adapt(credential): + var authenticatedRequest = urlRequest + authenticator.apply(credential, to: &authenticatedRequest) + completion(.success(authenticatedRequest)) + + case let .doNotAdapt(adaptError): + completion(.failure(adaptError)) + + case .adaptDeferred: + // No-op: adapt operation captured during refresh. + break + } + } + + // MARK: Retry + + public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { + // Do not attempt retry if there was not an original request and response from the server. + guard let urlRequest = request.request, let response = request.response else { + completion(.doNotRetry) + return + } + + // Do not attempt retry unless the `Authenticator` verifies failure was due to authentication error (i.e. 401 status code). + guard authenticator.didRequest(urlRequest, with: response, failDueToAuthenticationError: error) else { + completion(.doNotRetry) + return + } + + // Do not attempt retry if there is no credential. + guard let credential else { + let error = AuthenticationError.missingCredential + completion(.doNotRetryWithError(error)) + return + } + + // Retry the request if the `Authenticator` verifies it was authenticated with a previous credential. + guard authenticator.isRequest(urlRequest, authenticatedWith: credential) else { + completion(.retry) + return + } + + mutableState.write { mutableState in + mutableState.requestsToRetry.append(completion) + + guard !mutableState.isRefreshing else { return } + + refresh(credential, for: session, insideLock: &mutableState) + } + } + + // MARK: Refresh + + private func refresh(_ credential: Credential, for session: Session, insideLock mutableState: inout MutableState) { + guard !isRefreshExcessive(insideLock: &mutableState) else { + let error = AuthenticationError.excessiveRefresh + handleRefreshFailure(error, insideLock: &mutableState) + return + } + + mutableState.refreshTimestamps.append(ProcessInfo.processInfo.systemUptime) + mutableState.isRefreshing = true + + // Dispatch to queue to hop out of the lock in case authenticator.refresh is implemented synchronously. + queue.async { + self.authenticator.refresh(credential, for: session) { result in + self.mutableState.write { mutableState in + switch result { + case let .success(credential): + self.handleRefreshSuccess(credential, insideLock: &mutableState) + case let .failure(error): + self.handleRefreshFailure(error, insideLock: &mutableState) + } + } + } + } + } + + private func isRefreshExcessive(insideLock mutableState: inout MutableState) -> Bool { + guard let refreshWindow = mutableState.refreshWindow else { return false } + + let refreshWindowMin = ProcessInfo.processInfo.systemUptime - refreshWindow.interval + + let refreshAttemptsWithinWindow = mutableState.refreshTimestamps.reduce(into: 0) { attempts, refreshTimestamp in + guard refreshWindowMin <= refreshTimestamp else { return } + attempts += 1 + } + + let isRefreshExcessive = refreshAttemptsWithinWindow >= refreshWindow.maximumAttempts + + return isRefreshExcessive + } + + private func handleRefreshSuccess(_ credential: Credential, insideLock mutableState: inout MutableState) { + mutableState.credential = credential + + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { self.adapt($0.urlRequest, for: $0.session, completion: $0.completion) } + requestsToRetry.forEach { $0(.retry) } + } + } + + private func handleRefreshFailure(_ error: Error, insideLock mutableState: inout MutableState) { + let adaptOperations = mutableState.adaptOperations + let requestsToRetry = mutableState.requestsToRetry + + mutableState.adaptOperations.removeAll() + mutableState.requestsToRetry.removeAll() + + mutableState.isRefreshing = false + + // Dispatch to queue to hop out of the mutable state lock + queue.async { + adaptOperations.forEach { $0.completion(.failure(error)) } + requestsToRetry.forEach { $0(.doNotRetryWithError(error)) } + } + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/CachedResponseHandler.swift b/ChatBot/Pods/Alamofire/Source/Features/CachedResponseHandler.swift new file mode 100644 index 00000000..1371b6e1 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/CachedResponseHandler.swift @@ -0,0 +1,107 @@ +// +// CachedResponseHandler.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles whether the data task should store the HTTP response in the cache. +public protocol CachedResponseHandler { + /// Determines whether the HTTP response should be stored in the cache. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The cached response provided by the server (this is the most common use case). + /// 2. A modified version of the cached response (you may want to modify it in some way before caching). + /// 3. A `nil` value to prevent the cached response from being stored in the cache. + /// + /// - Parameters: + /// - task: The data task whose request resulted in the cached response. + /// - response: The cached response to potentially store in the cache. + /// - completion: The closure to execute containing cached response, a modified response, or `nil`. + func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) +} + +// MARK: - + +/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached +/// response. +public struct ResponseCacher { + /// Defines the behavior of the `ResponseCacher` type. + public enum Behavior { + /// Stores the cached response in the cache. + case cache + /// Prevents the cached response from being stored in the cache. + case doNotCache + /// Modifies the cached response before storing it in the cache. + case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?) + } + + /// Returns a `ResponseCacher` with a `.cache` `Behavior`. + public static let cache = ResponseCacher(behavior: .cache) + /// Returns a `ResponseCacher` with a `.doNotCache` `Behavior`. + public static let doNotCache = ResponseCacher(behavior: .doNotCache) + + /// The `Behavior` of the `ResponseCacher`. + public let behavior: Behavior + + /// Creates a `ResponseCacher` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +extension ResponseCacher: CachedResponseHandler { + public func dataTask(_ task: URLSessionDataTask, + willCacheResponse response: CachedURLResponse, + completion: @escaping (CachedURLResponse?) -> Void) { + switch behavior { + case .cache: + completion(response) + case .doNotCache: + completion(nil) + case let .modify(closure): + let response = closure(task, response) + completion(response) + } + } +} + +extension CachedResponseHandler where Self == ResponseCacher { + /// Provides a `ResponseCacher` which caches the response, if allowed. Equivalent to `ResponseCacher.cache`. + public static var cache: ResponseCacher { .cache } + + /// Provides a `ResponseCacher` which does not cache the response. Equivalent to `ResponseCacher.doNotCache`. + public static var doNotCache: ResponseCacher { .doNotCache } + + /// Creates a `ResponseCacher` which modifies the proposed `CachedURLResponse` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the `CachedURLResponse`. + /// - Returns: The `ResponseCacher`. + public static func modify(using closure: @escaping ((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)) -> ResponseCacher { + ResponseCacher(behavior: .modify(closure)) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/Combine.swift b/ChatBot/Pods/Alamofire/Source/Features/Combine.swift new file mode 100644 index 00000000..79fce0de --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/Combine.swift @@ -0,0 +1,652 @@ +// +// Combine.swift +// +// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !((os(iOS) && (arch(i386) || arch(arm))) || os(Windows) || os(Linux) || os(Android)) + +import Combine +import Dispatch +import Foundation + +// MARK: - DataRequest / UploadRequest + +/// A Combine `Publisher` that publishes the `DataResponse` of the provided `DataRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataResponsePublisher: Publisher { + public typealias Output = DataResponse + public typealias Failure = Never + + private typealias Handler = (@escaping (_ response: DataResponse) -> Void) -> DataRequest + + private let request: DataRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DataResponse`. + public init(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`. + /// + /// - Parameters: + /// - request: `DataRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`. + public init(_ request: DataRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DataResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + private let downstream: Protected + private let request: DataRequest + private let responseHandler: Handler + + init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = Protected(downstream) + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream.read({ $0 }) else { return } + + self.downstream.write(nil) + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream.write(nil) + } + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DataResponsePublisher where Value == Data? { + /// Creates an instance which publishes a `DataResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DataRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DataRequest { + /// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize response `Data`. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher + where Serializer.SerializedObject == T { + DataResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by + /// default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// + /// - Returns: The `DataResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher { + DataResponsePublisher(self, queue: queue) + } +} + +// A Combine `Publisher` that publishes a sequence of `Stream` values received by the provided `DataStreamRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DataStreamPublisher: Publisher { + public typealias Output = DataStreamRequest.Stream + public typealias Failure = Never + + private typealias Handler = (@escaping DataStreamRequest.Handler) -> DataStreamRequest + + private let request: DataStreamRequest + private let streamHandler: Handler + + /// Creates an instance which will serialize responses using the provided `DataStreamSerializer`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `Stream` values will be published. `.main` by + /// default. + /// - serializer: `DataStreamSerializer` used to produce the published `Stream` values. + public init(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) } + } + + /// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + compactMap { stream in + switch stream.event { + case let .stream(result): + return result + // If the stream has completed with an error, send the error value downstream as a `.failure`. + case let .complete(completion): + return completion.error.map(Result.failure) + } + } + .eraseToAnyPublisher() + } + + /// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the + /// `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + result().setFailureType(to: AFError.self).flatMap(\.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + streamHandler: streamHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + private let downstream: Protected + private let request: DataStreamRequest + private let streamHandler: Handler + + init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.streamHandler = streamHandler + self.downstream = Protected(downstream) + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream.read({ $0 }) else { return } + + self.downstream.write(nil) + streamHandler { stream in + _ = downstream.receive(stream) + if case .complete = stream.event { + downstream.receive(completion: .finished) + } + }.resume() + } + + func cancel() { + request.cancel() + downstream.write(nil) + } + } +} + +extension DataStreamRequest { + /// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishStream(using serializer: Serializer, + on queue: DispatchQueue = .main) -> DataStreamPublisher { + DataStreamPublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data` + /// unserialized. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: PassthroughStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream + /// `Data` values into `String` values. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher { + publishStream(using: StringStreamSerializer(), on: queue) + } + + /// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided + /// parameters to serialize stream `Data` values into the provided type. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default. + /// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default. + /// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - Returns: The `DataStreamPublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + decoder: DataDecoder = JSONDecoder(), + preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher { + publishStream(using: DecodableStreamSerializer(decoder: decoder, + dataPreprocessor: preprocessor), + on: queue) + } +} + +/// A Combine `Publisher` that publishes the `DownloadResponse` of the provided `DownloadRequest`. +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +public struct DownloadResponsePublisher: Publisher { + public typealias Output = DownloadResponse + public typealias Failure = Never + + private typealias Handler = (@escaping (_ response: DownloadResponse) -> Void) -> DownloadRequest + + private let request: DownloadRequest + private let responseHandler: Handler + + /// Creates an instance which will serialize responses using the provided `ResponseSerializer`. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default. + /// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`. + public init(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value. + /// + /// - Parameters: + /// - request: `DownloadRequest` for which to publish the response. + /// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default. + /// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, + queue: DispatchQueue, + serializer: Serializer) + where Value == Serializer.SerializedObject { + self.request = request + responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) } + } + + /// Publishes only the `Result` of the `DownloadResponse` value. + /// + /// - Returns: The `AnyPublisher` publishing the `Result` value. + public func result() -> AnyPublisher, Never> { + map(\.result).eraseToAnyPublisher() + } + + /// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance. + /// + /// - Returns: The `AnyPublisher` publishing the stream. + public func value() -> AnyPublisher { + setFailureType(to: AFError.self).flatMap(\.result.publisher).eraseToAnyPublisher() + } + + public func receive(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input { + subscriber.receive(subscription: Inner(request: request, + responseHandler: responseHandler, + downstream: subscriber)) + } + + private final class Inner: Subscription + where Downstream.Input == Output { + typealias Failure = Downstream.Failure + + private let downstream: Protected + private let request: DownloadRequest + private let responseHandler: Handler + + init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) { + self.request = request + self.responseHandler = responseHandler + self.downstream = Protected(downstream) + } + + func request(_ demand: Subscribers.Demand) { + assert(demand > 0) + + guard let downstream = downstream.read({ $0 }) else { return } + + self.downstream.write(nil) + responseHandler { response in + _ = downstream.receive(response) + downstream.receive(completion: .finished) + }.resume() + } + + func cancel() { + request.cancel() + downstream.write(nil) + } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and + /// `DispatchQueue`. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk. + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher + where Serializer.SerializedObject == T { + DownloadResponsePublisher(self, queue: queue, serializer: serializer) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the + /// response. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher { + publishResponse(using: URLResponseSerializer(), on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishData(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the + /// response. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()` + /// by default. + /// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding + /// will be determined by the server response, falling back to the default HTTP character + /// set, `ISO-8859-1`. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of + /// status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishString(queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } + + @_disfavoredOverload + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + @available(*, deprecated, message: "Renamed publishDecodable(type:queue:preprocessor:decoder:emptyResponseCodes:emptyRequestMethods).") + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyResponseMethods), + on: queue) + } + + /// Creates a `DownloadResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize + /// the response. + /// + /// - Parameters: + /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. + /// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default. + /// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default. + /// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by + /// default. + /// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless + /// of status code. `[.head]` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishDecodable(type: T.Type = T.self, + queue: DispatchQueue = .main, + preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher { + publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + on: queue) + } +} + +@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) +extension DownloadResponsePublisher where Value == URL? { + /// Creates an instance which publishes a `DownloadResponse` value without serialization. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public init(_ request: DownloadRequest, queue: DispatchQueue) { + self.request = request + responseHandler = { request.response(queue: queue, completionHandler: $0) } + } +} + +extension DownloadRequest { + /// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing. + /// + /// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default. + /// + /// - Returns: The `DownloadResponsePublisher`. + @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) + public func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher { + DownloadResponsePublisher(self, queue: queue) + } +} + +#endif diff --git a/ChatBot/Pods/Alamofire/Source/Features/Concurrency.swift b/ChatBot/Pods/Alamofire/Source/Features/Concurrency.swift new file mode 100644 index 00000000..42eff7f2 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/Concurrency.swift @@ -0,0 +1,962 @@ +// +// Concurrency.swift +// +// Copyright (c) 2021 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(_Concurrency) + +import Foundation + +// MARK: - Request Event Streams + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension Request { + /// Creates a `StreamOf` for the instance's upload progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func uploadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + uploadProgress(queue: underlyingQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the instance's download progress. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func downloadProgress(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + downloadProgress(queue: underlyingQueue) { progress in + continuation.yield(progress) + } + } + } + + /// Creates a `StreamOf` for the `URLRequest`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlRequests(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLRequestCreation(on: underlyingQueue) { request in + continuation.yield(request) + } + } + } + + /// Creates a `StreamOf` for the `URLSessionTask`s produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func urlSessionTasks(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onURLSessionTaskCreation(on: underlyingQueue) { task in + continuation.yield(task) + } + } + } + + /// Creates a `StreamOf` for the cURL descriptions produced for the instance. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func cURLDescriptions(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + cURLDescription(on: underlyingQueue) { description in + continuation.yield(description) + } + } + } + + fileprivate func stream(of type: T.Type = T.self, + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded, + yielder: @escaping (StreamOf.Continuation) -> Void) -> StreamOf { + StreamOf(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + yielder(continuation) + // Must come after serializers run in order to catch retry progress. + onFinish { + continuation.finish() + } + } + } +} + +// MARK: - DataTask + +/// Value used to `await` a `DataResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataTask { + /// `DataResponse` produced by the `DataRequest` and its response handler. + public var response: DataResponse { + get async { + if shouldAutomaticallyCancel { + return await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + return await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let request: DataRequest + private let task: Task, Never> + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DataRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DataRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DataRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataRequest { + /// Creates a `StreamOf` for the instance's responses. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onHTTPResponse(on: underlyingQueue) { response in + continuation.yield(response) + } + } + } + + /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataRequest` produces an + /// `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a + /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as + /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, + /// so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse( + perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> ResponseDisposition + ) -> Self { + onHTTPResponse(on: underlyingQueue) { response, completionHandler in + Task { + let disposition = await handler(response) + completionHandler(disposition) + } + } + + return self + } + + /// Sets an async closure called whenever the `DataRequest` produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an + /// arbitrary thread, so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> Void) -> Self { + onHTTPResponse { response in + await handler(response) + return .allow + } + + return self + } + + /// Creates a `DataTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `Decodable` value. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DataTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataTask { + serializingResponse(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DataTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DataTask` to `await` serialization using the provided `DataResponseSerializerProtocol` instance. + /// + /// - Parameters: + /// - serializer: `DataResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DataTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DataTask`. + public func serializingResponse(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DataTask { + dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func dataTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @escaping (@escaping (DataResponse) -> Void) -> Void) + -> DataTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DataTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DownloadTask + +/// Value used to `await` a `DownloadResponse` and associated values. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DownloadTask { + /// `DownloadResponse` produced by the `DownloadRequest` and its response handler. + public var response: DownloadResponse { + get async { + if shouldAutomaticallyCancel { + return await withTaskCancellationHandler { + await task.value + } onCancel: { + cancel() + } + } else { + return await task.value + } + } + } + + /// `Result` of any response serialization performed for the `response`. + public var result: Result { + get async { await response.result } + } + + /// `Value` returned by the `response`. + public var value: Value { + get async throws { + try await result.get() + } + } + + private let task: Task, Never> + private let request: DownloadRequest + private let shouldAutomaticallyCancel: Bool + + fileprivate init(request: DownloadRequest, task: Task, Never>, shouldAutomaticallyCancel: Bool) { + self.request = request + self.task = task + self.shouldAutomaticallyCancel = shouldAutomaticallyCancel + } + + /// Cancel the underlying `DownloadRequest` and `Task`. + public func cancel() { + task.cancel() + } + + /// Resume the underlying `DownloadRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DownloadRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DownloadRequest { + /// Creates a `DownloadTask` to `await` a `Data` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion. + /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `Decodable` value. + /// + /// - Note: This serializer reads the entire response into memory before parsing. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer. + /// `PassthroughPreprocessor()` by default. + /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDecodable(_ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of the downloaded file's `URL` on disk. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownloadedFileURL(automaticallyCancelling shouldAutomaticallyCancel: Bool = true) -> DownloadTask { + serializingDownload(using: URLResponseSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization of a `String` value. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the + /// serializer. `PassthroughPreprocessor()` by default. + /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case + /// the encoding will be determined from the server response, falling back to the + /// default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default. + /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask { + serializingDownload(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods), + automaticallyCancelling: shouldAutomaticallyCancel) + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `ResponseSerializer` instance. + /// + /// - Parameters: + /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + /// Creates a `DownloadTask` to `await` serialization using the provided `DownloadResponseSerializerProtocol` + /// instance. + /// + /// - Parameters: + /// - serializer: `DownloadResponseSerializerProtocol` responsible for serializing the request, + /// response, and data. + /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the + /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async + /// properties. `true` by default. + /// + /// - Returns: The `DownloadTask`. + public func serializingDownload(using serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true) + -> DownloadTask { + downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in + response(queue: underlyingQueue, + responseSerializer: serializer, + completionHandler: $0) + } + } + + private func downloadTask(automaticallyCancelling shouldAutomaticallyCancel: Bool, + forResponse onResponse: @escaping (@escaping (DownloadResponse) -> Void) -> Void) + -> DownloadTask { + let task = Task { + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + onResponse { + continuation.resume(returning: $0) + } + } + } onCancel: { + self.cancel() + } + } + + return DownloadTask(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel) + } +} + +// MARK: - DataStreamTask + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DataStreamTask { + // Type of created streams. + public typealias Stream = StreamOf> + + private let request: DataStreamRequest + + fileprivate init(request: DataStreamRequest) { + self.request = request + } + + /// Creates a `Stream` of `Data` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `UTF-8` `String`s from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// - Returns: + public func streamingStrings(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream.BufferingPolicy = .unbounded) -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStreamString(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream) + } + } + + /// Creates a `Stream` of `Decodable` values from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - type: `Decodable` type to be serialized from stream payloads. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingDecodables(_ type: T.Type = T.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream where T: Decodable { + streamingResponses(serializedUsing: DecodableStreamSerializer(), + automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy) + } + + /// Creates a `Stream` of values using the provided `DataStreamSerializer` from the underlying `DataStreamRequest`. + /// + /// - Parameters: + /// - serializer: `DataStreamSerializer` to use to serialize incoming `Data`. + /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled + /// which observation of the stream stops. `true` by default. + /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `Stream`. + public func streamingResponses(serializedUsing serializer: Serializer, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded) + -> Stream { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in + request.responseStream(using: serializer, + on: .streamCompletionQueue(forRequestID: request.id), + stream: onStream) + } + } + + private func createStream(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: Stream.BufferingPolicy = .unbounded, + forResponse onResponse: @escaping (@escaping (DataStreamRequest.Stream) -> Void) -> Void) + -> Stream { + StreamOf(bufferingPolicy: bufferingPolicy) { + guard shouldAutomaticallyCancel, + request.isInitialized || request.isResumed || request.isSuspended else { return } + + cancel() + } builder: { continuation in + onResponse { stream in + continuation.yield(stream) + if case .complete = stream.event { + continuation.finish() + } + } + } + } + + /// Cancel the underlying `DataStreamRequest`. + public func cancel() { + request.cancel() + } + + /// Resume the underlying `DataStreamRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `DataStreamRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension DataStreamRequest { + /// Creates a `StreamOf` for the instance's responses. + /// + /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default. + /// + /// - Returns: The `StreamOf`. + public func httpResponses(bufferingPolicy: StreamOf.BufferingPolicy = .unbounded) -> StreamOf { + stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in + onHTTPResponse(on: underlyingQueue) { response in + continuation.yield(response) + } + } + } + + /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataStreamRequest` + /// produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a + /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as + /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread, + /// so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @_disfavoredOverload + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> ResponseDisposition) -> Self { + onHTTPResponse(on: underlyingQueue) { response, completionHandler in + Task { + let disposition = await handler(response) + completionHandler(disposition) + } + } + + return self + } + + /// Sets an async closure called whenever the `DataStreamRequest` produces an `HTTPURLResponse`. + /// + /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries). + /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams, + /// where responses after the first will contain the part headers. + /// + /// - Parameters: + /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an + /// arbitrary thread, so any synchronous calls in it will execute in that context. + /// + /// - Returns: The instance. + @discardableResult + public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> Void) -> Self { + onHTTPResponse { response in + await handler(response) + return .allow + } + + return self + } + + /// Creates a `DataStreamTask` used to `await` streams of serialized values. + /// + /// - Returns: The `DataStreamTask`. + public func streamTask() -> DataStreamTask { + DataStreamTask(request: self) + } +} + +#if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask. +// - MARK: WebSocketTask + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +@_spi(WebSocket) public struct WebSocketTask { + private let request: WebSocketRequest + + fileprivate init(request: WebSocketRequest) { + self.request = request + } + + public typealias EventStreamOf = StreamOf> + + public func streamingMessageEvents( + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: EventStreamOf.BufferingPolicy = .unbounded + ) -> EventStreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0 }) { onEvent in + request.streamMessageEvents(on: .streamCompletionQueue(forRequestID: request.id), handler: onEvent) + } + } + + public func streamingMessages( + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded + ) -> StreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0.message }) { onEvent in + request.streamMessageEvents(on: .streamCompletionQueue(forRequestID: request.id), handler: onEvent) + } + } + + public func streamingDecodableEvents( + _ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + using decoder: DataDecoder = JSONDecoder(), + bufferingPolicy: EventStreamOf.BufferingPolicy = .unbounded + ) -> EventStreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0 }) { onEvent in + request.streamDecodableEvents(Value.self, + on: .streamCompletionQueue(forRequestID: request.id), + using: decoder, + handler: onEvent) + } + } + + public func streamingDecodable( + _ type: Value.Type = Value.self, + automaticallyCancelling shouldAutomaticallyCancel: Bool = true, + using decoder: DataDecoder = JSONDecoder(), + bufferingPolicy: StreamOf.BufferingPolicy = .unbounded + ) -> StreamOf { + createStream(automaticallyCancelling: shouldAutomaticallyCancel, + bufferingPolicy: bufferingPolicy, + transform: { $0.message }) { onEvent in + request.streamDecodableEvents(Value.self, + on: .streamCompletionQueue(forRequestID: request.id), + using: decoder, + handler: onEvent) + } + } + + private func createStream( + automaticallyCancelling shouldAutomaticallyCancel: Bool, + bufferingPolicy: StreamOf.BufferingPolicy, + transform: @escaping (WebSocketRequest.Event) -> Value?, + forResponse onResponse: @escaping (@escaping (WebSocketRequest.Event) -> Void) -> Void + ) -> StreamOf { + StreamOf(bufferingPolicy: bufferingPolicy) { + guard shouldAutomaticallyCancel, + request.isInitialized || request.isResumed || request.isSuspended else { return } + + cancel() + } builder: { continuation in + onResponse { event in + if let value = transform(event) { + continuation.yield(value) + } + + if case .completed = event.kind { + continuation.finish() + } + } + } + } + + /// Send a `URLSessionWebSocketTask.Message`. + /// + /// - Parameter message: The `Message`. + /// + public func send(_ message: URLSessionWebSocketTask.Message) async throws { + try await withCheckedThrowingContinuation { continuation in + request.send(message, queue: .streamCompletionQueue(forRequestID: request.id)) { result in + continuation.resume(with: result) + } + } + } + + /// Close the underlying `WebSocketRequest`. + public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) { + request.close(sending: closeCode, reason: reason) + } + + /// Cancel the underlying `WebSocketRequest`. + /// + /// Cancellation will produce an `AFError.explicitlyCancelled` instance. + public func cancel() { + request.cancel() + } + + /// Resume the underlying `WebSocketRequest`. + public func resume() { + request.resume() + } + + /// Suspend the underlying `WebSocketRequest`. + public func suspend() { + request.suspend() + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension WebSocketRequest { + public func webSocketTask() -> WebSocketTask { + WebSocketTask(request: self) + } +} +#endif + +extension DispatchQueue { + fileprivate static let singleEventQueue = DispatchQueue(label: "org.alamofire.concurrencySingleEventQueue", + attributes: .concurrent) + + fileprivate static func streamCompletionQueue(forRequestID id: UUID) -> DispatchQueue { + DispatchQueue(label: "org.alamofire.concurrencyStreamCompletionQueue-\(id)", target: .singleEventQueue) + } +} + +/// An asynchronous sequence generated from an underlying `AsyncStream`. Only produced by Alamofire. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct StreamOf: AsyncSequence { + public typealias AsyncIterator = Iterator + public typealias BufferingPolicy = AsyncStream.Continuation.BufferingPolicy + fileprivate typealias Continuation = AsyncStream.Continuation + + private let bufferingPolicy: BufferingPolicy + private let onTermination: (() -> Void)? + private let builder: (Continuation) -> Void + + fileprivate init(bufferingPolicy: BufferingPolicy = .unbounded, + onTermination: (() -> Void)? = nil, + builder: @escaping (Continuation) -> Void) { + self.bufferingPolicy = bufferingPolicy + self.onTermination = onTermination + self.builder = builder + } + + public func makeAsyncIterator() -> Iterator { + var continuation: AsyncStream.Continuation? + let stream = AsyncStream(bufferingPolicy: bufferingPolicy) { innerContinuation in + continuation = innerContinuation + builder(innerContinuation) + } + + return Iterator(iterator: stream.makeAsyncIterator()) { + continuation?.finish() + onTermination?() + } + } + + public struct Iterator: AsyncIteratorProtocol { + private final class Token { + private let onDeinit: () -> Void + + init(onDeinit: @escaping () -> Void) { + self.onDeinit = onDeinit + } + + deinit { + onDeinit() + } + } + + private var iterator: AsyncStream.AsyncIterator + private let token: Token + + init(iterator: AsyncStream.AsyncIterator, onCancellation: @escaping () -> Void) { + self.iterator = iterator + token = Token(onDeinit: onCancellation) + } + + public mutating func next() async -> Element? { + await iterator.next() + } + } +} + +#endif diff --git a/ChatBot/Pods/Alamofire/Source/Features/EventMonitor.swift b/ChatBot/Pods/Alamofire/Source/Features/EventMonitor.swift new file mode 100644 index 00000000..c997e713 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/EventMonitor.swift @@ -0,0 +1,907 @@ +// +// EventMonitor.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various +/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses. +public protocol EventMonitor { + /// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default. + var queue: DispatchQueue { get } + + // MARK: - URLSession Events + + // MARK: URLSessionDelegate Events + + /// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method. + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) + + // MARK: URLSessionTaskDelegate Events + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method. + func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method. + func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method. + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) + + /// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method. + func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) + + // MARK: URLSessionDataDelegate Events + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) + + /// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method. + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) + + // MARK: URLSessionDownloadDelegate Events + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method. + func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + + /// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method. + func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) + + // MARK: - Request Events + + /// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the + /// `URLRequest` will be adapted before being issued. + func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) + + /// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails. + func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) + + /// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`. + func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) + + /// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`. + func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) + + /// Event called when a final `URLRequest` is created for a `Request`. + func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) + + /// Event called when a `URLSessionTask` subclass instance is created for a `Request`. + func request(_ request: Request, didCreateTask task: URLSessionTask) + + /// Event called when a `Request` receives a `URLSessionTaskMetrics` value. + func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) + + /// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails. + func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) + + /// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event + /// multiple times if it is retried. + func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) + + /// Event called when a `Request` is about to be retried. + func requestIsRetrying(_ request: Request) + + /// Event called when a `Request` finishes and response serializers are being called. + func requestDidFinish(_ request: Request) + + /// Event called when a `Request` receives a `resume` call. + func requestDidResume(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is resumed. + func request(_ request: Request, didResumeTask task: URLSessionTask) + + /// Event called when a `Request` receives a `suspend` call. + func requestDidSuspend(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is suspended. + func request(_ request: Request, didSuspendTask task: URLSessionTask) + + /// Event called when a `Request` receives a `cancel` call. + func requestDidCancel(_ request: Request) + + /// Event called when a `Request`'s associated `URLSessionTask` is cancelled. + func request(_ request: Request, didCancelTask task: URLSessionTask) + + // MARK: DataRequest Events + + /// Event called when a `DataRequest` calls a `Validation`. + func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) + + /// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + /// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`. + func request(_ request: DataRequest, didParseResponse response: DataResponse) + + // MARK: DataStreamRequest Events + + /// Event called when a `DataStreamRequest` calls a `Validation` closure. + /// + /// - Parameters: + /// - request: `DataStreamRequest` which is calling the `Validation`. + /// - urlRequest: `URLRequest` of the request being validated. + /// - response: `HTTPURLResponse` of the request being validated. + /// - result: Produced `ValidationResult`. + func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) + + /// Event called when a `DataStreamSerializer` produces a value from streamed `Data`. + /// + /// - Parameters: + /// - request: `DataStreamRequest` for which the value was serialized. + /// - result: `Result` of the serialization attempt. + func request(_ request: DataStreamRequest, didParseStream result: Result) + + // MARK: UploadRequest Events + + /// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents. + func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) + + /// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error. + func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) + + /// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if + /// the `InputStream` does not wrap a `Data` value or file `URL`. + func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) + + // MARK: DownloadRequest Events + + /// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved. + func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) + + /// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the + /// downloaded file will be moved to. + func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) + + /// Event called when a `DownloadRequest` calls a `Validation`. + func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) + + /// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`. + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) + + /// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse` + func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) +} + +extension EventMonitor { + /// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default. + public var queue: DispatchQueue { .main } + + // MARK: Default Implementations + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) {} + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) {} + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didFinishCollecting metrics: URLSessionTaskMetrics) {} + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {} + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) {} + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {} + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) {} + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) {} + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {} + public func request(_ request: Request, + didAdaptInitialRequest initialRequest: URLRequest, + to adaptedRequest: URLRequest) {} + public func request(_ request: Request, + didFailToAdaptURLRequest initialRequest: URLRequest, + withError error: AFError) {} + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {} + public func request(_ request: Request, didCreateTask task: URLSessionTask) {} + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {} + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {} + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {} + public func requestIsRetrying(_ request: Request) {} + public func requestDidFinish(_ request: Request) {} + public func requestDidResume(_ request: Request) {} + public func request(_ request: Request, didResumeTask task: URLSessionTask) {} + public func requestDidSuspend(_ request: Request) {} + public func request(_ request: Request, didSuspendTask task: URLSessionTask) {} + public func requestDidCancel(_ request: Request) {} + public func request(_ request: Request, didCancelTask task: URLSessionTask) {} + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataRequest, didParseResponse response: DataResponse) {} + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) {} + public func request(_ request: DataStreamRequest, didParseStream result: Result) {} + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {} + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {} + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {} + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {} + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {} + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {} +} + +/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues. +public final class CompositeEventMonitor: EventMonitor { + public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor") + + let monitors: [EventMonitor] + + init(monitors: [EventMonitor]) { + self.monitors = monitors + } + + func performEvent(_ event: @escaping (EventMonitor) -> Void) { + queue.async { + for monitor in self.monitors { + monitor.queue.async { event(monitor) } + } + } + } + + public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge) { + performEvent { $0.urlSession(session, task: task, didReceive: challenge) } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + performEvent { + $0.urlSession(session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend) + } + } + + public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + performEvent { + $0.urlSession(session, taskNeedsNewBodyStream: task) + } + } + + public func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + performEvent { + $0.urlSession(session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request) + } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) } + } + + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) } + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: response) } + } + + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) } + } + + public func urlSession(_ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse) { + performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + performEvent { + $0.urlSession(session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite) + } + } + + public func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) { + performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } + } + + public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) } + } + + public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) } + } + + public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) } + } + + public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) } + } + + public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + performEvent { $0.request(request, didCreateURLRequest: urlRequest) } + } + + public func request(_ request: Request, didCreateTask task: URLSessionTask) { + performEvent { $0.request(request, didCreateTask: task) } + } + + public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + performEvent { $0.request(request, didGatherMetrics: metrics) } + } + + public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + performEvent { $0.request(request, didFailTask: task, earlyWithError: error) } + } + + public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + performEvent { $0.request(request, didCompleteTask: task, with: error) } + } + + public func requestIsRetrying(_ request: Request) { + performEvent { $0.requestIsRetrying(request) } + } + + public func requestDidFinish(_ request: Request) { + performEvent { $0.requestDidFinish(request) } + } + + public func requestDidResume(_ request: Request) { + performEvent { $0.requestDidResume(request) } + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + performEvent { $0.request(request, didResumeTask: task) } + } + + public func requestDidSuspend(_ request: Request) { + performEvent { $0.requestDidSuspend(request) } + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + performEvent { $0.request(request, didSuspendTask: task) } + } + + public func requestDidCancel(_ request: Request) { + performEvent { $0.requestDidCancel(request) } + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + performEvent { $0.request(request, didCancelTask: task) } + } + + public func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + data: data, + withResult: result) + } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataRequest, didParseResponse response: DataResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DataStreamRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + withResult: result) + } + } + + public func request(_ request: DataStreamRequest, didParseStream result: Result) { + performEvent { $0.request(request, didParseStream: result) } + } + + public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + performEvent { $0.request(request, didCreateUploadable: uploadable) } + } + + public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + performEvent { $0.request(request, didFailToCreateUploadableWithError: error) } + } + + public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + performEvent { $0.request(request, didProvideInputStream: stream) } + } + + public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) } + } + + public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + performEvent { $0.request(request, didCreateDestinationURL: url) } + } + + public func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + performEvent { $0.request(request, + didValidateRequest: urlRequest, + response: response, + fileURL: fileURL, + withResult: result) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } + + public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + performEvent { $0.request(request, didParseResponse: response) } + } +} + +/// `EventMonitor` that allows optional closures to be set to receive events. +open class ClosureEventMonitor: EventMonitor { + /// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)? + + /// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:task:needNewBodyStream:)` event. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)? + + /// Closure called on the `urlSession(_:task:didFinishCollecting:)` event. + open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `urlSession(_:task:didCompleteWithError:)` event. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + /// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event. + open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:didReceive:completionHandler:)` event. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> Void)? + + /// Closure that receives the `urlSession(_:dataTask:didReceive:)` event. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` + /// event. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: - Request Events + + /// Closure called on the `request(_:didCreateInitialURLRequest:)` event. + open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event. + open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)? + + /// Closure called on the `request(_:didAdaptInitialRequest:to:)` event. + open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)? + + /// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event. + open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didCreateURLRequest:)` event. + open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)? + + /// Closure called on the `request(_:didCreateTask:)` event. + open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didGatherMetrics:)` event. + open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)? + + /// Closure called on the `request(_:didFailTask:earlyWithError:)` event. + open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)? + + /// Closure called on the `request(_:didCompleteTask:with:)` event. + open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)? + + /// Closure called on the `requestIsRetrying(_:)` event. + open var requestIsRetrying: ((Request) -> Void)? + + /// Closure called on the `requestDidFinish(_:)` event. + open var requestDidFinish: ((Request) -> Void)? + + /// Closure called on the `requestDidResume(_:)` event. + open var requestDidResume: ((Request) -> Void)? + + /// Closure called on the `request(_:didResumeTask:)` event. + open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidSuspend(_:)` event. + open var requestDidSuspend: ((Request) -> Void)? + + /// Closure called on the `request(_:didSuspendTask:)` event. + open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `requestDidCancel(_:)` event. + open var requestDidCancel: ((Request) -> Void)? + + /// Closure called on the `request(_:didCancelTask:)` event. + open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event. + open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:withResult:)` event. + open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didCreateUploadable:)` event. + open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)? + + /// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event. + open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)? + + /// Closure called on the `request(_:didProvideInputStream:)` event. + open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)? + + /// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event. + open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)? + + /// Closure called on the `request(_:didCreateDestinationURL:)` event. + open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)? + + /// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event. + open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)? + + /// Closure called on the `request(_:didParseResponse:)` event. + open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)? + + public let queue: DispatchQueue + + /// Creates an instance using the provided queue. + /// + /// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default. + public init(queue: DispatchQueue = .main) { + self.queue = queue + } + + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) { + taskDidReceiveChallenge?(session, task, challenge) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) { + taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + + open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) { + taskNeedNewBodyStream?(session, task) + } + + open func urlSession(_ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest) { + taskWillPerformHTTPRedirection?(session, task, response, request) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + taskDidFinishCollectingMetrics?(session, task, metrics) + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + taskDidComplete?(session, task, error) + } + + @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) + open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { + taskIsWaitingForConnectivity?(session, task) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse) { + dataTaskDidReceiveResponse?(session, dataTask, response) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + dataTaskDidReceiveData?(session, dataTask, data) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) { + dataTaskWillCacheResponse?(session, dataTask, proposedResponse) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) { + downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes) + } + + open func urlSession(_ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) { + downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + + open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { + downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location) + } + + // MARK: Request Events + + open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) { + requestDidCreateInitialURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) { + requestDidFailToCreateURLRequestWithError?(request, error) + } + + open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) { + requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest) + } + + open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) { + requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error) + } + + open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) { + requestDidCreateURLRequest?(request, urlRequest) + } + + open func request(_ request: Request, didCreateTask task: URLSessionTask) { + requestDidCreateTask?(request, task) + } + + open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) { + requestDidGatherMetrics?(request, metrics) + } + + open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) { + requestDidFailTaskEarlyWithError?(request, task, error) + } + + open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) { + requestDidCompleteTaskWithError?(request, task, error) + } + + open func requestIsRetrying(_ request: Request) { + requestIsRetrying?(request) + } + + open func requestDidFinish(_ request: Request) { + requestDidFinish?(request) + } + + open func requestDidResume(_ request: Request) { + requestDidResume?(request) + } + + public func request(_ request: Request, didResumeTask task: URLSessionTask) { + requestDidResumeTask?(request, task) + } + + open func requestDidSuspend(_ request: Request) { + requestDidSuspend?(request) + } + + public func request(_ request: Request, didSuspendTask task: URLSessionTask) { + requestDidSuspendTask?(request, task) + } + + open func requestDidCancel(_ request: Request) { + requestDidCancel?(request) + } + + public func request(_ request: Request, didCancelTask task: URLSessionTask) { + requestDidCancelTask?(request, task) + } + + open func request(_ request: DataRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + data: Data?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result) + } + + open func request(_ request: DataRequest, didParseResponse response: DataResponse) { + requestDidParseResponse?(request, response) + } + + public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result) + } + + open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) { + requestDidCreateUploadable?(request, uploadable) + } + + open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) { + requestDidFailToCreateUploadableWithError?(request, error) + } + + open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) { + requestDidProvideInputStream?(request, stream) + } + + open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) { + requestDidFinishDownloadingUsingTaskWithResult?(request, task, result) + } + + open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) { + requestDidCreateDestinationURL?(request, url) + } + + open func request(_ request: DownloadRequest, + didValidateRequest urlRequest: URLRequest?, + response: HTTPURLResponse, + fileURL: URL?, + withResult result: Request.ValidationResult) { + requestDidValidateRequestResponseFileURLWithResult?(request, + urlRequest, + response, + fileURL, + result) + } + + open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) { + requestDidParseDownloadResponse?(request, response) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/MultipartFormData.swift b/ChatBot/Pods/Alamofire/Source/Features/MultipartFormData.swift new file mode 100644 index 00000000..9c908b2f --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/MultipartFormData.swift @@ -0,0 +1,601 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if canImport(MobileCoreServices) +import MobileCoreServices +#elseif canImport(CoreServices) +import CoreServices +#endif + +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { + // MARK: - Helper Types + + enum EncodingCharacters { + static let crlf = "\r\n" + } + + enum BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + let first = UInt32.random(in: UInt32.min...UInt32.max) + let second = UInt32.random(in: UInt32.min...UInt32.max) + + return String(format: "alamofire.boundary.%08x%08x", first, second) + } + + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + let boundaryText: String + + switch boundaryType { + case .initial: + boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" + } + + return Data(boundaryText.utf8) + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// Default memory threshold used when encoding `MultipartFormData`, in bytes. + public static let encodingMemoryThreshold: UInt64 = 10_000_000 + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + let fileManager: FileManager + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates an instance. + /// + /// - Parameters: + /// - fileManager: `FileManager` to use for file operations, if needed. + /// - boundary: Boundary `String` used to separate body parts. + public init(fileManager: FileManager = .default, boundary: String? = nil) { + self.fileManager = fileManager + self.boundary = boundary ?? BoundaryGenerator.randomBoundary() + bodyParts = [] + + // + // The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + // information, please refer to the following article: + // - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + // + streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - data: `Data` to encoding into the instance. + /// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - Parameters: + /// - fileURL: `URL` of the file whose content will be encoded into the instance. + /// - name: Name to associate with the file content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + #if !(os(Linux) || os(Windows) || os(Android)) + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + #endif + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append(_ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the stream, length, and headers and appends it to the instance. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - Parameters: + /// - stream: `InputStream` to encode into the instance. + /// - length: Length, in bytes, of the stream. + /// - headers: `HTTPHeaders` for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all appended body parts into a single `Data` value. + /// + /// - Note: This method will load all the appended body parts into memory all at the same time. This method should + /// only be used when the encoded data will have a small memory footprint. For large data cases, please use + /// the `writeEncodedData(to:))` method. + /// + /// - Returns: The encoded `Data`, if encoding is successful. + /// - Throws: An `AFError` if encoding encounters an error. + public func encode() throws -> Data { + if let bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes all appended body parts to the given file `URL`. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - Parameter fileURL: File `URL` to which to write the form data. + /// - Throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError { + throw bodyPartError + } + + if fileManager.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" } + .joined() + + EncodingCharacters.crlf + + return Data(headerText.utf8) + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + guard UInt64(encoded.count) == bodyPart.bodyContentLength else { + let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength, + bytesRead: UInt64(encoded.count)) + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + var bytesLeftToRead = bodyPart.bodyContentLength + while inputStream.hasBytesAvailable && bytesLeftToRead > 0 { + let bufferSize = min(streamBufferSize, Int(bytesLeftToRead)) + var buffer = [UInt8](repeating: 0, count: bufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: bufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. HTTPHeaders { + var disposition = "form-data; name=\"\(name)\"" + if let fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers: HTTPHeaders = [.contentDisposition(disposition)] + if let mimeType { headers.add(.contentType(mimeType)) } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} + +#if canImport(UniformTypeIdentifiers) +import UniformTypeIdentifiers + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + #if swift(>=5.9) + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { + return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" + } else { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + + return "application/octet-stream" + } + #else + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { + return UTType(filenameExtension: pathExtension)?.preferredMIMEType ?? "application/octet-stream" + } else { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + + return "application/octet-stream" + } + #endif + } +} + +#else + +extension MultipartFormData { + // MARK: - Private - Mime Type + + private func mimeType(forPathExtension pathExtension: String) -> String { + #if canImport(CoreServices) || canImport(MobileCoreServices) + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { + return contentType as String + } + #endif + + return "application/octet-stream" + } +} + +#endif diff --git a/ChatBot/Pods/Alamofire/Source/Features/MultipartUpload.swift b/ChatBot/Pods/Alamofire/Source/Features/MultipartUpload.swift new file mode 100644 index 00000000..ae905bda --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/MultipartUpload.swift @@ -0,0 +1,89 @@ +// +// MultipartUpload.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Internal type which encapsulates a `MultipartFormData` upload. +final class MultipartUpload { + lazy var result = Result { try build() } + + private let multipartFormData: Protected + + let encodingMemoryThreshold: UInt64 + let request: URLRequestConvertible + let fileManager: FileManager + + init(encodingMemoryThreshold: UInt64, + request: URLRequestConvertible, + multipartFormData: MultipartFormData) { + self.encodingMemoryThreshold = encodingMemoryThreshold + self.request = request + fileManager = multipartFormData.fileManager + self.multipartFormData = Protected(multipartFormData) + } + + func build() throws -> UploadRequest.Uploadable { + let uploadable: UploadRequest.Uploadable + if multipartFormData.contentLength < encodingMemoryThreshold { + let data = try multipartFormData.read { try $0.encode() } + + uploadable = .data(data) + } else { + let tempDirectoryURL = fileManager.temporaryDirectory + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + + do { + try multipartFormData.read { try $0.writeEncodedData(to: fileURL) } + } catch { + // Cleanup after attempted write if it fails. + try? fileManager.removeItem(at: fileURL) + throw error + } + + uploadable = .file(fileURL, shouldRemove: true) + } + + return uploadable + } +} + +extension MultipartUpload: UploadConvertible { + func asURLRequest() throws -> URLRequest { + var urlRequest = try request.asURLRequest() + + multipartFormData.read { multipartFormData in + urlRequest.headers.add(.contentType(multipartFormData.contentType)) + } + + return urlRequest + } + + func createUploadable() throws -> UploadRequest.Uploadable { + try result.get() + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/NetworkReachabilityManager.swift b/ChatBot/Pods/Alamofire/Source/Features/NetworkReachabilityManager.swift new file mode 100644 index 00000000..6150d0d8 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/NetworkReachabilityManager.swift @@ -0,0 +1,292 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(SystemConfiguration) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and +/// WiFi network interfaces. +/// +/// Reachability can be used to determine background information about why a network operation failed, or to retry +/// network requests when a connection is established. It should not be used to prevent a user from initiating a network +/// request, as it's possible that an initial request may be required to establish reachability. +open class NetworkReachabilityManager { + /// Defines the various states of network reachability. + public enum NetworkReachabilityStatus { + /// It is unknown whether the network is reachable. + case unknown + /// The network is not reachable. + case notReachable + /// The network is reachable on the associated `ConnectionType`. + case reachable(ConnectionType) + + init(_ flags: SCNetworkReachabilityFlags) { + guard flags.isActuallyReachable else { self = .notReachable; return } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + if flags.isCellular { networkStatus = .reachable(.cellular) } + + self = networkStatus + } + + /// Defines the various connection types detected by reachability flags. + public enum ConnectionType { + /// The connection type is either over Ethernet or WiFi. + case ethernetOrWiFi + /// The connection type is a cellular connection. + case cellular + } + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`. + public static let `default` = NetworkReachabilityManager() + + // MARK: - Properties + + /// Whether the network is currently reachable. + open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the cellular interface. + /// + /// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended. + /// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued. + /// + open var isReachableOnCellular: Bool { status == .reachable(.cellular) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) } + + /// `DispatchQueue` on which reachability will update. + public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue") + + /// Flags of the current reachability type, if any. + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + return SCNetworkReachabilityGetFlags(reachability, &flags) ? flags : nil + } + + /// The current network reachability status. + open var status: NetworkReachabilityStatus { + flags.map(NetworkReachabilityStatus.init) ?? .unknown + } + + /// Mutable state storage. + struct MutableState { + /// A closure executed when the network reachability status changes. + var listener: Listener? + /// `DispatchQueue` on which listeners will be called. + var listenerQueue: DispatchQueue? + /// Previously calculated status. + var previousStatus: NetworkReachabilityStatus? + } + + /// `SCNetworkReachability` instance providing notifications. + private let reachability: SCNetworkReachability + + /// Protected storage for mutable state. + private let mutableState = Protected(MutableState()) + + // MARK: - Initialization + + /// Creates an instance with the specified host. + /// + /// - Note: The `host` value must *not* contain a scheme, just the hostname. + /// + /// - Parameters: + /// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`). + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + + self.init(reachability: reachability) + } + + /// Creates an instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + public convenience init?() { + var zero = sockaddr() + zero.sa_len = UInt8(MemoryLayout.size) + zero.sa_family = sa_family_t(AF_INET) + + guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - Note: Stops and removes any existing listener. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default. + /// - listener: `Listener` closure called when reachability changes. + /// + /// - Returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + open func startListening(onQueue queue: DispatchQueue = .main, + onUpdatePerforming listener: @escaping Listener) -> Bool { + stopListening() + + mutableState.write { state in + state.listenerQueue = queue + state.listener = listener + } + + let weakManager = WeakManager(manager: self) + + var context = SCNetworkReachabilityContext( + version: 0, + info: Unmanaged.passUnretained(weakManager).toOpaque(), + retain: { info in + let unmanaged = Unmanaged.fromOpaque(info) + _ = unmanaged.retain() + + return UnsafeRawPointer(unmanaged.toOpaque()) + }, + release: { info in + let unmanaged = Unmanaged.fromOpaque(info) + unmanaged.release() + }, + copyDescription: { info in + let unmanaged = Unmanaged.fromOpaque(info) + let weakManager = unmanaged.takeUnretainedValue() + let description = weakManager.manager?.flags?.readableDescription ?? "nil" + + return Unmanaged.passRetained(description as CFString) + } + ) + let callback: SCNetworkReachabilityCallBack = { _, flags, info in + guard let info else { return } + + let weakManager = Unmanaged.fromOpaque(info).takeUnretainedValue() + weakManager.manager?.notifyListener(flags) + } + + let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue) + let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context) + + // Manually call listener to give initial state, since the framework may not. + if let currentFlags = flags { + reachabilityQueue.async { + self.notifyListener(currentFlags) + } + } + + return callbackAdded && queueAdded + } + + /// Stops listening for changes in network reachability status. + open func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + mutableState.write { state in + state.listener = nil + state.listenerQueue = nil + state.previousStatus = nil + } + } + + // MARK: - Internal - Listener Notification + + /// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed. + /// + /// - Note: Should only be called from the `reachabilityQueue`. + /// + /// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status. + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + let newStatus = NetworkReachabilityStatus(flags) + + mutableState.write { state in + guard state.previousStatus != newStatus else { return } + + state.previousStatus = newStatus + + let listener = state.listener + state.listenerQueue?.async { listener?(newStatus) } + } + } + + private final class WeakManager { + weak var manager: NetworkReachabilityManager? + + init(manager: NetworkReachabilityManager?) { + self.manager = manager + } + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +extension SCNetworkReachabilityFlags { + var isReachable: Bool { contains(.reachable) } + var isConnectionRequired: Bool { contains(.connectionRequired) } + var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) } + var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) } + var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) } + var isCellular: Bool { + #if os(iOS) || os(tvOS) || (swift(>=5.9) && os(visionOS)) + return contains(.isWWAN) + #else + return false + #endif + } + + /// Human readable `String` for all states, to help with debugging. + var readableDescription: String { + let W = isCellular ? "W" : "-" + let R = isReachable ? "R" : "-" + let c = isConnectionRequired ? "c" : "-" + let t = contains(.transientConnection) ? "t" : "-" + let i = contains(.interventionRequired) ? "i" : "-" + let C = contains(.connectionOnTraffic) ? "C" : "-" + let D = contains(.connectionOnDemand) ? "D" : "-" + let l = contains(.isLocalAddress) ? "l" : "-" + let d = contains(.isDirect) ? "d" : "-" + let a = contains(.connectionAutomatic) ? "a" : "-" + + return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)" + } +} +#endif diff --git a/ChatBot/Pods/Alamofire/Source/Features/RedirectHandler.swift b/ChatBot/Pods/Alamofire/Source/Features/RedirectHandler.swift new file mode 100644 index 00000000..cf88abf5 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/RedirectHandler.swift @@ -0,0 +1,111 @@ +// +// RedirectHandler.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request. +public protocol RedirectHandler { + /// Determines how the HTTP redirect response should be redirected to the new request. + /// + /// The `completion` closure should be passed one of three possible options: + /// + /// 1. The new request specified by the redirect (this is the most common use case). + /// 2. A modified version of the new request (you may want to route it somewhere else). + /// 3. A `nil` value to deny the redirect request and return the body of the redirect response. + /// + /// - Parameters: + /// - task: The `URLSessionTask` whose request resulted in a redirect. + /// - request: The `URLRequest` to the new location specified by the redirect response. + /// - response: The `HTTPURLResponse` containing the server's response to the original request. + /// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`. + func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) +} + +// MARK: - + +/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. +public struct Redirector { + /// Defines the behavior of the `Redirector` type. + public enum Behavior { + /// Follow the redirect as defined in the response. + case follow + /// Do not follow the redirect defined in the response. + case doNotFollow + /// Modify the redirect request defined in the response. + case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) + } + + /// Returns a `Redirector` with a `.follow` `Behavior`. + public static let follow = Redirector(behavior: .follow) + /// Returns a `Redirector` with a `.doNotFollow` `Behavior`. + public static let doNotFollow = Redirector(behavior: .doNotFollow) + + /// The `Behavior` of the `Redirector`. + public let behavior: Behavior + + /// Creates a `Redirector` instance from the `Behavior`. + /// + /// - Parameter behavior: The `Behavior`. + public init(behavior: Behavior) { + self.behavior = behavior + } +} + +// MARK: - + +extension Redirector: RedirectHandler { + public func task(_ task: URLSessionTask, + willBeRedirectedTo request: URLRequest, + for response: HTTPURLResponse, + completion: @escaping (URLRequest?) -> Void) { + switch behavior { + case .follow: + completion(request) + case .doNotFollow: + completion(nil) + case let .modify(closure): + let request = closure(task, request, response) + completion(request) + } + } +} + +extension RedirectHandler where Self == Redirector { + /// Provides a `Redirector` which follows redirects. Equivalent to `Redirector.follow`. + public static var follow: Redirector { .follow } + + /// Provides a `Redirector` which does not follow redirects. Equivalent to `Redirector.doNotFollow`. + public static var doNotFollow: Redirector { .doNotFollow } + + /// Creates a `Redirector` which modifies the redirected `URLRequest` using the provided closure. + /// + /// - Parameter closure: Closure used to modify the redirect. + /// - Returns: The `Redirector`. + public static func modify(using closure: @escaping (URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) -> Redirector { + Redirector(behavior: .modify(closure)) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/RequestCompression.swift b/ChatBot/Pods/Alamofire/Source/Features/RequestCompression.swift new file mode 100644 index 00000000..1f848908 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/RequestCompression.swift @@ -0,0 +1,146 @@ +// +// RequestCompression.swift +// +// Copyright (c) 2023 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if canImport(zlib) +import Foundation +import zlib + +/// `RequestAdapter` which compresses outgoing `URLRequest` bodies using the `deflate` `Content-Encoding` and adds the +/// appropriate header. +/// +/// - Note: Most requests to most APIs are small and so would only be slowed down by applying this adapter. Measure the +/// size of your request bodies and the performance impact of using this adapter before use. Using this adapter +/// with already compressed data, such as images, will, at best, have no effect. Additionally, body compression +/// is a synchronous operation, so measuring the performance impact may be important to determine whether you +/// want to use a dedicated `requestQueue` in your `Session` instance. Finally, not all servers support request +/// compression, so test with all of your server configurations before deploying. +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +public struct DeflateRequestCompressor: RequestInterceptor { + /// Type that determines the action taken when the `URLRequest` already has a `Content-Encoding` header. + public enum DuplicateHeaderBehavior { + /// Throws a `DuplicateHeaderError`. The default. + case error + /// Replaces the existing header value with `deflate`. + case replace + /// Silently skips compression when the header exists. + case skip + } + + /// `Error` produced when the outgoing `URLRequest` already has a `Content-Encoding` header, when the instance has + /// been configured to produce an error. + public struct DuplicateHeaderError: Error {} + + /// Behavior to use when the outgoing `URLRequest` already has a `Content-Encoding` header. + public let duplicateHeaderBehavior: DuplicateHeaderBehavior + /// Closure which determines whether the outgoing body data should be compressed. + public let shouldCompressBodyData: (_ bodyData: Data) -> Bool + + /// Creates an instance with the provided parameters. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. `.error` by default. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + public init(duplicateHeaderBehavior: DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true }) { + self.duplicateHeaderBehavior = duplicateHeaderBehavior + self.shouldCompressBodyData = shouldCompressBodyData + } + + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + // No need to compress unless we have body data. No support for compressing streams. + guard let bodyData = urlRequest.httpBody else { + completion(.success(urlRequest)) + return + } + + guard shouldCompressBodyData(bodyData) else { + completion(.success(urlRequest)) + return + } + + if urlRequest.headers.value(for: "Content-Encoding") != nil { + switch duplicateHeaderBehavior { + case .error: + completion(.failure(DuplicateHeaderError())) + return + case .replace: + // Header will be replaced once the body data is compressed. + break + case .skip: + completion(.success(urlRequest)) + return + } + } + + var compressedRequest = urlRequest + + do { + compressedRequest.httpBody = try deflate(bodyData) + compressedRequest.headers.update(.contentEncoding("deflate")) + completion(.success(compressedRequest)) + } catch { + completion(.failure(error)) + } + } + + func deflate(_ data: Data) throws -> Data { + var output = Data([0x78, 0x5E]) // Header + try output.append((data as NSData).compressed(using: .zlib) as Data) + var checksum = adler32Checksum(of: data).bigEndian + output.append(Data(bytes: &checksum, count: MemoryLayout.size)) + + return output + } + + func adler32Checksum(of data: Data) -> UInt32 { + data.withUnsafeBytes { buffer in + UInt32(adler32(1, buffer.baseAddress, UInt32(buffer.count))) + } + } +} + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension RequestInterceptor where Self == DeflateRequestCompressor { + /// Create a `DeflateRequestCompressor` with default `duplicateHeaderBehavior` and `shouldCompressBodyData` values. + public static var deflateCompressor: DeflateRequestCompressor { + DeflateRequestCompressor() + } + + /// Creates a `DeflateRequestCompressor` with the provided `DuplicateHeaderBehavior` and `shouldCompressBodyData` + /// closure. + /// + /// - Parameters: + /// - duplicateHeaderBehavior: `DuplicateHeaderBehavior` to use. + /// - shouldCompressBodyData: Closure which determines whether the outgoing body data should be compressed. `true` by default. + /// + /// - Returns: The `DeflateRequestCompressor`. + public static func deflateCompressor( + duplicateHeaderBehavior: DeflateRequestCompressor.DuplicateHeaderBehavior = .error, + shouldCompressBodyData: @escaping (_ bodyData: Data) -> Bool = { _ in true } + ) -> DeflateRequestCompressor { + DeflateRequestCompressor(duplicateHeaderBehavior: duplicateHeaderBehavior, + shouldCompressBodyData: shouldCompressBodyData) + } +} +#endif diff --git a/ChatBot/Pods/Alamofire/Source/Features/RequestInterceptor.swift b/ChatBot/Pods/Alamofire/Source/Features/RequestInterceptor.swift new file mode 100644 index 00000000..9acd9860 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/RequestInterceptor.swift @@ -0,0 +1,351 @@ +// +// RequestInterceptor.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Stores all state associated with a `URLRequest` being adapted. +public struct RequestAdapterState { + /// The `UUID` of the `Request` associated with the `URLRequest` to adapt. + public let requestID: UUID + + /// The `Session` associated with the `URLRequest` to adapt. + public let session: Session +} + +// MARK: - + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - session: The `Session` that will execute the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) + + /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result. + /// + /// - Parameters: + /// - urlRequest: The `URLRequest` to adapt. + /// - state: The `RequestAdapterState` associated with the `URLRequest`. + /// - completion: The completion handler that must be called when adaptation is complete. + func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) +} + +extension RequestAdapter { + public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: state.session, completion: completion) + } +} + +// MARK: - + +/// Outcome of determination whether retry is necessary. +public enum RetryResult { + /// Retry should be attempted immediately. + case retry + /// Retry should be attempted after the associated `TimeInterval`. + case retryWithDelay(TimeInterval) + /// Do not retry. + case doNotRetry + /// Do not retry due to the associated `Error`. + case doNotRetryWithError(Error) +} + +extension RetryResult { + var retryRequired: Bool { + switch self { + case .retry, .retryWithDelay: return true + default: return false + } + } + + var delay: TimeInterval? { + switch self { + case let .retryWithDelay(delay): return delay + default: return nil + } + } + + var error: Error? { + guard case let .doNotRetryWithError(error) = self else { return nil } + return error + } +} + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - session: `Session` that produced the `Request`. + /// - error: `Error` encountered while executing the `Request`. + /// - completion: Completion closure to be executed when a retry decision has been determined. + func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) +} + +// MARK: - + +/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality. +public protocol RequestInterceptor: RequestAdapter, RequestRetrier {} + +extension RequestInterceptor { + public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + completion(.success(urlRequest)) + } + + public func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + completion(.doNotRetry) + } +} + +/// `RequestAdapter` closure definition. +public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result) -> Void) -> Void +/// `RequestRetrier` closure definition. +public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void + +// MARK: - + +/// Closure-based `RequestAdapter`. +open class Adapter: RequestInterceptor { + private let adaptHandler: AdaptHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation. + public init(_ adaptHandler: @escaping AdaptHandler) { + self.adaptHandler = adaptHandler + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adaptHandler(urlRequest, session, completion) + } + + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adaptHandler(urlRequest, state.session, completion) + } +} + +extension RequestAdapter where Self == Adapter { + /// Creates an `Adapter` using the provided `AdaptHandler` closure. + /// + /// - Parameter closure: `AdaptHandler` to use to adapt the request. + /// - Returns: The `Adapter`. + public static func adapter(using closure: @escaping AdaptHandler) -> Adapter { + Adapter(closure) + } +} + +// MARK: - + +/// Closure-based `RequestRetrier`. +open class Retrier: RequestInterceptor { + private let retryHandler: RetryHandler + + /// Creates an instance using the provided closure. + /// + /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry. + public init(_ retryHandler: @escaping RetryHandler) { + self.retryHandler = retryHandler + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retryHandler(request, session, error, completion) + } +} + +extension RequestRetrier where Self == Retrier { + /// Creates a `Retrier` using the provided `RetryHandler` closure. + /// + /// - Parameter closure: `RetryHandler` to use to retry the request. + /// - Returns: The `Retrier`. + public static func retrier(using closure: @escaping RetryHandler) -> Retrier { + Retrier(closure) + } +} + +// MARK: - + +/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values. +open class Interceptor: RequestInterceptor { + /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails. + public let adapters: [RequestAdapter] + /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry. + public let retriers: [RequestRetrier] + + /// Creates an instance from `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adaptHandler: `AdaptHandler` closure to be used. + /// - retryHandler: `RetryHandler` closure to be used. + public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) { + adapters = [Adapter(adaptHandler)] + retriers = [Retrier(retryHandler)] + } + + /// Creates an instance from `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapter: `RequestAdapter` value to be used. + /// - retrier: `RequestRetrier` value to be used. + public init(adapter: RequestAdapter, retrier: RequestRetrier) { + adapters = [adapter] + retriers = [retrier] + } + + /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values. + /// + /// - Parameters: + /// - adapters: `RequestAdapter` values to be used. + /// - retriers: `RequestRetrier` values to be used. + /// - interceptors: `RequestInterceptor`s to be used. + public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) { + self.adapters = adapters + interceptors + self.retriers = retriers + interceptors + } + + open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) { + adapt(urlRequest, for: session, using: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + for session: Session, + using adapters: [RequestAdapter], + completion: @escaping (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, for: session) { result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result) -> Void) { + adapt(urlRequest, using: state, adapters: adapters, completion: completion) + } + + private func adapt(_ urlRequest: URLRequest, + using state: RequestAdapterState, + adapters: [RequestAdapter], + completion: @escaping (Result) -> Void) { + var pendingAdapters = adapters + + guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return } + + let adapter = pendingAdapters.removeFirst() + + adapter.adapt(urlRequest, using: state) { result in + switch result { + case let .success(urlRequest): + self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion) + case .failure: + completion(result) + } + } + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + retry(request, for: session, dueTo: error, using: retriers, completion: completion) + } + + private func retry(_ request: Request, + for session: Session, + dueTo error: Error, + using retriers: [RequestRetrier], + completion: @escaping (RetryResult) -> Void) { + var pendingRetriers = retriers + + guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return } + + let retrier = pendingRetriers.removeFirst() + + retrier.retry(request, for: session, dueTo: error) { result in + switch result { + case .retry, .retryWithDelay, .doNotRetryWithError: + completion(result) + case .doNotRetry: + // Only continue to the next retrier if retry was not triggered and no error was encountered + self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion) + } + } + } +} + +extension RequestInterceptor where Self == Interceptor { + /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures. + /// + /// - Parameters: + /// - adapter: `AdapterHandler`to use to adapt the request. + /// - retrier: `RetryHandler` to use to retry the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor { + Interceptor(adaptHandler: adapter, retryHandler: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances. + /// - Parameters: + /// - adapter: `RequestAdapter` to use to adapt the request + /// - retrier: `RequestRetrier` to use to retry the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapter: RequestAdapter, retrier: RequestRetrier) -> Interceptor { + Interceptor(adapter: adapter, retrier: retrier) + } + + /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s. + /// - Parameters: + /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails. + /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until + /// a retry is triggered. + /// - interceptors: `RequestInterceptor`s to use to intercept the request. + /// - Returns: The `Interceptor`. + public static func interceptor(adapters: [RequestAdapter] = [], + retriers: [RequestRetrier] = [], + interceptors: [RequestInterceptor] = []) -> Interceptor { + Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/ResponseSerialization.swift b/ChatBot/Pods/Alamofire/Source/Features/ResponseSerialization.swift new file mode 100644 index 00000000..b765bdb6 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/ResponseSerialization.swift @@ -0,0 +1,525 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The type to which all data response serializers must conform in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the response `Data` into the provided type. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - data: `Data` returned from the server, if any. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject +} + +/// The type to which all download response serializers must conform in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created. + associatedtype SerializedObject + + /// Serialize the downloaded response `Data` from disk into the provided type. + /// + /// - Parameters: + /// - request: `URLRequest` which was used to perform the request, if any. + /// - response: `HTTPURLResponse` received from the server, if any. + /// - fileURL: File `URL` to which the response data was downloaded. + /// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request. + /// + /// - Returns: The `SerializedObject`. + /// - Throws: Any `Error` produced during serialization. + func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject +} + +/// A serializer that can handle both data and download responses. +public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { + /// `DataPreprocessor` used to prepare incoming `Data` for serialization. + var dataPreprocessor: DataPreprocessor { get } + /// `HTTPMethod`s for which empty response bodies are considered appropriate. + var emptyRequestMethods: Set { get } + /// HTTP response codes for which empty response bodies are considered appropriate. + var emptyResponseCodes: Set { get } +} + +/// Type used to preprocess `Data` before it handled by a serializer. +public protocol DataPreprocessor { + /// Process `Data` before it's handled by a serializer. + /// - Parameter data: The raw `Data` to process. + func preprocess(_ data: Data) throws -> Data +} + +/// `DataPreprocessor` that returns passed `Data` without any transform. +public struct PassthroughPreprocessor: DataPreprocessor { + /// Creates an instance. + public init() {} + + public func preprocess(_ data: Data) throws -> Data { data } +} + +/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header. +public struct GoogleXSSIPreprocessor: DataPreprocessor { + /// Creates an instance. + public init() {} + + public func preprocess(_ data: Data) throws -> Data { + (data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data + } +} + +extension DataPreprocessor where Self == PassthroughPreprocessor { + /// Provides a `PassthroughPreprocessor` instance. + public static var passthrough: PassthroughPreprocessor { PassthroughPreprocessor() } +} + +extension DataPreprocessor where Self == GoogleXSSIPreprocessor { + /// Provides a `GoogleXSSIPreprocessor` instance. + public static var googleXSSI: GoogleXSSIPreprocessor { GoogleXSSIPreprocessor() } +} + +extension ResponseSerializer { + /// Default `DataPreprocessor`. `PassthroughPreprocessor` by default. + public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() } + /// Default `HTTPMethod`s for which empty response bodies are always considered appropriate. `[.head]` by default. + public static var defaultEmptyRequestMethods: Set { [.head] } + /// HTTP response codes for which empty response bodies are always considered appropriate. `[204, 205]` by default. + public static var defaultEmptyResponseCodes: Set { [204, 205] } + + public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor } + public var emptyRequestMethods: Set { Self.defaultEmptyRequestMethods } + public var emptyResponseCodes: Set { Self.defaultEmptyResponseCodes } + + /// Determines whether the `request` allows empty response bodies, if `request` exists. + /// + /// - Parameter request: `URLRequest` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`. + public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? { + request.flatMap(\.httpMethod) + .flatMap(HTTPMethod.init) + .map { emptyRequestMethods.contains($0) } + } + + /// Determines whether the `response` allows empty response bodies, if `response` exists. + /// + /// - Parameter response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`. + public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? { + response.map(\.statusCode) + .map { emptyResponseCodes.contains($0) } + } + + /// Determines whether `request` and `response` allow empty response bodies. + /// + /// - Parameters: + /// - request: `URLRequest` to evaluate. + /// - response: `HTTPURLResponse` to evaluate. + /// + /// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise. + public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool { + (requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true) + } +} + +/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds +/// the data read from disk into the data response serializer. +extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol { + public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject { + guard error == nil else { throw error! } + + guard let fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + let data: Data + do { + data = try Data(contentsOf: fileURL) + } catch { + throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)) + } + + do { + return try serialize(request: request, response: response, data: data, error: error) + } catch { + throw error + } + } +} + +// MARK: - URL + +/// A `DownloadResponseSerializerProtocol` that performs only `Error` checking and ensures that a downloaded `fileURL` +/// is present. +public struct URLResponseSerializer: DownloadResponseSerializerProtocol { + /// Creates an instance. + public init() {} + + public func serializeDownload(request: URLRequest?, + response: HTTPURLResponse?, + fileURL: URL?, + error: Error?) throws -> URL { + guard error == nil else { throw error! } + + guard let url = fileURL else { + throw AFError.responseSerializationFailed(reason: .inputFileNil) + } + + return url + } +} + +extension DownloadResponseSerializerProtocol where Self == URLResponseSerializer { + /// Provides a `URLResponseSerializer` instance. + public static var url: URLResponseSerializer { URLResponseSerializer() } +} + +// MARK: - Data + +/// A `ResponseSerializer` that performs minimal response checking and returns any response `Data` as-is. By default, a +/// request returning `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the +/// response has an HTTP status code valid for empty responses, then an empty `Data` value is returned. +public final class DataResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Data { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return Data() + } + + data = try dataPreprocessor.preprocess(data) + + return data + } +} + +extension ResponseSerializer where Self == DataResponseSerializer { + /// Provides a default `DataResponseSerializer` instance. + public static var data: DataResponseSerializer { DataResponseSerializer() } + + /// Creates a `DataResponseSerializer` using the provided parameters. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DataResponseSerializer`. + public static func data(dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponseSerializer { + DataResponseSerializer(dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +// MARK: - String + +/// A `ResponseSerializer` that decodes the response data as a `String`. By default, a request returning `nil` or no +/// data is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code +/// valid for empty responses, then an empty `String` is returned. +public final class StringResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// Optional string encoding used to validate the response. + public let encoding: String.Encoding? + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.encoding = encoding + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> String { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return "" + } + + data = try dataPreprocessor.preprocess(data) + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName, convertedEncoding == nil { + convertedEncoding = String.Encoding(ianaCharsetName: encodingName) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + guard let string = String(data: data, encoding: actualEncoding) else { + throw AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)) + } + + return string + } +} + +extension ResponseSerializer where Self == StringResponseSerializer { + /// Provides a default `StringResponseSerializer` instance. + public static var string: StringResponseSerializer { StringResponseSerializer() } + + /// Creates a `StringResponseSerializer` with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - encoding: A string encoding. Defaults to `nil`, in which case the encoding will be determined + /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `StringResponseSerializer`. + public static func string(dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, + encoding: String.Encoding? = nil, + emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> StringResponseSerializer { + StringResponseSerializer(dataPreprocessor: dataPreprocessor, + encoding: encoding, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} + +// MARK: - JSON + +/// A `ResponseSerializer` that decodes the response data using `JSONSerialization`. By default, a request returning +/// `nil` or no data is considered an error. However, if the request has an `HTTPMethod` or the response has an +/// HTTP status code valid for empty responses, then an `NSNull` value is returned. +/// +/// - Note: This serializer is deprecated and should not be used. Instead, create concrete types conforming to +/// `Decodable` and use a `DecodableResponseSerializer`. +@available(*, deprecated, message: "JSONResponseSerializer deprecated and will be removed in Alamofire 6. Use DecodableResponseSerializer instead.") +public final class JSONResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + /// `JSONSerialization.ReadingOptions` used when serializing a response. + public let options: JSONSerialization.ReadingOptions + + /// Creates an instance with the provided values. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// - options: The options to use. `.allowFragments` by default. + public init(dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments) { + self.dataPreprocessor = dataPreprocessor + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + self.options = options + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Any { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + return NSNull() + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch { + throw AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)) + } + } +} + +// MARK: - Empty + +/// Protocol representing an empty response. Use `T.emptyValue()` to get an instance. +public protocol EmptyResponse { + /// Empty value for the conforming type. + /// + /// - Returns: Value of `Self` to use for empty values. + static func emptyValue() -> Self +} + +/// Type representing an empty value. Use `Empty.value` to get the static instance. +public struct Empty: Codable, Sendable { + /// Static `Empty` instance used for all `Empty` responses. + public static let value = Empty() +} + +extension Empty: EmptyResponse { + public static func emptyValue() -> Empty { + value + } +} + +// MARK: - DataDecoder Protocol + +/// Any type which can decode `Data` into a `Decodable` type. +public protocol DataDecoder { + /// Decode `Data` into the provided type. + /// + /// - Parameters: + /// - type: The `Type` to be decoded. + /// - data: The `Data` to be decoded. + /// + /// - Returns: The decoded value of type `D`. + /// - Throws: Any error that occurs during decode. + func decode(_ type: D.Type, from data: Data) throws -> D +} + +/// `JSONDecoder` automatically conforms to `DataDecoder`. +extension JSONDecoder: DataDecoder {} +/// `PropertyListDecoder` automatically conforms to `DataDecoder`. +extension PropertyListDecoder: DataDecoder {} + +// MARK: - Decodable + +/// A `ResponseSerializer` that decodes the response data as a generic value using any type that conforms to +/// `DataDecoder`. By default, this is an instance of `JSONDecoder`. Additionally, a request returning `nil` or no data +/// is considered an error. However, if the request has an `HTTPMethod` or the response has an HTTP status code valid +/// for empty responses then an empty value will be returned. If the decoded type conforms to `EmptyResponse`, the +/// type's `emptyValue()` will be returned. If the decoded type is `Empty`, the `.value` instance is returned. If the +/// decoded type *does not* conform to `EmptyResponse` and isn't `Empty`, an error will be produced. +public final class DecodableResponseSerializer: ResponseSerializer { + public let dataPreprocessor: DataPreprocessor + /// The `DataDecoder` instance used to decode responses. + public let decoder: DataDecoder + public let emptyResponseCodes: Set + public let emptyRequestMethods: Set + + /// Creates an instance using the values provided. + /// + /// - Parameters: + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + public init(dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) { + self.dataPreprocessor = dataPreprocessor + self.decoder = decoder + self.emptyResponseCodes = emptyResponseCodes + self.emptyRequestMethods = emptyRequestMethods + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { + guard error == nil else { throw error! } + + guard var data, !data.isEmpty else { + guard emptyResponseAllowed(forRequest: request, response: response) else { + throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) + } + + guard let emptyResponseType = T.self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? T else { + throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\(T.self)")) + } + + return emptyValue + } + + data = try dataPreprocessor.preprocess(data) + + do { + return try decoder.decode(T.self, from: data) + } catch { + throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error)) + } + } +} + +extension ResponseSerializer { + /// Creates a `DecodableResponseSerializer` using the values provided. + /// + /// - Parameters: + /// - type: `Decodable` type to decode from response data. + /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. + /// - decoder: The `DataDecoder`. `JSONDecoder()` by default. + /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. `[204, 205]` by default. + /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. `[.head]` by default. + /// + /// - Returns: The `DecodableResponseSerializer`. + public static func decodable(of type: T.Type, + dataPreprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor, + decoder: DataDecoder = JSONDecoder(), + emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DecodableResponseSerializer where Self == DecodableResponseSerializer { + DecodableResponseSerializer(dataPreprocessor: dataPreprocessor, + decoder: decoder, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/RetryPolicy.swift b/ChatBot/Pods/Alamofire/Source/Features/RetryPolicy.swift new file mode 100644 index 00000000..bb52c6c0 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/RetryPolicy.swift @@ -0,0 +1,430 @@ +// +// RetryPolicy.swift +// +// Copyright (c) 2019-2020 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes +/// as well as certain types of networking errors. +open class RetryPolicy: RequestInterceptor { + /// The default retry limit for retry policies. + public static let defaultRetryLimit: UInt = 2 + + /// The default exponential backoff base for retry policies (must be a minimum of 2). + public static let defaultExponentialBackoffBase: UInt = 2 + + /// The default exponential backoff scale for retry policies. + public static let defaultExponentialBackoffScale: Double = 0.5 + + /// The default HTTP methods to retry. + /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information. + public static let defaultRetryableHTTPMethods: Set = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent + .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent + .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent + .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent + .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent + .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent + ] + + /// The default HTTP status codes to retry. + /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information. + public static let defaultRetryableHTTPStatusCodes: Set = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9) + 500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1) + 502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3) + 503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4) + 504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5) + ] + + /// The default URL error codes to retry. + public static let defaultRetryableURLErrorCodes: Set = [ // [Security] App Transport Security disallowed a connection because there is no secure network connection. + // - [Disabled] ATS settings do not change at runtime. + // .appTransportSecurityRequiresSecureConnection, + + // [System] An app or app extension attempted to connect to a background session that is already connected to a + // process. + // - [Enabled] The other process could release the background session. + .backgroundSessionInUseByAnotherProcess, + + // [System] The shared container identifier of the URL session configuration is needed but has not been set. + // - [Disabled] Cannot change at runtime. + // .backgroundSessionRequiresSharedContainer, + + // [System] The app is suspended or exits while a background data task is processing. + // - [Enabled] App can be foregrounded or launched to recover. + .backgroundSessionWasDisconnected, + + // [Network] The URL Loading system received bad data from the server. + // - [Enabled] Server could return valid data when retrying. + .badServerResponse, + + // [Resource] A malformed URL prevented a URL request from being initiated. + // - [Disabled] URL was most likely constructed incorrectly. + // .badURL, + + // [System] A connection was attempted while a phone call is active on a network that does not support + // simultaneous phone and data communication (EDGE or GPRS). + // - [Enabled] Phone call could be ended to allow request to recover. + .callIsActive, + + // [Client] An asynchronous load has been canceled. + // - [Disabled] Request was cancelled by the client. + // .cancelled, + + // [File System] A download task couldn’t close the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCloseFile, + + // [Network] An attempt to connect to a host failed. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotConnectToHost, + + // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotCreateFile, + + // [Data] Content data received during a connection request had an unknown content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeContentData, + + // [Data] Content data received during a connection request could not be decoded for a known content encoding. + // - [Disabled] Server is unlikely to modify the content encoding during a retry. + // .cannotDecodeRawData, + + // [Network] The host name for a URL could not be resolved. + // - [Enabled] Server or DNS lookup could recover during retry. + .cannotFindHost, + + // [Network] A request to load an item only from the cache could not be satisfied. + // - [Enabled] Cache could be populated during a retry. + .cannotLoadFromNetwork, + + // [File System] A download task was unable to move a downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotMoveFile, + + // [File System] A download task was unable to open the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotOpenFile, + + // [Data] A task could not parse a response. + // - [Disabled] Invalid response is unlikely to recover with retry. + // .cannotParseResponse, + + // [File System] A download task was unable to remove a downloaded file from disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotRemoveFile, + + // [File System] A download task was unable to write to the downloaded file on disk. + // - [Disabled] File system error is unlikely to recover with retry. + // .cannotWriteToFile, + + // [Security] A client certificate was rejected. + // - [Disabled] Client certificate is unlikely to change with retry. + // .clientCertificateRejected, + + // [Security] A client certificate was required to authenticate an SSL connection during a request. + // - [Disabled] Client certificate is unlikely to be provided with retry. + // .clientCertificateRequired, + + // [Data] The length of the resource data exceeds the maximum allowed. + // - [Disabled] Resource will likely still exceed the length maximum on retry. + // .dataLengthExceedsMaximum, + + // [System] The cellular network disallowed a connection. + // - [Enabled] WiFi connection could be established during retry. + .dataNotAllowed, + + // [Network] The host address could not be found via DNS lookup. + // - [Enabled] DNS lookup could succeed during retry. + .dnsLookupFailed, + + // [Data] A download task failed to decode an encoded file during the download. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedMidStream, + + // [Data] A download task failed to decode an encoded file after downloading. + // - [Enabled] Server could correct the decoding issue with retry. + .downloadDecodingFailedToComplete, + + // [File System] A file does not exist. + // - [Disabled] File system error is unlikely to recover with retry. + // .fileDoesNotExist, + + // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file, + // but a directory. + // - [Disabled] FTP directory is not likely to change to a file during a retry. + // .fileIsDirectory, + + // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been + // exceeded (currently 16). + // - [Disabled] The redirect loop is unlikely to be resolved within the retry window. + // .httpTooManyRedirects, + + // [System] The attempted connection required activating a data context while roaming, but international roaming + // is disabled. + // - [Enabled] WiFi connection could be established during retry. + .internationalRoamingOff, + + // [Connectivity] A client or server connection was severed in the middle of an in-progress load. + // - [Enabled] A network connection could be established during retry. + .networkConnectionLost, + + // [File System] A resource couldn’t be read because of insufficient permissions. + // - [Disabled] Permissions are unlikely to be granted during retry. + // .noPermissionsToReadFile, + + // [Connectivity] A network resource was requested, but an internet connection has not been established and + // cannot be established automatically. + // - [Enabled] A network connection could be established during retry. + .notConnectedToInternet, + + // [Resource] A redirect was specified by way of server response code, but the server did not accompany this + // code with a redirect URL. + // - [Disabled] The redirect URL is unlikely to be supplied during a retry. + // .redirectToNonExistentLocation, + + // [Client] A body stream is needed but the client did not provide one. + // - [Disabled] The client will be unlikely to supply a body stream during retry. + // .requestBodyStreamExhausted, + + // [Resource] A requested resource couldn’t be retrieved. + // - [Disabled] The resource is unlikely to become available during the retry window. + // .resourceUnavailable, + + // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more + // specifically. + // - [Enabled] The secure connection could be established during a retry given the lack of specificity + // provided by the error. + .secureConnectionFailed, + + // [Security] A server certificate had a date which indicates it has expired, or is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateHasBadDate, + + // [Security] A server certificate was not signed by any root server. + // - [Disabled] The server certificate is unlikely to change during the retry window. + // .serverCertificateHasUnknownRoot, + + // [Security] A server certificate is not yet valid. + // - [Enabled] The server certificate could become valid within the retry window. + .serverCertificateNotYetValid, + + // [Security] A server certificate was signed by a root server that isn’t trusted. + // - [Disabled] The server certificate is unlikely to become trusted within the retry window. + // .serverCertificateUntrusted, + + // [Network] An asynchronous operation timed out. + // - [Enabled] The request timed out for an unknown reason and should be retried. + .timedOut + + // [System] The URL Loading System encountered an error that it can’t interpret. + // - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry. + // .unknown, + + // [Resource] A properly formed URL couldn’t be handled by the framework. + // - [Disabled] The URL is unlikely to change during a retry. + // .unsupportedURL, + + // [Client] Authentication is required to access a resource. + // - [Disabled] The user authentication is unlikely to be provided by retrying. + // .userAuthenticationRequired, + + // [Client] An asynchronous request for authentication has been canceled by the user. + // - [Disabled] The user cancelled authentication and explicitly took action to not retry. + // .userCancelledAuthentication, + + // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection + // gracefully without sending any data. + // - [Disabled] The server is unlikely to provide data during the retry window. + // .zeroByteResource, + ] + + /// The total number of times the request is allowed to be retried. + public let retryLimit: UInt + + /// The base of the exponential backoff policy (should always be greater than or equal to 2). + public let exponentialBackoffBase: UInt + + /// The scale of the exponential backoff. + public let exponentialBackoffScale: Double + + /// The HTTP methods that are allowed to be retried. + public let retryableHTTPMethods: Set + + /// The HTTP status codes that are automatically retried by the policy. + public let retryableHTTPStatusCodes: Set + + /// The URL error codes that are automatically retried by the policy. + public let retryableURLErrorCodes: Set + + /// Creates a `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) { + precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.") + + self.retryLimit = retryLimit + self.exponentialBackoffBase = exponentialBackoffBase + self.exponentialBackoffScale = exponentialBackoffScale + self.retryableHTTPMethods = retryableHTTPMethods + self.retryableHTTPStatusCodes = retryableHTTPStatusCodes + self.retryableURLErrorCodes = retryableURLErrorCodes + } + + open func retry(_ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void) { + if request.retryCount < retryLimit, shouldRetry(request: request, dueTo: error) { + completion(.retryWithDelay(pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale)) + } else { + completion(.doNotRetry) + } + } + + /// Determines whether or not to retry the provided `Request`. + /// + /// - Parameters: + /// - request: `Request` that failed due to the provided `Error`. + /// - error: `Error` encountered while executing the `Request`. + /// + /// - Returns: `Bool` determining whether or not to retry the `Request`. + open func shouldRetry(request: Request, dueTo error: Error) -> Bool { + guard let httpMethod = request.request?.method, retryableHTTPMethods.contains(httpMethod) else { return false } + + if let statusCode = request.response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { + return true + } else { + let errorCode = (error as? URLError)?.code + let afErrorCode = (error.asAFError?.underlyingError as? URLError)?.code + + guard let code = errorCode ?? afErrorCode else { return false } + + return retryableURLErrorCodes.contains(code) + } + } +} + +extension RequestInterceptor where Self == RetryPolicy { + /// Provides a default `RetryPolicy` instance. + public static var retryPolicy: RetryPolicy { RetryPolicy() } + + /// Creates an `RetryPolicy` from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. `2` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. `2` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. `0.5` by default. + /// - retryableHTTPMethods: The HTTP methods that are allowed to be retried. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + /// - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableHTTPStatusCodes` by default. + /// - retryableURLErrorCodes: The URL error codes that are automatically retried by the policy. + /// `RetryPolicy.defaultRetryableURLErrorCodes` by default. + /// + /// - Returns: The `RetryPolicy` + public static func retryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods, + retryableHTTPStatusCodes: Set = RetryPolicy.defaultRetryableHTTPStatusCodes, + retryableURLErrorCodes: Set = RetryPolicy.defaultRetryableURLErrorCodes) -> RetryPolicy { + RetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: retryableHTTPStatusCodes, + retryableURLErrorCodes: retryableURLErrorCodes) + } +} + +// MARK: - + +/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more +/// information about retrying network connection lost errors, please refer to Apple's +/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html). +open class ConnectionLostRetryPolicy: RetryPolicy { + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// `RetryPolicy.defaultRetryableHTTPMethods` by default. + public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) { + super.init(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods, + retryableHTTPStatusCodes: [], + retryableURLErrorCodes: [.networkConnectionLost]) + } +} + +extension RequestInterceptor where Self == ConnectionLostRetryPolicy { + /// Provides a default `ConnectionLostRetryPolicy` instance. + public static var connectionLostRetryPolicy: ConnectionLostRetryPolicy { ConnectionLostRetryPolicy() } + + /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters. + /// + /// - Parameters: + /// - retryLimit: The total number of times the request is allowed to be retried. + /// `RetryPolicy.defaultRetryLimit` by default. + /// - exponentialBackoffBase: The base of the exponential backoff policy. + /// `RetryPolicy.defaultExponentialBackoffBase` by default. + /// - exponentialBackoffScale: The scale of the exponential backoff. + /// `RetryPolicy.defaultExponentialBackoffScale` by default. + /// - retryableHTTPMethods: The idempotent http methods to retry. + /// + /// - Returns: The `ConnectionLostRetryPolicy`. + public static func connectionLostRetryPolicy(retryLimit: UInt = RetryPolicy.defaultRetryLimit, + exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase, + exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale, + retryableHTTPMethods: Set = RetryPolicy.defaultRetryableHTTPMethods) -> ConnectionLostRetryPolicy { + ConnectionLostRetryPolicy(retryLimit: retryLimit, + exponentialBackoffBase: exponentialBackoffBase, + exponentialBackoffScale: exponentialBackoffScale, + retryableHTTPMethods: retryableHTTPMethods) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/ServerTrustEvaluation.swift b/ChatBot/Pods/Alamofire/Source/Features/ServerTrustEvaluation.swift new file mode 100644 index 00000000..7e6cb104 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/ServerTrustEvaluation.swift @@ -0,0 +1,768 @@ +// +// ServerTrustEvaluation.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts. +open class ServerTrustManager { + /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default. + public let allHostsMustBeEvaluated: Bool + + /// The dictionary of policies mapped to a particular host. + public let evaluators: [String: ServerTrustEvaluating] + + /// Initializes the `ServerTrustManager` instance with the given evaluators. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - Parameters: + /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true` + /// by default. + /// - evaluators: A dictionary of evaluators mapped to hosts. + public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) { + self.allHostsMustBeEvaluated = allHostsMustBeEvaluated + self.evaluators = evaluators + } + + #if canImport(Security) + /// Returns the `ServerTrustEvaluating` value for the given host, if one is set. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - Parameter host: The host to use when searching for a matching policy. + /// + /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise. + /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching + /// evaluators are found. + open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? { + guard let evaluator = evaluators[host] else { + if allHostsMustBeEvaluated { + throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host)) + } + + return nil + } + + return evaluator + } + #endif +} + +/// A protocol describing the API used to evaluate server trusts. +public protocol ServerTrustEvaluating { + #if !canImport(Security) + // Implement this once other platforms have API for evaluating server trusts. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`. + func evaluate(_ trust: SecTrust, forHost host: String) throws + #endif +} + +// MARK: - Server Trust Evaluators + +#if canImport(Security) +/// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the +/// host provided by the challenge. Applications are encouraged to always validate the host in production environments +/// to guarantee the validity of the server's certificate chain. +public final class DefaultTrustEvaluator: ServerTrustEvaluating { + private let validateHost: Bool + + /// Creates a `DefaultTrustEvaluator`. + /// + /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default. + public init(validateHost: Bool = true) { + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if validateHost { + try trust.af.performValidation(forHost: host) + } + + try trust.af.performDefaultValidation(forHost: host) + } +} + +/// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate +/// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates. +/// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS +/// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production +/// environments to guarantee the validity of the server's certificate chain. +public final class RevocationTrustEvaluator: ServerTrustEvaluating { + /// Represents the options to be use when evaluating the status of a certificate. + /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants). + public struct Options: OptionSet { + /// Perform revocation checking using the CRL (Certification Revocation List) method. + public static let crl = Options(rawValue: kSecRevocationCRLMethod) + /// Consult only locally cached replies; do not use network access. + public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled) + /// Perform revocation checking using OCSP (Online Certificate Status Protocol). + public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod) + /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred. + public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL) + /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a + /// "best attempt" basis, where failure to reach the server is not considered fatal. + public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse) + /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the + /// certificate and the value of `preferCRL`. + public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod) + + /// The raw value of the option. + public let rawValue: CFOptionFlags + + /// Creates an `Options` value with the given `CFOptionFlags`. + /// + /// - Parameter rawValue: The `CFOptionFlags` value to initialize with. + public init(rawValue: CFOptionFlags) { + self.rawValue = rawValue + } + } + + private let performDefaultValidation: Bool + private let validateHost: Bool + private let options: Options + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` by + /// default. + public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) { + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + self.options = options + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + #if swift(>=5.9) + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { + try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) + } else { + try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) + } + } + #else + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options)) + } else { + try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options)) + } + } + #endif + } +} + +extension ServerTrustEvaluating where Self == RevocationTrustEvaluator { + /// Provides a default `RevocationTrustEvaluator` instance. + public static var revocationChecking: RevocationTrustEvaluator { RevocationTrustEvaluator() } + + /// Creates a `RevocationTrustEvaluator` using the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + /// - options: The `Options` to use to check the revocation status of the certificate. `.any` + /// by default. + /// - Returns: The `RevocationTrustEvaluator`. + public static func revocationChecking(performDefaultValidation: Bool = true, + validateHost: Bool = true, + options: RevocationTrustEvaluator.Options = .any) -> RevocationTrustEvaluator { + RevocationTrustEvaluator(performDefaultValidation: performDefaultValidation, + validateHost: validateHost, + options: options) + } +} + +/// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned +/// certificates match one of the server certificates. By validating both the certificate chain and host, certificate +/// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating { + private let certificates: [SecCertificate] + private let acceptSelfSignedCertificates: Bool + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PinnedCertificatesTrustEvaluator` from the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public init(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.certificates = certificates + self.acceptSelfSignedCertificates = acceptSelfSignedCertificates + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !certificates.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) + } + + if acceptSelfSignedCertificates { + try trust.af.setAnchorCertificates(certificates) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let serverCertificatesData = Set(trust.af.certificateData) + let pinnedCertificatesData = Set(certificates.af.data) + let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData) + if !pinnedCertificatesInServerData { + throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host, + trust: trust, + pinnedCertificates: certificates, + serverCertificates: trust.af.certificates)) + } + } +} + +extension ServerTrustEvaluating where Self == PinnedCertificatesTrustEvaluator { + /// Provides a default `PinnedCertificatesTrustEvaluator` instance. + public static var pinnedCertificates: PinnedCertificatesTrustEvaluator { PinnedCertificatesTrustEvaluator() } + + /// Creates a `PinnedCertificatesTrustEvaluator` using the provided parameters. + /// + /// - Parameters: + /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der` + /// certificates in `Bundle.main` by default. + /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing + /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE + /// FALSE IN PRODUCTION! + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition + /// to performing the default evaluation, even if `performDefaultValidation` is + /// `false`. `true` by default. + public static func pinnedCertificates(certificates: [SecCertificate] = Bundle.main.af.certificates, + acceptSelfSignedCertificates: Bool = false, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PinnedCertificatesTrustEvaluator { + PinnedCertificatesTrustEvaluator(certificates: certificates, + acceptSelfSignedCertificates: acceptSelfSignedCertificates, + performDefaultValidation: performDefaultValidation, + validateHost: validateHost) + } +} + +/// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned +/// public keys match one of the server certificate public keys. By validating both the certificate chain and host, +/// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate chain in production +/// environments. +public final class PublicKeysTrustEvaluator: ServerTrustEvaluating { + private let keys: [SecKey] + private let performDefaultValidation: Bool + private let validateHost: Bool + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public init(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) { + self.keys = keys + self.performDefaultValidation = performDefaultValidation + self.validateHost = validateHost + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + guard !keys.isEmpty else { + throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound) + } + + if performDefaultValidation { + try trust.af.performDefaultValidation(forHost: host) + } + + if validateHost { + try trust.af.performValidation(forHost: host) + } + + let pinnedKeysInServerKeys: Bool = { + for serverPublicKey in trust.af.publicKeys { + if keys.contains(serverPublicKey) { + return true + } + } + return false + }() + + if !pinnedKeysInServerKeys { + throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host, + trust: trust, + pinnedKeys: keys, + serverKeys: trust.af.publicKeys)) + } + } +} + +extension ServerTrustEvaluating where Self == PublicKeysTrustEvaluator { + /// Provides a default `PublicKeysTrustEvaluator` instance. + public static var publicKeys: PublicKeysTrustEvaluator { PublicKeysTrustEvaluator() } + + /// Creates a `PublicKeysTrustEvaluator` from the provided parameters. + /// + /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use + /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates. + /// + /// - Parameters: + /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all + /// certificates included in the main bundle. + /// - performDefaultValidation: Determines whether default validation should be performed in addition to + /// evaluating the pinned certificates. `true` by default. + /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to + /// performing the default evaluation, even if `performDefaultValidation` is `false`. + /// `true` by default. + public static func publicKeys(keys: [SecKey] = Bundle.main.af.publicKeys, + performDefaultValidation: Bool = true, + validateHost: Bool = true) -> PublicKeysTrustEvaluator { + PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: performDefaultValidation, validateHost: validateHost) + } +} + +/// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the +/// evaluators consider it valid. +public final class CompositeTrustEvaluator: ServerTrustEvaluating { + private let evaluators: [ServerTrustEvaluating] + + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public init(evaluators: [ServerTrustEvaluating]) { + self.evaluators = evaluators + } + + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + try evaluators.evaluate(trust, forHost: host) + } +} + +extension ServerTrustEvaluating where Self == CompositeTrustEvaluator { + /// Creates a `CompositeTrustEvaluator` from the provided evaluators. + /// + /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. + public static func composite(evaluators: [ServerTrustEvaluating]) -> CompositeTrustEvaluator { + CompositeTrustEvaluator(evaluators: evaluators) + } +} + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +@available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.") +public typealias DisabledEvaluator = DisabledTrustEvaluator + +/// Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// +/// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test +/// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html). +/// +/// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** +public final class DisabledTrustEvaluator: ServerTrustEvaluating { + /// Creates an instance. + public init() {} + + public func evaluate(_ trust: SecTrust, forHost host: String) throws {} +} + +// MARK: - Extensions + +extension [ServerTrustEvaluating] { + #if os(Linux) || os(Windows) || os(Android) + // Add this same convenience method for Linux/Windows. + #else + /// Evaluates the given `SecTrust` value for the given `host`. + /// + /// - Parameters: + /// - trust: The `SecTrust` value to evaluate. + /// - host: The host for which to evaluate the `SecTrust` value. + /// + /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`. + public func evaluate(_ trust: SecTrust, forHost host: String) throws { + for evaluator in self { + try evaluator.evaluate(trust, forHost: host) + } + } + #endif +} + +extension Bundle: AlamofireExtended {} +extension AlamofireExtension where ExtendedType: Bundle { + /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle. + public var certificates: [SecCertificate] { + paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in + guard + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil } + + return certificate + } + } + + /// Returns all public keys for the valid certificates in the bundle. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// Returns all pathnames for the resources identified by the provided file extensions. + /// + /// - Parameter types: The filename extensions locate. + /// + /// - Returns: All pathnames for the given filename extensions. + public func paths(forResourcesOfTypes types: [String]) -> [String] { + Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) })) + } +} + +extension SecTrust: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrust { + /// Evaluates `self` after applying the `SecPolicy` value provided. + /// + /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation. + /// + /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate(afterApplying policy: SecPolicy) throws { + try apply(policy: policy).af.evaluate() + } + + /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed. + /// + /// - Parameters: + /// - policy: The `SecPolicy` used to evaluate `self`. + /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`. + /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)") + public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + try apply(policy: policy).af.validate(errorProducer: errorProducer) + } + + /// Applies a `SecPolicy` to `self`, throwing if it fails. + /// + /// - Parameter policy: The `SecPolicy`. + /// + /// - Returns: `self`, with the policy applied. + /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason. + public func apply(policy: SecPolicy) throws -> SecTrust { + let status = SecTrustSetPolicies(type, policy) + + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type, + policy: policy, + status: status)) + } + + return type + } + + /// Evaluate `self`, throwing an `Error` if evaluation fails. + /// + /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from + /// the underlying evaluation. + @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) + public func evaluate() throws { + var error: CFError? + let evaluationSucceeded = SecTrustEvaluateWithError(type, &error) + + if !evaluationSucceeded { + throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error)) + } + } + + /// Validate `self`, passing any failure values through `errorProducer`. + /// + /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an + /// `Error`. + /// - Throws: The `Error` produced by the `errorProducer` closure. + @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()") + @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()") + @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()") + public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws { + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(type, &result) + + guard status.af.isSuccess && result.af.isSuccess else { + throw errorProducer(status, result) + } + } + + /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain. + /// + /// - Parameter certificates: The `SecCertificate`s to add to the chain. + /// - Throws: Any error produced when applying the new certificate chain. + public func setAnchorCertificates(_ certificates: [SecCertificate]) throws { + // Add additional anchor certificates. + let status = SecTrustSetAnchorCertificates(type, certificates as CFArray) + guard status.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status, + certificates: certificates)) + } + + // Trust only the set anchor certs. + let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true) + guard onlyStatus.af.isSuccess else { + throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus, + certificates: certificates)) + } + } + + /// The public keys contained in `self`. + public var publicKeys: [SecKey] { + certificates.af.publicKeys + } + + /// The `SecCertificate`s contained in `self`. + public var certificates: [SecCertificate] { + #if swift(>=5.9) + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, visionOS 1, *) { + return (SecTrustCopyCertificateChain(type) as? [SecCertificate]) ?? [] + } else { + return (0..=5.9) + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { + try evaluate(afterApplying: SecPolicy.af.default) + } else { + try validate(policy: SecPolicy.af.default) { status, result in + AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result))) + } + } + #else + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try evaluate(afterApplying: SecPolicy.af.default) + } else { + try validate(policy: SecPolicy.af.default) { status, result in + AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result))) + } + } + #endif + } + + /// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as + /// hostname validation. + /// + /// - Parameter host: The hostname to use in the validation. + /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason. + public func performValidation(forHost host: String) throws { + #if swift(>=5.9) + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, visionOS 1, *) { + try evaluate(afterApplying: SecPolicy.af.hostname(host)) + } else { + try validate(policy: SecPolicy.af.hostname(host)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result))) + } + } + #else + if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { + try evaluate(afterApplying: SecPolicy.af.hostname(host)) + } else { + try validate(policy: SecPolicy.af.hostname(host)) { status, result in + AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result))) + } + } + #endif + } +} + +extension SecPolicy: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecPolicy { + /// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match. + public static let `default` = SecPolicyCreateSSL(true, nil) + + /// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname. + /// + /// - Parameter hostname: The hostname to validate against. + /// + /// - Returns: The `SecPolicy`. + public static func hostname(_ hostname: String) -> SecPolicy { + SecPolicyCreateSSL(true, hostname as CFString) + } + + /// Creates a `SecPolicy` which checks the revocation of certificates. + /// + /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation. + /// + /// - Returns: The `SecPolicy`. + /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed` + /// if the policy cannot be created. + public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy { + guard let policy = SecPolicyCreateRevocation(options.rawValue) else { + throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed) + } + + return policy + } +} + +extension Array: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == [SecCertificate] { + /// All `Data` values for the contained `SecCertificate`s. + public var data: [Data] { + type.map { SecCertificateCopyData($0) as Data } + } + + /// All public `SecKey` values for the contained `SecCertificate`s. + public var publicKeys: [SecKey] { + type.compactMap(\.af.publicKey) + } +} + +extension SecCertificate: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecCertificate { + /// The public key for `self`, if it can be extracted. + /// + /// - Note: On 2020 OSes and newer, only RSA and ECDSA keys are supported. + /// + public var publicKey: SecKey? { + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust) + + guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil } + + #if swift(>=5.9) + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, visionOS 1, *) { + return SecTrustCopyKey(createdTrust) + } else { + return SecTrustCopyPublicKey(createdTrust) + } + #else + if #available(iOS 14, macOS 11, tvOS 14, watchOS 7, *) { + return SecTrustCopyKey(createdTrust) + } else { + return SecTrustCopyPublicKey(createdTrust) + } + #endif + } +} + +extension OSStatus: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == OSStatus { + /// Returns whether `self` is `errSecSuccess`. + public var isSuccess: Bool { type == errSecSuccess } +} + +extension SecTrustResultType: AlamofireExtended {} +extension AlamofireExtension where ExtendedType == SecTrustResultType { + /// Returns whether `self` is `.unspecified` or `.proceed`. + public var isSuccess: Bool { + type == .unspecified || type == .proceed + } +} +#endif diff --git a/ChatBot/Pods/Alamofire/Source/Features/URLEncodedFormEncoder.swift b/ChatBot/Pods/Alamofire/Source/Features/URLEncodedFormEncoder.swift new file mode 100644 index 00000000..a2156b1c --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/URLEncodedFormEncoder.swift @@ -0,0 +1,1151 @@ +// +// URLEncodedFormEncoder.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// An object that encodes instances into URL-encoded query strings. +/// +/// `ArrayEncoding` can be used to configure how `Array` values are encoded. By default, the `.brackets` encoding is +/// used, encoding array values with brackets for each value. e.g `array[]=1&array[]=2`. +/// +/// `BoolEncoding` can be used to configure how `Bool` values are encoded. By default, the `.numeric` encoding is used, +/// encoding `true` as `1` and `false` as `0`. +/// +/// `DataEncoding` can be used to configure how `Data` values are encoded. By default, the `.deferredToData` encoding is +/// used, which encodes `Data` values using their default `Encodable` implementation. +/// +/// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` +/// encoding is used, which encodes `Date`s using their default `Encodable` implementation. +/// +/// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used, +/// which encodes the keys directly from the `Encodable` implementation. +/// +/// `KeyPathEncoding` can be used to configure how paths within nested objects are encoded. By default, the `.brackets` +/// encoding is used, which encodes each sub-key in brackets. e.g. `parent[child][grandchild]=value`. +/// +/// `NilEncoding` can be used to configure how `nil` `Optional` values are encoded. By default, the `.dropKey` encoding +/// is used, which drops `nil` key / value pairs from the output entirely. +/// +/// `SpaceEncoding` can be used to configure how spaces are encoded. By default, the `.percentEscaped` encoding is used, +/// replacing spaces with `%20`. +/// +/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. +public final class URLEncodedFormEncoder { + /// Encoding to use for `Array` values. + public enum ArrayEncoding { + /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding. + case brackets + /// No brackets are appended to the key and the key is encoded as is. + case noBrackets + /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. + case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((_ key: String, _ index: Int) -> String) + + /// Encodes the key according to the encoding. + /// + /// - Parameters: + /// - key: The `key` to encode. + /// - index: When this enum instance is `.indexInBrackets`, the `index` to encode. + /// + /// - Returns: The encoded key. + func encode(_ key: String, atIndex index: Int) -> String { + switch self { + case .brackets: return "\(key)[]" + case .noBrackets: return key + case .indexInBrackets: return "\(key)[\(index)]" + case let .custom(encoding): return encoding(key, index) + } + } + } + + /// Encoding to use for `Bool` values. + public enum BoolEncoding { + /// Encodes `true` as `1`, `false` as `0`. + case numeric + /// Encodes `true` as "true", `false` as "false". This is the default encoding. + case literal + + /// Encodes the given `Bool` as a `String`. + /// + /// - Parameter value: The `Bool` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ value: Bool) -> String { + switch self { + case .numeric: return value ? "1" : "0" + case .literal: return value ? "true" : "false" + } + } + } + + /// Encoding to use for `Data` values. + public enum DataEncoding { + /// Defers encoding to the `Data` type. + case deferredToData + /// Encodes `Data` as a Base64-encoded string. This is the default encoding. + case base64 + /// Encode the `Data` as a custom value encoded by the given closure. + case custom((Data) throws -> String) + + /// Encodes `Data` according to the encoding. + /// + /// - Parameter data: The `Data` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its + /// `Encodable` implementation. + func encode(_ data: Data) throws -> String? { + switch self { + case .deferredToData: return nil + case .base64: return data.base64EncodedString() + case let .custom(encoding): return try encoding(data) + } + } + } + + /// Encoding to use for `Date` values. + public enum DateEncoding { + /// ISO8601 and RFC3339 formatter. + private static let iso8601Formatter: ISO8601DateFormatter = { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = .withInternetDateTime + return formatter + }() + + /// Defers encoding to the `Date` type. This is the default encoding. + case deferredToDate + /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970. + case secondsSince1970 + /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970. + case millisecondsSince1970 + /// Encodes `Date`s according to the ISO8601 and RFC3339 standards. + case iso8601 + /// Encodes `Date`s using the given `DateFormatter`. + case formatted(DateFormatter) + /// Encodes `Date`s using the given closure. + case custom((Date) throws -> String) + + /// Encodes the date according to the encoding. + /// + /// - Parameter date: The `Date` to encode. + /// + /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its + /// `Encodable` implementation. + func encode(_ date: Date) throws -> String? { + switch self { + case .deferredToDate: + return nil + case .secondsSince1970: + return String(date.timeIntervalSince1970) + case .millisecondsSince1970: + return String(date.timeIntervalSince1970 * 1000.0) + case .iso8601: + return DateEncoding.iso8601Formatter.string(from: date) + case let .formatted(formatter): + return formatter.string(from: date) + case let .custom(closure): + return try closure(date) + } + } + } + + /// Encoding to use for keys. + /// + /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128) + /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102). + public enum KeyEncoding { + /// Use the keys specified by each type. This is the default encoding. + case useDefaultKeys + /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key. + /// + /// Capital characters are determined by testing membership in + /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` + /// (Unicode General Categories Lu and Lt). + /// The conversion to lower case uses `Locale.system`, also known as + /// the ICU "root" locale. This means the result is consistent + /// regardless of the current user's locale and language preferences. + /// + /// Converting from camel case to snake case: + /// 1. Splits words at the boundary of lower-case to upper-case + /// 2. Inserts `_` between words + /// 3. Lowercases the entire string + /// 4. Preserves starting and ending `_`. + /// + /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. + /// + /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. + case convertToSnakeCase + /// Same as convertToSnakeCase, but using `-` instead of `_`. + /// For example `oneTwoThree` becomes `one-two-three`. + case convertToKebabCase + /// Capitalize the first letter only. + /// For example `oneTwoThree` becomes `OneTwoThree`. + case capitalized + /// Uppercase all letters. + /// For example `oneTwoThree` becomes `ONETWOTHREE`. + case uppercased + /// Lowercase all letters. + /// For example `oneTwoThree` becomes `onetwothree`. + case lowercased + /// A custom encoding using the provided closure. + case custom((String) -> String) + + func encode(_ key: String) -> String { + switch self { + case .useDefaultKeys: return key + case .convertToSnakeCase: return convertToSnakeCase(key) + case .convertToKebabCase: return convertToKebabCase(key) + case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst()) + case .uppercased: return key.uppercased() + case .lowercased: return key.lowercased() + case let .custom(encoding): return encoding(key) + } + } + + private func convertToSnakeCase(_ key: String) -> String { + convert(key, usingSeparator: "_") + } + + private func convertToKebabCase(_ key: String) -> String { + convert(key, usingSeparator: "-") + } + + private func convert(_ key: String, usingSeparator separator: String) -> String { + guard !key.isEmpty else { return key } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on + // transition from lower to upper case, then on transition of >1 + // upper case characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // It is assumed, per Swift naming conventions, that the first character of the key is lowercase. + var wordStart = key.startIndex + var searchRange = key.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before + // the lower case character. + let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound.. String + + /// Creates an instance with the encoding closure called for each sub-key in a key path. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping (_ subkey: String) -> String) { + self.encoding = encoding + } + + func encodeKeyPath(_ keyPath: String) -> String { + encoding(keyPath) + } + } + + /// Encoding to use for `nil` values. + public struct NilEncoding { + /// Encodes `nil` by dropping the entire key / value pair. + public static let dropKey = NilEncoding { nil } + /// Encodes `nil` by dropping only the value. e.g. `value1=one&nilValue=&value2=two`. + public static let dropValue = NilEncoding { "" } + /// Encodes `nil` as `null`. + public static let null = NilEncoding { "null" } + + private let encoding: () -> String? + + /// Creates an instance with the encoding closure called for `nil` values. + /// + /// - Parameter encoding: Closure used to perform the encoding. + public init(encoding: @escaping () -> String?) { + self.encoding = encoding + } + + func encodeNil() -> String? { + encoding() + } + } + + /// Encoding to use for spaces. + public enum SpaceEncoding { + /// Encodes spaces using percent escaping (`%20`). + case percentEscaped + /// Encodes spaces as `+`. + case plusReplaced + + /// Encodes the string according to the encoding. + /// + /// - Parameter string: The `String` to encode. + /// + /// - Returns: The encoded `String`. + func encode(_ string: String) -> String { + switch self { + case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") + case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") + } + } + } + + /// `URLEncodedFormEncoder` error. + public enum Error: Swift.Error { + /// An invalid root object was created by the encoder. Only keyed values are valid. + case invalidRootObject(String) + + var localizedDescription: String { + switch self { + case let .invalidRootObject(object): + return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." + } + } + } + + /// Whether or not to sort the encoded key value pairs. + /// + /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, + /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to + /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order. + public let alphabetizeKeyValuePairs: Bool + /// The `ArrayEncoding` to use. + public let arrayEncoding: ArrayEncoding + /// The `BoolEncoding` to use. + public let boolEncoding: BoolEncoding + /// THe `DataEncoding` to use. + public let dataEncoding: DataEncoding + /// The `DateEncoding` to use. + public let dateEncoding: DateEncoding + /// The `KeyEncoding` to use. + public let keyEncoding: KeyEncoding + /// The `KeyPathEncoding` to use. + public let keyPathEncoding: KeyPathEncoding + /// The `NilEncoding` to use. + public let nilEncoding: NilEncoding + /// The `SpaceEncoding` to use. + public let spaceEncoding: SpaceEncoding + /// The `CharacterSet` of allowed (non-escaped) characters. + public var allowedCharacters: CharacterSet + + /// Creates an instance from the supplied parameters. + /// + /// - Parameters: + /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. + /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. + /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default. + /// - dataEncoding: The `DataEncoding` to use. `.base64` by default. + /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default. + /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default. + /// - nilEncoding: The `NilEncoding` to use. `.drop` by default. + /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default. + /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by + /// default. + public init(alphabetizeKeyValuePairs: Bool = true, + arrayEncoding: ArrayEncoding = .brackets, + boolEncoding: BoolEncoding = .numeric, + dataEncoding: DataEncoding = .base64, + dateEncoding: DateEncoding = .deferredToDate, + keyEncoding: KeyEncoding = .useDefaultKeys, + keyPathEncoding: KeyPathEncoding = .brackets, + nilEncoding: NilEncoding = .dropKey, + spaceEncoding: SpaceEncoding = .percentEscaped, + allowedCharacters: CharacterSet = .afURLQueryAllowed) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.nilEncoding = nilEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func encode(_ value: Encodable) throws -> URLEncodedFormComponent { + let context = URLEncodedFormContext(.object([])) + let encoder = _URLEncodedFormEncoder(context: context, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + + return context.component + } + + /// Encodes the `value` as a URL form encoded `String`. + /// + /// - Parameter value: The `Encodable` value. + /// + /// - Returns: The encoded `String`. + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> String { + let component: URLEncodedFormComponent = try encode(value) + + guard case let .object(object) = component else { + throw Error.invalidRootObject("\(component)") + } + + let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs, + arrayEncoding: arrayEncoding, + keyEncoding: keyEncoding, + keyPathEncoding: keyPathEncoding, + spaceEncoding: spaceEncoding, + allowedCharacters: allowedCharacters) + let query = serializer.serialize(object) + + return query + } + + /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the + /// `.utf8` data. + /// + /// - Parameter value: The `Encodable` value. + /// + /// - Returns: The encoded `Data`. + /// + /// - Throws: An `Error` or `EncodingError` instance if encoding fails. + public func encode(_ value: Encodable) throws -> Data { + let string: String = try encode(value) + + return Data(string.utf8) + } +} + +final class _URLEncodedFormEncoder { + var codingPath: [CodingKey] + // Returns an empty dictionary, as this encoder doesn't support userInfo. + var userInfo: [CodingUserInfoKey: Any] { [:] } + + let context: URLEncodedFormContext + + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey] = [], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } +} + +extension _URLEncodedFormEncoder: Encoder { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { + _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func singleValueContainer() -> SingleValueEncodingContainer { + _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormContext { + var component: URLEncodedFormComponent + + init(_ component: URLEncodedFormComponent) { + self.component = component + } +} + +enum URLEncodedFormComponent { + typealias Object = [(key: String, value: URLEncodedFormComponent)] + + case string(String) + case array([URLEncodedFormComponent]) + case object(Object) + + /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible. + var array: [URLEncodedFormComponent]? { + switch self { + case let .array(array): return array + default: return nil + } + } + + /// Converts self to an `Object` or returns `nil` if not convertible. + var object: Object? { + switch self { + case let .object(object): return object + default: return nil + } + } + + /// Sets self to the supplied value at a given path. + /// + /// data.set(to: "hello", at: ["path", "to", "value"]) + /// + /// - parameters: + /// - value: Value of `Self` to set at the supplied path. + /// - path: `CodingKey` path to update with the supplied value. + public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) { + set(&self, to: value, at: path) + } + + /// Recursive backing method to `set(to:at:)`. + private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) { + guard !path.isEmpty else { + context = value + return + } + + let end = path[0] + var child: URLEncodedFormComponent + switch path.count { + case 1: + child = value + case 2...: + if let index = end.intValue { + let array = context.array ?? [] + if array.count > index { + child = array[index] + } else { + child = .array([]) + } + set(&child, to: value, at: Array(path[1...])) + } else { + child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init()) + set(&child, to: value, at: Array(path[1...])) + } + default: fatalError("Unreachable") + } + + if let index = end.intValue { + if var array = context.array { + if array.count > index { + array[index] = child + } else { + array.append(child) + } + context = .array(array) + } else { + context = .array([child]) + } + } else { + if var object = context.object { + if let index = object.firstIndex(where: { $0.key == end.stringValue }) { + object[index] = (key: end.stringValue, value: child) + } else { + object.append((key: end.stringValue, value: child)) + } + context = .object(object) + } else { + context = .object([(key: end.stringValue, value: child)]) + } + } + } +} + +struct AnyCodingKey: CodingKey, Hashable { + let stringValue: String + let intValue: Int? + + init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } + + init(_ base: Key) where Key: CodingKey { + if let intValue = base.intValue { + self.init(intValue: intValue)! + } else { + self.init(stringValue: base.stringValue)! + } + } +} + +extension _URLEncodedFormEncoder { + final class KeyedContainer where Key: CodingKey { + var codingPath: [CodingKey] + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func nestedCodingPath(for key: CodingKey) -> [CodingKey] { + codingPath + [key] + } + } +} + +extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol { + func encodeNil(forKey key: Key) throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue, forKey: key) + } + + func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: String?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Double?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Float?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { + try _encodeIfPresent(value, forKey: key) + } + + func encodeIfPresent(_ value: Value?, forKey key: Key) throws where Value: Encodable { + try _encodeIfPresent(value, forKey: key) + } + + func _encodeIfPresent(_ value: Value?, forKey key: Key) throws where Value: Encodable { + if let value { + try encode(value, forKey: key) + } else { + try encodeNil(forKey: key) + } + } + + func encode(_ value: T, forKey key: Key) throws where T: Encodable { + var container = nestedSingleValueEncoder(for: key) + try container.encode(value) + } + + func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer { + let container = _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { + let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return container + } + + func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey: CodingKey { + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func superEncoder() -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder(forKey key: Key) -> Encoder { + _URLEncodedFormEncoder(context: context, + codingPath: nestedCodingPath(for: key), + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +extension _URLEncodedFormEncoder { + final class SingleValueContainer { + var codingPath: [CodingKey] + + private var canEncodeNewValue = true + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + + private func checkCanEncode(value: Any?) throws { + guard canEncodeNewValue else { + let context = EncodingError.Context(codingPath: codingPath, + debugDescription: "Attempt to encode value through single value container when previously value already encoded.") + throw EncodingError.invalidValue(value as Any, context) + } + } + } +} + +extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: Bool) throws { + try encode(value, as: String(boolEncoding.encode(value))) + } + + func encode(_ value: String) throws { + try encode(value, as: value) + } + + func encode(_ value: Double) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Float) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: Int64) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt8) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt16) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt32) throws { + try encode(value, as: String(value)) + } + + func encode(_ value: UInt64) throws { + try encode(value, as: String(value)) + } + + private func encode(_ value: T, as string: String) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + context.component.set(to: .string(string), at: codingPath) + } + + func encode(_ value: T) throws where T: Encodable { + switch value { + case let date as Date: + guard let string = try dateEncoding.encode(date) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let data as Data: + guard let string = try dataEncoding.encode(data) else { + try attemptToEncode(value) + return + } + + try encode(value, as: string) + case let decimal as Decimal: + // Decimal's `Encodable` implementation returns an object, not a single value, so override it. + try encode(value, as: String(describing: decimal)) + default: + try attemptToEncode(value) + } + } + + private func attemptToEncode(_ value: T) throws where T: Encodable { + try checkCanEncode(value: value) + defer { canEncodeNewValue = false } + + let encoder = _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + try value.encode(to: encoder) + } +} + +extension _URLEncodedFormEncoder { + final class UnkeyedContainer { + var codingPath: [CodingKey] + + var count = 0 + var nestedCodingPath: [CodingKey] { + codingPath + [AnyCodingKey(intValue: count)!] + } + + private let context: URLEncodedFormContext + private let boolEncoding: URLEncodedFormEncoder.BoolEncoding + private let dataEncoding: URLEncodedFormEncoder.DataEncoding + private let dateEncoding: URLEncodedFormEncoder.DateEncoding + private let nilEncoding: URLEncodedFormEncoder.NilEncoding + + init(context: URLEncodedFormContext, + codingPath: [CodingKey], + boolEncoding: URLEncodedFormEncoder.BoolEncoding, + dataEncoding: URLEncodedFormEncoder.DataEncoding, + dateEncoding: URLEncodedFormEncoder.DateEncoding, + nilEncoding: URLEncodedFormEncoder.NilEncoding) { + self.context = context + self.codingPath = codingPath + self.boolEncoding = boolEncoding + self.dataEncoding = dataEncoding + self.dateEncoding = dateEncoding + self.nilEncoding = nilEncoding + } + } +} + +extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer { + func encodeNil() throws { + guard let nilValue = nilEncoding.encodeNil() else { return } + + try encode(nilValue) + } + + func encode(_ value: T) throws where T: Encodable { + var container = nestedSingleValueContainer() + try container.encode(value) + } + + func nestedSingleValueContainer() -> SingleValueEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.SingleValueContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey: CodingKey { + defer { count += 1 } + let container = _URLEncodedFormEncoder.KeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + + return KeyedEncodingContainer(container) + } + + func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { + defer { count += 1 } + + return _URLEncodedFormEncoder.UnkeyedContainer(context: context, + codingPath: nestedCodingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } + + func superEncoder() -> Encoder { + defer { count += 1 } + + return _URLEncodedFormEncoder(context: context, + codingPath: codingPath, + boolEncoding: boolEncoding, + dataEncoding: dataEncoding, + dateEncoding: dateEncoding, + nilEncoding: nilEncoding) + } +} + +final class URLEncodedFormSerializer { + private let alphabetizeKeyValuePairs: Bool + private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding + private let keyEncoding: URLEncodedFormEncoder.KeyEncoding + private let keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding + private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding + private let allowedCharacters: CharacterSet + + init(alphabetizeKeyValuePairs: Bool, + arrayEncoding: URLEncodedFormEncoder.ArrayEncoding, + keyEncoding: URLEncodedFormEncoder.KeyEncoding, + keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding, + spaceEncoding: URLEncodedFormEncoder.SpaceEncoding, + allowedCharacters: CharacterSet) { + self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs + self.arrayEncoding = arrayEncoding + self.keyEncoding = keyEncoding + self.keyPathEncoding = keyPathEncoding + self.spaceEncoding = spaceEncoding + self.allowedCharacters = allowedCharacters + } + + func serialize(_ object: URLEncodedFormComponent.Object) -> String { + var output: [String] = [] + for (key, component) in object { + let value = serialize(component, forKey: key) + output.append(value) + } + output = alphabetizeKeyValuePairs ? output.sorted() : output + + return output.joinedWithAmpersands() + } + + func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { + switch component { + case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))" + case let .array(array): return serialize(array, forKey: key) + case let .object(object): return serialize(object, forKey: key) + } + } + + func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String { + var segments: [String] = object.map { subKey, value in + let keyPath = keyPathEncoding.encodeKeyPath(subKey) + return serialize(value, forKey: key + keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { + var segments: [String] = array.enumerated().map { index, component in + let keyPath = arrayEncoding.encode(key, atIndex: index) + return serialize(component, forKey: keyPath) + } + segments = alphabetizeKeyValuePairs ? segments.sorted() : segments + + return segments.joinedWithAmpersands() + } + + func escape(_ query: String) -> String { + var allowedCharactersWithSpace = allowedCharacters + allowedCharactersWithSpace.insert(charactersIn: " ") + let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query + let spaceEncodedQuery = spaceEncoding.encode(escapedQuery) + + return spaceEncodedQuery + } +} + +extension [String] { + func joinedWithAmpersands() -> String { + joined(separator: "&") + } +} + +extension CharacterSet { + /// Creates a CharacterSet from RFC 3986 allowed characters. + /// + /// RFC 3986 states that the following characters are "reserved" characters. + /// + /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + /// + /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + /// should be percent-escaped in the query string. + public static let afURLQueryAllowed: CharacterSet = { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters) + }() +} diff --git a/ChatBot/Pods/Alamofire/Source/Features/Validation.swift b/ChatBot/Pods/Alamofire/Source/Features/Validation.swift new file mode 100644 index 00000000..eab45766 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/Features/Validation.swift @@ -0,0 +1,302 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether a validation succeeded or failed. + public typealias ValidationResult = Result + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: Range { 200..<300 } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate(statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int { + if acceptableStatusCodes.contains(response.statusCode) { + return .success(()) + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String { + guard let data, !data.isEmpty else { return .success(()) } + + return validate(contentType: acceptableContentTypes, response: response) + } + + fileprivate func validate(contentType acceptableContentTypes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == String { + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success(()) + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: acceptableContentTypes.sorted()) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success(()) + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: acceptableContentTypes.sorted(), + responseContentType: responseContentType) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response, data in + self.validate(contentType: acceptableContentTypes(), response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes: () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +extension DataStreamRequest { + /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the + /// request was valid. + public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response in + self.validate(contentType: acceptableContentTypes(), response: response) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Returns: The instance. + @discardableResult + public func validate() -> Self { + let contentTypes: () -> [String] = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = (_ request: URLRequest?, + _ response: HTTPURLResponse, + _ fileURL: URL?) + -> ValidationResult + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes. + /// + /// - Returns: The instance. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + validate { [unowned self] _, response, _ in + self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String { + validate { [unowned self] _, response, fileURL in + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes(), response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + let contentTypes = { [unowned self] in + acceptableContentTypes + } + return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) + } +} diff --git a/ChatBot/Pods/Alamofire/Source/PrivacyInfo.xcprivacy b/ChatBot/Pods/Alamofire/Source/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..488cbb11 --- /dev/null +++ b/ChatBot/Pods/Alamofire/Source/PrivacyInfo.xcprivacy @@ -0,0 +1,23 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategorySystemBootTime + NSPrivacyAccessedAPITypeReasons + + 35F9.1 + + + + + diff --git a/ChatBot/Pods/Manifest.lock b/ChatBot/Pods/Manifest.lock new file mode 100644 index 00000000..7f3fbab7 --- /dev/null +++ b/ChatBot/Pods/Manifest.lock @@ -0,0 +1,45 @@ +PODS: + - Alamofire (5.9.1) + - RxAlamofire (6.1.1): + - RxAlamofire/Core (= 6.1.1) + - RxAlamofire/Core (6.1.1): + - Alamofire (~> 5.4) + - RxSwift (~> 6.0) + - RxCocoa (6.5.0): + - RxRelay (= 6.5.0) + - RxSwift (= 6.5.0) + - RxRelay (6.5.0): + - RxSwift (= 6.5.0) + - RxSwift (6.5.0) + - SnapKit (5.7.1) + - Then (3.0.0) + +DEPENDENCIES: + - RxAlamofire + - RxCocoa (~> 6.5.0) + - RxSwift (~> 6.5.0) + - SnapKit (~> 5.7.0) + - Then + +SPEC REPOS: + trunk: + - Alamofire + - RxAlamofire + - RxCocoa + - RxRelay + - RxSwift + - SnapKit + - Then + +SPEC CHECKSUMS: + Alamofire: f36a35757af4587d8e4f4bfa223ad10be2422b8c + RxAlamofire: beb75a1c452d0de225651db4903f5d29d034a620 + RxCocoa: 94f817b71c07517321eb4f9ad299112ca8af743b + RxRelay: 1de1523e604c72b6c68feadedd1af3b1b4d0ecbd + RxSwift: 5710a9e6b17f3c3d6e40d6e559b9fa1e813b2ef8 + SnapKit: d612e99e678a2d3b95bf60b0705ed0a35c03484a + Then: 844265ae87834bbe1147d91d5d41a404da2ec27d + +PODFILE CHECKSUM: 7e0d07ea5c428039c896d73e099e3982d8244715 + +COCOAPODS: 1.14.3 diff --git a/ChatBot/Pods/Pods.xcodeproj/project.pbxproj b/ChatBot/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 00000000..99ff4e21 --- /dev/null +++ b/ChatBot/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,3416 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 01F4CE6D9DCBC1325DB52474E6D857FF /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BE3D39C8F07748932F044C9079EF373 /* Platform.Darwin.swift */; }; + 04A54AC2721CD67A178C2C922C6A798B /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECD7DA76959F3C43286DB917F3A24AEF /* Window.swift */; }; + 057D0EC1E728D714A73210ACAF1FAC6A /* UISearchBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 717C05410FB264842860E5EE81C2A9FF /* UISearchBar+Rx.swift */; }; + 07550E0A8451CACE9593873C543F1B78 /* RxTabBarControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 029ACF334268DD6E08782744E5E583B1 /* RxTabBarControllerDelegateProxy.swift */; }; + 0907413AF1BF312948C6CA8289CE29AE /* ControlProperty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B43007B2F375635F0F543820879F2C5 /* ControlProperty.swift */; }; + 091B0930115982BD92CC1D70D2A5BF21 /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = D17A927600BDBCA8E9CBD704B1A90D7F /* BehaviorSubject.swift */; }; + 0A5C290276F7453D9471E25BEA655842 /* ConstraintLayoutGuide.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0786D5A312B4358DA30CD934FEBE630 /* ConstraintLayoutGuide.swift */; }; + 0AD7A0DA8FF5880E3D8599062129AB12 /* ConstraintMakerEditable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60A46529099F1A13A3CFA08A9D4F5825 /* ConstraintMakerEditable.swift */; }; + 0B5BB08F1937AD6324F0ADDD8F9E067B /* Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B74AF3B54FBE109EB58A9D28762BE51 /* Driver.swift */; }; + 0CB47ABA6CF2F336790A6ADADC98FBCA /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA4AA34A4B5698D80B54272AC22D86A /* Sample.swift */; }; + 0D665B6767B345D8C70D7E029A2A48D8 /* ConstraintViewDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = F28F1ADB6CBBC92FA78ACCF525C8EF07 /* ConstraintViewDSL.swift */; }; + 0DA9A9D2F8960818017E26DA480FA143 /* ConstraintLayoutGuideDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 574C212A009E9DD99FD7689219748093 /* ConstraintLayoutGuideDSL.swift */; }; + 0F1D68554CA1AC595168E8FB4E1A6E63 /* CachedResponseHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A669D07C06527F67F9F5EA3A530BE61 /* CachedResponseHandler.swift */; }; + 103F1A8C3CF6BEECD11E01B05C5BE726 /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBFD850A4CBDB294862616A563E3AB71 /* RxMutableBox.swift */; }; + 10E361764348CA50879CDE3AEB5AF946 /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 415901951242B664A2B911C62154C000 /* Buffer.swift */; }; + 10F10A61A6D185762AEF2ECBD30BDD41 /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9398B7D245E1A375E3295C501C9E4C0E /* ConnectableObservableType.swift */; }; + 111810B8652D290C58076B92FCE40A1F /* RxPickerViewAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 449F164ADAF01D26FCA0CCF5FEBC8092 /* RxPickerViewAdapter.swift */; }; + 114F6342633413C8BBEC4169F34CFAFD /* RxTextViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45B1BCE02DC2388F30FBDBF9DB7EA27F /* RxTextViewDelegateProxy.swift */; }; + 12CCAB43B5D8AF62EB458BA947D9FC8D /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F1BDA54CA3FD66FFEBE84116D45C2DC /* ConcurrentMainScheduler.swift */; }; + 13CC0CFB1C56F23BBC872801F983C1A3 /* ConstraintLayoutSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B847CFA9EC1D1B3959AFBEFD46E6A491 /* ConstraintLayoutSupport.swift */; }; + 14A2DE0766AB513B0D321CF49386F8DD /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D114EF866038D865BB2CA522AE5DB6D /* AsyncLock.swift */; }; + 14CAA40442778EFE3DF8B07CE170CAF7 /* UITextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48FA0A5D99CA478DCAC3D6AA4F0BC343 /* UITextView+Rx.swift */; }; + 15F68E09ADCDB843B938C490059485BD /* ConstraintMakerRelatable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B52E420BECBD89CE2E82F8EE79CDCAC5 /* ConstraintMakerRelatable+Extensions.swift */; }; + 1787EBB3723875770997006509209EDD /* RxTableViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDBDCC4538898CA2A08F40F3200FA34B /* RxTableViewDataSourceProxy.swift */; }; + 1813B9F519EF0C8FC86FBA1FA8E6CA77 /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3076DC3B5B5110925CDB6D08D2D2374F /* Throttle.swift */; }; + 18211EE7B495AA06EBBED1D6FD9423C0 /* RxCocoa-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = EBE34063EEA4DA55E61FFD61C170D3C3 /* RxCocoa-dummy.m */; }; + 183F4AFDEDD14DD0C1DCBF8483CD3EC0 /* AtomicInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B5E514669455AC7CDFC7A7F3A83C31C /* AtomicInt.swift */; }; + 18471091D8FB4CFBF4CF0B62D2FBDB90 /* Decode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B2D1274E08FB6DDEC02B498198422B6 /* Decode.swift */; }; + 193CAAB846EDEDB62BBD22F61F64DC55 /* GroupedObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 264943C6B3A3AA13E3CDE698CA29690E /* GroupedObservable.swift */; }; + 196C06A99C54F2907FCE69E594E5A00B /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = E882E636762C2DE2DB0044AD197FADF4 /* CompactMap.swift */; }; + 1BDB4F8DFAF5BA5C3ED782FFB3A6C755 /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7924A346EAD4E87C41875A779EF066D1 /* ObservableConvertibleType.swift */; }; + 1CC3FBF38E35B664C2A003664C58E2D7 /* ControlEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09BFFFE07F21014134381D50352C279C /* ControlEvent.swift */; }; + 1D96D59ADA0DE50FCAC9E22B0BF00BA8 /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 856202112A1327779BA17C88CA19EA21 /* ReplaySubject.swift */; }; + 1E7E37C51375285EA22294CD2ADB3159 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0472F405283317F7A29275AEE20318B /* Debugging.swift */; }; + 1F64C124283555FF5E1944FA37501247 /* Signal+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = A886D886268384F906A6A2155C50E9FD /* Signal+Subscription.swift */; }; + 1F6F0B8C1A8EA633EFEBE64EB781A6B5 /* UINavigationController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66206B9155CD697680CDD63E69552C73 /* UINavigationController+Rx.swift */; }; + 2061A178B7AB446FA752910F59FEA8C4 /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DD265E1057FFAD9BEAC51E6D8D280C4 /* ScheduledItem.swift */; }; + 2087DD8278E2FC32F75C947E058EA423 /* NSObject+Rx+KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3279EA9AD5D4A54540E377F973965A63 /* NSObject+Rx+KVORepresentable.swift */; }; + 22D947BE5DFBE8BD471A215F9EF26183 /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FC5CC519367BF482C3936349FEFE33F /* RetryWhen.swift */; }; + 22F92D32F00189DC7B856E133736B0AE /* Infallible+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = D82CFCB2EA1D63276A4C46484CFDD495 /* Infallible+Operators.swift */; }; + 22FAFA41450EC40132CF4B0EEE7E6788 /* ParameterEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F4CCB3C159644E08405B0F8E4C14A9 /* ParameterEncoder.swift */; }; + 24C8FC3B11676AD57F3A7914E6621AD0 /* TextInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DDFA8FDE05F071E9CB3CFFD7D1198AF /* TextInput.swift */; }; + 250F6EBE090607C5CBDBA8CA6627CD3C /* Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA524373C17A6B9855D3A7609533BDB1 /* Reactive.swift */; }; + 252B64A12E2810921E86B78ECD5BDA9D /* UIApplication+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = F56E65F457FF030938F76858DC819B98 /* UIApplication+Rx.swift */; }; + 263A6B3B9C8592FC16697D2AB6333AC9 /* RxCocoa.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9D61CA24837D23444AC17D5836E6548 /* RxCocoa.swift */; }; + 2662EA3D1400EC4BD90947902CD85670 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C0343E12CDBD4EB4F143FAB1B9C5B50 /* Platform.Darwin.swift */; }; + 275C15979C1EC7DB6234974758037906 /* PublishRelay+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33D725EA40F13C08F36A24B9E06F4E0B /* PublishRelay+Signal.swift */; }; + 27F2BE5D6E990841E8DA1DF91CF3623B /* Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD5AFD8EB6E9537884257E4F1C42F8B1 /* Signal.swift */; }; + 28B20C35F4E1B3DDE716C831B049ADBC /* _RX.h in Headers */ = {isa = PBXBuildFile; fileRef = 18F7F490A910E7E0D76C88A07216708D /* _RX.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2987A730911012C32AF6695D7B54E35C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + 2AC794BEBE17BA6257A13065584EC5DF /* UIDatePicker+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4279D69741987540D0F56531AE01ABC8 /* UIDatePicker+Rx.swift */; }; + 2B230B24827053BA3E9DA0C78A796BC2 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DACEC6E20113CB147731DF4D114EAF9 /* ResponseSerialization.swift */; }; + 2B42D035AFF52D62722161A7772C6C08 /* HTTPHeaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = C857C2A40F26662E363000C1696FEB51 /* HTTPHeaders.swift */; }; + 2C4C08BB733A2101D945E8C37256F78F /* UploadRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34E8380CBACC761166B203FC3CCB5C78 /* UploadRequest.swift */; }; + 2CEEECD91A44E33E3A3241FD38E3DAF5 /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFE4765EE6079E252FB352B1B09F0BFC /* ScheduledDisposable.swift */; }; + 2D753CA94C0B51687DF83A74A014F321 /* SwiftSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02E615620C3410BBAE6D6999743D7F42 /* SwiftSupport.swift */; }; + 2EFF6DCB0FC66EB564B96A35840D5016 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = F586CD775793113152D995CE9D789F97 /* RxTableViewDataSourcePrefetchingProxy.swift */; }; + 2FCCAB4BA1D71EDB993309159D5DFA7C /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1C8536CD5EEA7448B5B8AFA116E6AE4 /* RecursiveLock.swift */; }; + 30883E7D247064BE76D27A675FAADD67 /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0223457AB5E07E184142B3486A399FF5 /* InvocableType.swift */; }; + 3091F1A82E0FD6ABA766EBC91D4E5DE6 /* Then.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AD61CEB655920AB20FCFEEEBF886775 /* Then.swift */; }; + 312652D3A84692893A71F7D98FFFB0DC /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76048962C0BC28502748A6199F2B937B /* Merge.swift */; }; + 3206D3B3E8A5500E86D4BBD3B2382988 /* RxAlamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = FFAF002049961423F31CDABAB1A70EB5 /* RxAlamofire-dummy.m */; }; + 321DECDF554D08A2FFB5B9FCC8FC6C22 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = D50184859B7E7B2FCD142F2D0FF83501 /* Error.swift */; }; + 327569362E4604E125071D7CB6919726 /* BehaviorRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = BADC91F4D42F59A8002D134BBD2701F9 /* BehaviorRelay.swift */; }; + 335DA9729DDCC2A2E86C484605B39A36 /* Date+Dispatch.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA92A72939FDF2DAAE299309646D27DF /* Date+Dispatch.swift */; }; + 34382B9F5C051B5F2A3E521C4CD421BF /* Completable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E4DC2EDF14DC98C9F492BF09D0C6F43 /* Completable.swift */; }; + 34990DB4BE282AA7BEC367B2A21DBD20 /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98B577F905A0DA8FFFBBC48596B8D5FE /* AsyncSubject.swift */; }; + 34AD4108D936C4D7FEAE17C66067A6E4 /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E2F5D5BC86EFAFEFE5DC81DA9185589 /* Timer.swift */; }; + 364FBFE2AFBDA63FFC062E7A329D00E1 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D883AB68A43C2C17FDA723730E4EFE1 /* PriorityQueue.swift */; }; + 36C78069A72BECAEB66B31FF794A09ED /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6C67A01F1DC5F2579165A141A0F18CB /* Request.swift */; }; + 371CD58570B89DE6A3090CC6CE16AEE7 /* UIControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E1C9087459E2A949E79028C67877E46 /* UIControl+Rx.swift */; }; + 377229136C0061FE2FABE71862C2070F /* ItemEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 693D5828BB933F59E948083F7EAF0754 /* ItemEvents.swift */; }; + 3A379670D0CFBC0FCC9D0F66E944D074 /* RxTextStorageDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D732BA10187D09CADE70C3677839C01 /* RxTextStorageDelegateProxy.swift */; }; + 3B901DF82C6576019330391D0F470B31 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */; }; + 3C0A2E4A387C34B462746390C6D61EE6 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11A6FDC99A0C74007C61727E532845B5 /* Optional.swift */; }; + 3D367323A56C61E6B7F8D37265E2A08E /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F35C9AC9D3F988492AAD9272FA8C5769 /* SchedulerServices+Emulation.swift */; }; + 3D88F3F5D413F6F8ED92C21BC2B16D68 /* SwitchIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 287D872BA20DCC059B3FDE9891FD1566 /* SwitchIfEmpty.swift */; }; + 3DAFEDCDC5094007E329D71FE84FF704 /* SnapKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9195910E446A0D67F0E1C2D10308382C /* SnapKit-dummy.m */; }; + 3EE7A29FCEE9B2A257B977E7137BC44C /* UITabBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C29A6CB0B11367EB927BDE743C42AAE /* UITabBar+Rx.swift */; }; + 3EFE8454C7301C05A00EC9870F47968B /* RxTableViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 127E27FD04D13F2FFD7E2365153EB850 /* RxTableViewDataSourceType.swift */; }; + 3F9271B2430E8B7F6F0F9507C5C22A6C /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 187E85CC75BB26EA4718340FCF30FBF1 /* RecursiveScheduler.swift */; }; + 3FFF0A40BDF7932C8CEBA6589210E980 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D57C9E5D77F803BC1396D2443A0EC94E /* NopDisposable.swift */; }; + 40E608508D38BE4E5A94993C39E0C64E /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F10AEB2ECC626E8F02B4E5A0D25E513 /* PublishSubject.swift */; }; + 418FC5C699A40AC43367B53199BAAB3E /* Infallible+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B8D5B36960DB2BC65E8FBF03EE16489 /* Infallible+Zip+arity.swift */; }; + 419A11A8F7797E02FA5AAC6D8B4B3C2F /* UIStepper+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99E955E7BAAB58DBCD9038D19F4B5AD3 /* UIStepper+Rx.swift */; }; + 42344E73EA15C26857ACC338F3513C3D /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE15C650A3A7D5EE93DE5F1B93B631FF /* SkipWhile.swift */; }; + 4251CDB971A8B94270E34381974BC9F8 /* _RXKVOObserver.h in Headers */ = {isa = PBXBuildFile; fileRef = 15BF47FD9953789FB51066C568FAC41B /* _RXKVOObserver.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 426C76C68C9FA3582F26BBB9E96316E4 /* _RX.m in Sources */ = {isa = PBXBuildFile; fileRef = 0D015391A1C86DCE1D900FDF55440501 /* _RX.m */; }; + 4337931D8B8E3F3BA03C77C1B496BEAD /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2117299940DBD9DE65E632C927B27BA2 /* HTTPMethod.swift */; }; + 45F6BA1117D64D98B32E0C77670EF906 /* RxCocoaRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = BCADE0A5DD41C1CFA84326E28BA08D0C /* RxCocoaRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 47D3FBF90386DABCAB70AA2CA176C8EB /* ControlEvent+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70B74220AE4F38E25CB0A28B625E2372 /* ControlEvent+Driver.swift */; }; + 47DF5E4B96F64623A02142740B54D05E /* ObservableType+PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8069A7DFF4B219ADA4811114C23D11D3 /* ObservableType+PrimitiveSequence.swift */; }; + 4877B1401025AA36C5A2F291B02809AC /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = E13A6F27F214D661B9C164F1CCCF44EF /* Zip.swift */; }; + 487963200BA2F42138606F20D447A24D /* Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB89EF4D9559D8D6C4CDB06E28D07A55 /* Infallible.swift */; }; + 4A6FE838AC054F308C1EC5A8ED403008 /* Pods-ChatBot-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0700B3295EFF8C509D89B5A64B4152F3 /* Pods-ChatBot-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4BE8D888F62311C302D0E3F3E38FA0FE /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = F081D86BE1B4AE213A4230C5E17511CC /* DispatchQueue+Extensions.swift */; }; + 4C51FF134747DF641E742FF87C68D82D /* Bag+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = B98456D107AAC8F527122AD29B590FDF /* Bag+Rx.swift */; }; + 4C55A60758D0C53AD5052463C9333227 /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89A39F4590E1023B896352835A3A02C1 /* ObserveOn.swift */; }; + 4DEA4F5E8F6DA1DDA399B1BA9570D356 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = B33EE3BFA18047A99158FD5A117AECAB /* Filter.swift */; }; + 4E0D848AC4FB40F7581A16576380E435 /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0395BB4AE5E323E8FA71EC99861881EB /* RecursiveLock.swift */; }; + 4E2A394AB9272D80EFC57512D1326B58 /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = C793E0D03758DB7853AE24B522404141 /* Catch.swift */; }; + 4F2BD19DADB87C8174B6D1FB40B17537 /* Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9744F3AFEABC868B5FEC030B3F516431 /* Single.swift */; }; + 4F315C18FC854325DD5D062DD7A363D5 /* ObservableConvertibleType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB4645A6E0537F17A5B8C5893424C888 /* ObservableConvertibleType+SharedSequence.swift */; }; + 4F4B9DFA352D9958C7494D7BC24631D8 /* Alamofire-Alamofire in Resources */ = {isa = PBXBuildFile; fileRef = 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */; }; + 5075DC82A63A9807DFC390B4CE8046CD /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89082F8D1E4CD49B61ADB867DD87D2E9 /* Session.swift */; }; + 50E4E24710A4C5A77BE6594A10DFE773 /* ConstraintMultiplierTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A8884BCDC6691051F7F78C5B82BBDBF /* ConstraintMultiplierTarget.swift */; }; + 5230B70A7B448918B83D3B983533D29A /* KVORepresentable+CoreGraphics.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6453BF98D49C0179F6FB62D15AB8577 /* KVORepresentable+CoreGraphics.swift */; }; + 542616E3D85E7777022D0AEF9FF6E377 /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 068488A1E3F95BF0A3399FE55E490D6B /* TailRecursiveSink.swift */; }; + 5435E924E7CE7B05B7F650C078A12F5B /* UITabBarController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEEA3119C2BCD2D17617CA0D51444126 /* UITabBarController+Rx.swift */; }; + 543824E1170EF49570C40DAE54604F21 /* _RXDelegateProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F1FADAD5E198D7CC5DCC5C8AD271E48 /* _RXDelegateProxy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 55713DE36F28B0D078ADAD60D5EE7FF4 /* ObservableConvertibleType+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = C913AE49B5DF5454F9459CB36E6CA8EB /* ObservableConvertibleType+Driver.swift */; }; + 557AE7547352CEA86AEE5518CC1A503E /* RxCocoa-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 1D6AF93AED3381C5C6CAB28DA53C2F76 /* RxCocoa-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 567E2B1BAE575E6556A2E57191BA2DA7 /* DelegateProxyType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C2E5505F6F6A3594BDBB66B1DCD2769 /* DelegateProxyType.swift */; }; + 56CD198002D3D45274F6719725B983CF /* ConstraintOffsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F334446FFE4A761CC9A75558CE34C48 /* ConstraintOffsetTarget.swift */; }; + 571142A2747CD90165F631A8AE980A0A /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A011A770240CFFC6D8C74720E1157413 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5830C6260CA2B7CD6DC74054FB29CDD1 /* DownloadRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82D156943C2BE51941A597CAB1A7058F /* DownloadRequest.swift */; }; + 58BBB00C541E40923CEA876909C4EDA7 /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7A240C434861DE54869DA90A5E98CAE /* SynchronizedOnType.swift */; }; + 58E936B1E7E42C0BFC119D428B70F1D8 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DCB0CDBC1CB97F3EF3EECDC0FF6896D /* Alamofire.swift */; }; + 5A39F3F258372FA025F08ECAFFFCF71D /* NSTextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AE4C07C0E4F8BB1308A67E29DEDB0F4 /* NSTextField+Rx.swift */; }; + 5A3DE5038C0E8C2BAFC3316589D0F918 /* NotificationCenter+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4D9A55B60B97A971CA56B8A6B8E61B5 /* NotificationCenter+Rx.swift */; }; + 5AD4E5B4118A1DC7D639F611044B4159 /* DataRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17E11CC2C615ADE1CDCDC3F1B78972E6 /* DataRequest.swift */; }; + 5C2AA24533F5C397A3140A0F0764DBC8 /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = C530A5336F0A017F2BD09AA4B88BCEB5 /* InvocableScheduledItem.swift */; }; + 5E3BF2B719B3A034C173D16B3ABF682E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + 5EB5C933162B0C6CA9EA70D9B41FF7C2 /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A231BA2298FF45B24675E00AA527578 /* DisposeBag.swift */; }; + 608DC0C8110DDFF5D8E5A43BB48A6A86 /* UISlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ACEED6A92C605A5B1876A7C7D739E7F /* UISlider+Rx.swift */; }; + 612AE0ABB9BCD3AF0E1D29B4C063CA62 /* StringEncoding+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58B14921D76D7D8FED822C02FF79B1F7 /* StringEncoding+Alamofire.swift */; }; + 61EB40AB5F1BB5E6FDC8C5CDE06C3DE9 /* RxPickerViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6554D2462B773751507D2561D0429059 /* RxPickerViewDataSourceType.swift */; }; + 61FE62E6814C05CE7F0A45A2AC924A51 /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = 896F73650AF4D2EB4B79C55847CC0198 /* Amb.swift */; }; + 6298EBC46156D790A40C5D525D8BCCF3 /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82EF1A5DB3E52E9027C29A9138C74835 /* Debug.swift */; }; + 6431218578A566C5EBF5FD166F164059 /* ConstraintMakerExtendable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C23BE9C5A3B2DC55606551EA6D075F2D /* ConstraintMakerExtendable.swift */; }; + 654D9C29A846E7ED4DD5BF0BFC8D64B8 /* UISwitch+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16669C5C88E94E1D44FD7DC175608B70 /* UISwitch+Rx.swift */; }; + 660E73ECB1E50185B9D21BAA127DC3A0 /* UIRefreshControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = E08CBB4AA59577D9B90F839FADB5B1B1 /* UIRefreshControl+Rx.swift */; }; + 66B4B08C5A78D74C5B0651F09C499BEC /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 026C02E8CE81519DBD52B3123FA8E7E6 /* Timeout.swift */; }; + 66F0BABA2924611DCE03722DD8C70691 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 171AD31BA80C89E3807389F00BEA8E63 /* PrivacyInfo.xcprivacy */; }; + 68127CAEDD4B253D26A3755302864FFE /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF6DA301B5D12B9ECBE093FB99BF3A1E /* SingleAssignmentDisposable.swift */; }; + 68238227D42B2511FA6A26BF71E92520 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7D9344310635F8BA17A842C89B58FB11 /* Alamofire-dummy.m */; }; + 68995B28EE5B539CEA5A1133E4623927 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAD9C633108582A231FE0655F51AE6F9 /* MultipartFormData.swift */; }; + 68A74F13F8FEBAA7E0EA9344DED0458B /* OperationQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF29834581204BB9C286730AFE098802 /* OperationQueue+Alamofire.swift */; }; + 68EFE2D24105AF72F6FB89F7C517D563 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 23378430FBA0F2A76F6D502BD6EB0BE8 /* PrivacyInfo.xcprivacy */; }; + 69261B5D3B53EBF7109D5E1DA3768CAC /* AuthenticationInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C2E5E9E33DDA1D3861DF17AF42F587 /* AuthenticationInterceptor.swift */; }; + 6927E0A61FCF762B43C75325110C3D77 /* Infallible+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40281A10694C95424518F246D0F1B9E3 /* Infallible+Bind.swift */; }; + 69657DEC11BB7E4F9F5B6DE8E1148B3E /* _RXObjCRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = 12CCC5D2BC32920261F210B0BF386F79 /* _RXObjCRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 69745C24634579C0CB191EA54894DE63 /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D9DF43A06E832A65244893A1DA6755A /* CompositeDisposable.swift */; }; + 6AECF90899DF432E8E89F101340111C6 /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60F6B26402A36D05D138482EDB18AB34 /* VirtualTimeScheduler.swift */; }; + 6BDA2BC21E394076C2E58E9269F4AABD /* SchedulerType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D2E5604E8A78A3AE6B8C2C88A765F06 /* SchedulerType+SharedSequence.swift */; }; + 6CC7E7C00730B1BF42A28B2E23CA01D6 /* URLSessionConfiguration+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = B12A085B5C37FE16D2A829B6816C93A4 /* URLSessionConfiguration+Alamofire.swift */; }; + 6D389E4D5F97798BE1AEEB8C317852D7 /* SnapKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 994826F0C4A5067DB8BF11B0BA848B8C /* SnapKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6DB19BEE9C42CBE8101A114524B38CE7 /* NSView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9B8857FCB950426B60F8110D84C1AC4 /* NSView+Rx.swift */; }; + 6DFB5C921332D5E14BF251A5ADA46473 /* RxNavigationControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAAB78B8DEFFFA4EE62B77E879B0C0C6 /* RxNavigationControllerDelegateProxy.swift */; }; + 6E2884B29CD49EE91C48C725105F295A /* LayoutConstraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = B924D032B5D54E217EEA5D0B35C8E119 /* LayoutConstraint.swift */; }; + 6F2E0DC7D8598283D088A989FDB8E5F6 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26819537DAF4920F3DE8BEB827D735A7 /* ParameterEncoding.swift */; }; + 6F803B4767FE50C12E3F0402DC0A3BE5 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = D592E632CF9AA82F2DDE3C8C185C7D6B /* PriorityQueue.swift */; }; + 7052944C657F270E47777446D0E10E1C /* ConstraintInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CA3DF40C7E6460D49F6E4F2CDFE599F /* ConstraintInsetTarget.swift */; }; + 72C19C762FADC82517C344E9F47D7E50 /* AlamofireExtended.swift in Sources */ = {isa = PBXBuildFile; fileRef = 366F04E49BB35F3ACC09667286ED9BDB /* AlamofireExtended.swift */; }; + 72E9834B8E1B3A3443B665C3D5244474 /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FE241258B132522FA585541CFAF35D6 /* Queue.swift */; }; + 72EE3F69E6154EF5C5524DE4F4EE0B5C /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAC809D021BADB863C6366F88736744E /* Queue.swift */; }; + 72FCE0D3F5EA7EB908C108DFD468B267 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8748D0DB8153052544C8742B25C8619D /* RxCollectionViewDataSourcePrefetchingProxy.swift */; }; + 7383111A52ACF20DC2BFDFA8FF1CD245 /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D964EEE828D2550E4147E863C869CBF /* Disposables.swift */; }; + 73F8AC99A58E5837924C056E89543B97 /* Typealiases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38D856B4C6C703EDEBE7F4A2DD975718 /* Typealiases.swift */; }; + 74E16C2EF9859BD51382E278FA2CA5C7 /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EE3D362AFB2DDFEE36E454BB2B4CCE4 /* AnonymousDisposable.swift */; }; + 7572216542D51908ECCB3B1AFF53B758 /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = B070E8A56551165C933D48C2D56D1A93 /* TakeLast.swift */; }; + 768A33DCEB41CBC5C7ECF5F0220B1A97 /* SharedSequence+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95B6C010BFBF729113881E2867C2A4DE /* SharedSequence+Concurrency.swift */; }; + 77409BB479A1C736C8614F9759218F85 /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52D9BC489E37B4988D0B1FBF2A7FF7FE /* SubscriptionDisposable.swift */; }; + 77CB99B19125DE660198CCF7E7FB3C7B /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = F14D3772A585D66A164FAAA5400B93C2 /* Observable+Bind.swift */; }; + 77D782DE125D322922466676E2FFA289 /* ConstraintPriorityTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EB0DCE44FD0616E133E3C72DA1C5A34 /* ConstraintPriorityTarget.swift */; }; + 782082D9F5529E63F249E8811BA6FD10 /* RxPickerViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24583429FDC6518EBA768A112CAACD99 /* RxPickerViewDataSourceProxy.swift */; }; + 792B9812F1A39EECA4834C5036081DBA /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24F1AE4D88714B12AF62EC96947C5E0C /* Just.swift */; }; + 794FC38D15336AB502B73B012005E9BD /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F71ECD032FB1811FA8D4AF1F399795DD /* Validation.swift */; }; + 795681285B4E2B121B5CD420131168F8 /* MultipartUpload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DDD33F99EB662F0680B72FD8C3703DB /* MultipartUpload.swift */; }; + 79FD300B87DA0ECE0491CAD22FB82C89 /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8DC8A713001D7BBFFCC38A262D3280C /* Sink.swift */; }; + 7AE2E0B382A14D58BE7DAA0C852DCD02 /* ServerTrustEvaluation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 837560DFCE36E39309E60ACBC7D8310F /* ServerTrustEvaluation.swift */; }; + 7AED511539D268220A6E16660639CDC4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + 7B3D680ED2CDD36A46922B03C0031676 /* Infallible+Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76A4001BFC51862CFE3D5E4EDAC0CAA7 /* Infallible+Create.swift */; }; + 7B6F19F234DC858A8E1196F64D1C9A32 /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E8F346691EC094F615279F3FF4FDE02 /* Event.swift */; }; + 7BA5D9B38DAEDD6A5166ECF2A498D194 /* RxCollectionViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA2BAD104F63EA5D8CF3DF2BFBB5B852 /* RxCollectionViewDataSourceType.swift */; }; + 7C9C0D2AB5BB6670928CC95B4DA46814 /* RxSearchBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = D92259428C053D17FB1662BE8F4C5AB0 /* RxSearchBarDelegateProxy.swift */; }; + 7CF8F7E1130D35E43F09D4D9995E016E /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB37A5874127201ED9091268DDC59E33 /* ScheduledItemType.swift */; }; + 7D90BC34596D47F2A6B2C284CAC4A61F /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EA0F02CDB0C6FCF2EAD47134DEF182C /* SubscribeOn.swift */; }; + 7EE83FB2B30B2D7B4907C0E0EFC0D08D /* Dematerialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07358E96DEF41D60D0B8AFE3003DA996 /* Dematerialize.swift */; }; + 7EFCB3392E3997F1F6479F2F01053281 /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0FD2684DAE63430FC2CE7152FD687BB /* Rx.swift */; }; + 7F0A5844D1DD4C225D7914AB49F4764C /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 157BBE9A61CA66643BC96A13F65E5448 /* HistoricalScheduler.swift */; }; + 7F5E49425D331C697D57E60DA02B8871 /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7077E8FC7907912CDAB548B19E229403 /* Cancelable.swift */; }; + 80213844BD1825B4F74CA12206958A48 /* ObservableType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 549CF5ED2A2E832777BBDDC43E594896 /* ObservableType+Extensions.swift */; }; + 80594A8E265328F6320F5C3AA6375477 /* WithUnretained.swift in Sources */ = {isa = PBXBuildFile; fileRef = F65E9E56914D2BF791EDE0C25C959805 /* WithUnretained.swift */; }; + 81148E8E0935476F92B10881A023D0DC /* ControlTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03CAC0BE6778E17AEE82829B73CFE34F /* ControlTarget.swift */; }; + 8196BA923F2CD32C92584D499B9BF86A /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D2330DB818D1AD381E696FC28AB475F /* Reduce.swift */; }; + 82126B5F4739FAE8AB2D606924777273 /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D06B8A1F0B29460B3E3F01A7C318EFE /* DelaySubscription.swift */; }; + 837AEFE0DB5EF57DB35C9C6E29BBF7EE /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F10AE20C1D469556BADF31DAAE1D900 /* HistoricalSchedulerTimeConverter.swift */; }; + 83F203FD35D282C29A03F28DA563C5D8 /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = B27B198BB3480203B55645C028400B99 /* SubjectType.swift */; }; + 84AEE29F4E7DDA962C49D6FAC6044EBC /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51710E6F5CDA4441327AE37E1D64A62D /* RxCocoaObjCRuntimeError+Extensions.swift */; }; + 84BEB9E439780B1E0DEF56459E3D3352 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + 852911F432575BD76E0EB72D4E696748 /* Observable+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9992B8D05DD99854D51E1DFAD535B4FF /* Observable+Concurrency.swift */; }; + 8640829049AE9907FE93825E5510C33D /* ConstraintMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F1E179320E97CEA94AB0BF098C8A150 /* ConstraintMaker.swift */; }; + 87996D11DC92EE19EAF9305DAEA4ACF2 /* ConstraintMakerPrioritizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAD4894D57791CCD7B1178232EDBB2FA /* ConstraintMakerPrioritizable.swift */; }; + 8868BA37E3CE7C58D26123806D543F3F /* ConstraintView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B67C30AE79B9114C47A26A2610553526 /* ConstraintView.swift */; }; + 887DB52C63E52FBD3B88F42DD8CFB421 /* RequestCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11B76877E7B02FE48A3692B3F0A370F1 /* RequestCompression.swift */; }; + 891D1BF14C8881C74262EE9DBE5D67A9 /* UILayoutSupport+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E7710C5413799170315818DA4E26E9B /* UILayoutSupport+Extensions.swift */; }; + 8A8AD24A8CE75FBE807EB5A9FC11E62A /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29B85E2CA3EF2226C302B57291E39AB /* Bag.swift */; }; + 8AEE5B74A5BAC274D6589F229D867768 /* UITableView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22F0E7B9E39A41E1992AB24925CDA083 /* UITableView+Rx.swift */; }; + 8B8B57F35F62B111B5B3FB282895AFCF /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 555021F007D69AA5D232C2CD69443EA4 /* DistinctUntilChanged.swift */; }; + 8DD46EE7FB9503E7634E929DDE1CBA31 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26771536FF580C386E574A2B02751833 /* Notifications.swift */; }; + 8E482ACFEE214E8473C95E359DEFD756 /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93FA24BD28C89D77F31B4C8729895EE0 /* Producer.swift */; }; + 9043DDBC3FF077FA99A6B84ED37FF5B3 /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = C62983CB803ED24DE720CAC5F8A2A145 /* AddRef.swift */; }; + 90585B3B5526DB8ECBD1AB8EF2C4D5A2 /* UISegmentedControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5193DE9E3B442CA0110473C426592C5 /* UISegmentedControl+Rx.swift */; }; + 906EF891E58A035281766993F82373E3 /* ConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 155951FD9ECB1880E00F8DDBF5772131 /* ConstraintItem.swift */; }; + 90D847B19214926EDE5210D44A08F3C7 /* RequestTaskMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54B87B26D0094409A4830F56BD3B51F6 /* RequestTaskMap.swift */; }; + 91CE3762DAC54C69D81002DC4E844E32 /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C449B8EEBBCE87868B17B7C5EE4EC28 /* Empty.swift */; }; + 91D1A6B6C16D21E2FD1BFBA9F8785A7A /* Pods-ChatBot-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7D60C3ECF2A7BA805DD9112C64977C46 /* Pods-ChatBot-dummy.m */; }; + 92138A77DFEB4F76FCB582E97633896D /* URLRequest+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A7A585318011652676222B16198D0EA /* URLRequest+Alamofire.swift */; }; + 922AC6AF7A90CC9BF44AEF51A4938D95 /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC66BBEA2109E95F813B2386F89B2421 /* Bag.swift */; }; + 9378157945D7B405C862A05B0D6B971B /* Result+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6C721E38859015E49325A6D611B1474 /* Result+Alamofire.swift */; }; + 938CFF5F6DE6E7E8CE94373E51F3E07A /* ConstraintLayoutGuide+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 022BDA7BA5349EFBEB9329EEA40E85A7 /* ConstraintLayoutGuide+Extensions.swift */; }; + 950B809760A8CE4375DCE1016FB9859F /* ConstraintMakerRelatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47D78FC4251E65A4B297FCA01575EE27 /* ConstraintMakerRelatable.swift */; }; + 9569C9DA81619ACD1ADAE3EECE246C3E /* First.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3343B5BBE4004D26874C5F274DB6C119 /* First.swift */; }; + 957CD2F9CEC64BC57FA35D672AD44FF8 /* PublishRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F55EB8DF2BC73493BDA426C5D5FBB38 /* PublishRelay.swift */; }; + 961B5042F0BFBD2C5FCDCCF40E2EA7CD /* UIButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D96B4C2B995A47D34B2F206E566FAA48 /* UIButton+Rx.swift */; }; + 96F9E4762C05BF7B009FA52FC18C18C5 /* NSObject+Rx+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADEE96E8C029C202DA706F1269584A45 /* NSObject+Rx+RawRepresentable.swift */; }; + 9779D52AD8CDA703D6EEE1C6D38E019F /* ConstraintAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = D47B73D1968879B897EFCC72DC84ACE6 /* ConstraintAttributes.swift */; }; + 97D7D91FC818805D8344C373CC098C32 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2842A835037EED44792264951C5EF03 /* SessionDelegate.swift */; }; + 986248DC617E2B972C64E15ABB23C737 /* Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DEF302201F515462E0B3D7AD6BD2208 /* Create.swift */; }; + 98E92B6037FB3E656FC53323547FC07E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + 9984D50CE2B652B71A147BAE98FAFCF8 /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DCBA6200BAAA6515261FA9034D87491 /* Skip.swift */; }; + 9A151985A3D24023E8B2996BF3EBA2BB /* RxCocoa.h in Headers */ = {isa = PBXBuildFile; fileRef = 9D43AE76EB42DD34137D60B072365019 /* RxCocoa.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9A92CFEF51236FA54EB5604F1AC4D2B3 /* ShareReplayScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = B96D597D387E7288923EE8C66B59C328 /* ShareReplayScope.swift */; }; + 9ADE1DD7C6AD8B57FD158350A66EF8D0 /* SharedSequence+Operators+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560DCBC2941D96B8B2EB9C2A2728D79B /* SharedSequence+Operators+arity.swift */; }; + 9BA0BE27FCCABBBEABE945BAB46EFB7E /* Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC148DD3BD6D5B3B9DA8CE61B451C3A5 /* Delay.swift */; }; + 9C7D314BE45AB79E96B260656C36BAEC /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 903786903B96AF67D7A9F33F39784FD8 /* RedirectHandler.swift */; }; + 9D8BED7F3F86BB39E7C0923D92E73F8B /* Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86FA9D7D2797406E2B96DFA5433F6DC0 /* Combine.swift */; }; + 9E8BA4FB802EDCD492DAF618CA7BFCE8 /* SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = D45D06B40D5FB020BB5498EDE9146C96 /* SharedSequence.swift */; }; + 9F370B3928A333AD7E41680A29B1F051 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6EB5CB57ECB22669866D6AF3FAE88655 /* RxCollectionViewReactiveArrayDataSource.swift */; }; + 9FF1035938822A5C24626E11825B7BA9 /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1FB810038811058EBE7EFDE05AF5B4E /* Scan.swift */; }; + A0208B623442A26CB9157F193CBB4A7F /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6536D1A3AA8A85023DC9EB6423385510 /* Platform.Linux.swift */; }; + A0371DF7D93D9B86BD50474D4B9294FD /* ConstraintInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5B5F214EE60E508D3B0518968BA0356 /* ConstraintInsets.swift */; }; + A051999781E1280746F7743BDEEA6C49 /* ConstraintDescription.swift in Sources */ = {isa = PBXBuildFile; fileRef = F24C61086DB2D41E0DF3945457E23C55 /* ConstraintDescription.swift */; }; + A1506893FF52AA466B130E8B05FBE868 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2259138BEDFCE536D81C60D9D8647DED /* NetworkReachabilityManager.swift */; }; + A1F1776D3749EE20F8EB31B5E5487637 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3AAC8A11121C5761C45996057A91DA7 /* Utils.swift */; }; + A20321979D272B922CD60B531BD05F7F /* UIPickerView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D80F36289073915F26ABAEA35BD714C /* UIPickerView+Rx.swift */; }; + A214A653E430C9079AA7B1090169262D /* UICollectionView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEFC74A4645C52AF239D907E90151564 /* UICollectionView+Rx.swift */; }; + A22A2ACF53FDC243AAAFB009005A710F /* Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF53BD35610DA8DDEB1ADB7A43CF5CCC /* Concurrency.swift */; }; + A35877DE0C3D6B4CF2A10E666EF5F490 /* LayoutConstraintItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B0753BA67BAB44F48140522DDD0AE2F /* LayoutConstraintItem.swift */; }; + A3FD52DF5584364FFD56965394C36CF2 /* URLConvertible+URLRequestConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 973A568267D079EB1AE5A7C115C76219 /* URLConvertible+URLRequestConvertible.swift */; }; + A4BA514E9F3A3ED20E3BF8ECE83A0DA1 /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75C7AABB4BCBC0251A8595E62687915A /* Deferred.swift */; }; + A5B4E3C7D3A6182FA7C41B3E87921DEF /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = C70DE0C182608023CED8EE3975A99DC0 /* SkipUntil.swift */; }; + A6D42E6DD51B7F0AB95F5AF0BE74061B /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A9C24B3F6BCE4CFFC79D6D04A8CA4BD8 /* RxSwift-dummy.m */; }; + A72C92BAD53CAC6C4509E66A4A963164 /* Debounce.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBF192D9799B34F2F85E30E9984C0C31 /* Debounce.swift */; }; + A768976F84C9BBF5391E70284550A251 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBA5035607E0250F9BBE850962674564 /* Map.swift */; }; + A892A3F92A4B151AD508CFCD080082A4 /* Then-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 5FF06DB04BE117F1E668EC5B610784BF /* Then-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A8A43FF9F100533C09FEF2BEC0F12BDA /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59C926A7CDCEECF7351850331FA6041D /* Sequence.swift */; }; + A93FC5BCB5B02182D27377A3724A60B1 /* RxSearchControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60D8162FD7345FD61DA97E075041A37B /* RxSearchControllerDelegateProxy.swift */; }; + A96859B67A721D5D6FBE1743278074F9 /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2440B278D21A210A9CA8F5F7A3386025 /* Switch.swift */; }; + A9CFC858DF241092F03917C50BB86C16 /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73F393C2D8D48019237DF4FE1B6B73F2 /* StartWith.swift */; }; + AA602A49B1DC7FDED565CAD8BB89EAC1 /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85E08654D83236E0605DB188B12DF8D8 /* AFError.swift */; }; + AAA7A11591D6E4B06124708291C37698 /* RxTabBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEC2726887ABD33AFCEFD85345582ACB /* RxTabBarDelegateProxy.swift */; }; + AB88D7A71BA82D3BAF097C992BFB221B /* UISearchController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E5190BBD5788742C6338758F6BE977A /* UISearchController+Rx.swift */; }; + ACA3DBC73A19F3CDF9C4FAB09988D0E6 /* RxScrollViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 859FFBDE9607E4C6AB22EFD8E96505A5 /* RxScrollViewDelegateProxy.swift */; }; + AD80EA9EFE70F246ED0FDF92EC90AD0F /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55062A93A34B74A387A9688645A20D58 /* ObserverBase.swift */; }; + ADF998E6E827C3D8774DD20BF0929C02 /* RxAlamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC95EA39E18B08E75EA4D0FF6728BAB5 /* RxAlamofire.swift */; }; + AE2614A1E163FFE957DFA5F87B284570 /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5B5C55A7858F6D27FE4FFF3DBC68E0B /* WithLatestFrom.swift */; }; + B00B8088EB50EA3F0F875993C675F421 /* UITextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDD59AB6E70B0DC2C150D58C0919F3A9 /* UITextField+Rx.swift */; }; + B0A8DE991100FB6054B886A847E78B7E /* Materialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D9B04EA37A48BBAE3DA14E4801DD485 /* Materialize.swift */; }; + B133BB9C9B03481C7F1D221F35A617F2 /* Constraint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 515F487FB3AAFFA95C98079E7CF98806 /* Constraint.swift */; }; + B1E2EE6C3296A1B2E79440800D431B8D /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCA11FA51DBB607BC021DDD68D7290F2 /* ImmediateSchedulerType.swift */; }; + B3167FEDC691D1DDF267F855CFF33636 /* DelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64B8AAF028420A2370690C9C868E9514 /* DelegateProxy.swift */; }; + B3F14F1B196B5858BD951366FA89FA6D /* RxWKNavigationDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0685B997231AAB114364A3E6B1FD607 /* RxWKNavigationDelegateProxy.swift */; }; + B3F75D115D5150C258F5E68404751010 /* ConstraintConstantTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5A209EE9411D05FC10172B94E7B984A /* ConstraintConstantTarget.swift */; }; + B4F9C9EC1B3F1689AE56BB719AE5439C /* ConstraintDirectionalInsetTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82C59C0A4CF1CC40F60AFD98B7B2FEA9 /* ConstraintDirectionalInsetTarget.swift */; }; + B59095D5EF330419B3ADFBAD7EBC2B1F /* NSButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F52E08AC945B9B081C5AECB2D4570D3 /* NSButton+Rx.swift */; }; + B5ACECCDD52AF69EBA2E11666BBAEB42 /* RxCollectionViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FF2B70AFEA833EA39A3F259BAFC3B0D /* RxCollectionViewDataSourceProxy.swift */; }; + B5C66B48EB624FEC4D2F64A50F143716 /* DataStreamRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = C31AF98ADA4531DCCCD5C8CFD6F7B304 /* DataStreamRequest.swift */; }; + B5CBB0B8314FB5E8CE1D0AF133CB4BC2 /* AsMaybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAE64EECD8849FB0FB04ADB2D28964CF /* AsMaybe.swift */; }; + B60181315C9F329E45A079B377960BBB /* PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A09382CD3E7BD02B20B236979C9EADB /* PrimitiveSequence.swift */; }; + B616C8E5078265366CA95C9444362299 /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4C1CAED9B312C0017A9D1B4ED53BD59 /* AnonymousObserver.swift */; }; + B6343A462D953EC3A9C7A7624C2E77E0 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34F46AFCC949DA69E26A2EBEAD1CD992 /* Errors.swift */; }; + B71010996CEFF96476C9B95FCD9B0B78 /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2974CD805B71D9119CCD669B17B0438D /* SingleAsync.swift */; }; + B79C23BFEADABBEF33F16E7A7A442D7F /* Zip+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 025E3D37026435B0D9CEB7B8A3A67F95 /* Zip+Collection.swift */; }; + B7EC9CAD1C5FACDB56DCDCBAB98F6D74 /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5805F7F760294D2321395AB23D42525 /* Multicast.swift */; }; + B8A4F17E7667C0565DC91A856E57AC04 /* ObservableConvertibleType+Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EDECA2A62722B870D23D09F0F0ECBEF /* ObservableConvertibleType+Infallible.swift */; }; + BA5658B6C27A81FA4665E507A1ED88DA /* Driver+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 822E3D722F17EB3AF1D5F0AEC7E5CADF /* Driver+Subscription.swift */; }; + BAD3834746DAB3C038417D16101B29A2 /* NSControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15F42CF91B11E49FD5E0A9C5D71E3D1E /* NSControl+Rx.swift */; }; + BB72FC9215BD907A82AE928782813D6C /* NSObject+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48E1C71FAD56AC66CA256D8B5D952C16 /* NSObject+Rx.swift */; }; + BBD437FE6BFF63452E6B7E08DFAB4DD9 /* UIBarButtonItem+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06F1307E057BB52BBE74D77F011C13AE /* UIBarButtonItem+Rx.swift */; }; + BC0A0C473B63B817926F4D58611281BB /* URLEncodedFormEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3752B5340A880B4107093D0C1A2EF50B /* URLEncodedFormEncoder.swift */; }; + BE355F69F84788D334FDAC7D1CD9B8C4 /* ConstraintDirectionalInsets.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4E41B3F95C8C68CDA816C5625843760 /* ConstraintDirectionalInsets.swift */; }; + BF567AEFDD52DC43AC75122734D571E2 /* ConstraintMakerFinalizable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A3AD3EE0EEF6835B65809B55230CE0 /* ConstraintMakerFinalizable.swift */; }; + BF860092BECACCD23B6F6420E5AE0BE0 /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB1F996427CD250487436CB2849D1CD4 /* Disposable.swift */; }; + C04DBE6AE13FC5CFD01D363A351EF76A /* ConstraintView+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = AABAC47B80C383925BE599657469267F /* ConstraintView+Extensions.swift */; }; + C05F81983EC39D0814DCE11AD9DF225B /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B4399861D55D60894AAEDEA32A28597 /* AnyObserver.swift */; }; + C07EDF0AA1783AF71B9AD7D6E4358F00 /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77D427FA7E345AFB7C19F288B79159A9 /* Take.swift */; }; + C0F89544C3BF7A670B44ED8A4F4F67B2 /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF83526A1A4E8DE771306E1B676F2D8D /* Do.swift */; }; + C12DCA02D36C5C6167F566AFC96A6057 /* _RXObjCRuntime.m in Sources */ = {isa = PBXBuildFile; fileRef = 58C931C356BFBADA46D7D94A93E31F96 /* _RXObjCRuntime.m */; }; + C16CCA036FB752322954E1F6047D57C9 /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 648ABDA4F57CCFFCCA2E35A67A86EC81 /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C195C44670C83CC91E8BADB11545D0B3 /* ReplayRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB1066583F16C904E8CC5ECDBC6DD7F8 /* ReplayRelay.swift */; }; + C213B88476DC058A3D6F66FC48D2997A /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DA04DDAF4253AC1E15CF4F0211613FA /* SynchronizedDisposeType.swift */; }; + C2D4FEEAF01038DB5C31CA401C105476 /* _RXDelegateProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = CCB808C5F7B22550C5478F209F2BC2A0 /* _RXDelegateProxy.m */; }; + C378AC3DF57A41F6F16D01BBD7A1BB02 /* UIActivityIndicatorView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2CBF621C3C27D36361AA1E26D1F30EC /* UIActivityIndicatorView+Rx.swift */; }; + C39EFD5DC31C8D98E9ADB90EFB336C3B /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9A124024F0B360DAD35804DA6ADCCDC /* Platform.Linux.swift */; }; + C53EDBD3F6005B01E29A50BE765F50FD /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B0B37F547380C5FDA244EFB99AD02B1 /* BooleanDisposable.swift */; }; + C54D40885EB2E2F67914570C646D216D /* CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC09B2025A8B2ECE8AC4C2D1261A8757 /* CombineLatest+Collection.swift */; }; + C5A1A8CFFE40F903721BA7E4543C8EBA /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4430E98B15C737B4092B51994223EDBD /* CurrentThreadScheduler.swift */; }; + C5CD2F6F8BA07FF284ACBF0F4A2BEFBB /* DefaultIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F33A0C1E70FC803B717A82FF7B656FF /* DefaultIfEmpty.swift */; }; + C6A1AF1239CD2F0D4745BAA097E1E63F /* RxCollectionViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0E167C7E239F77C09B30A1B1BFD6A6A /* RxCollectionViewDelegateProxy.swift */; }; + C784A7AAD94DD830A9EB5ADDEE6DE1BB /* KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E49C4101B06D09B0670CAA5BE93F2101 /* KVORepresentable.swift */; }; + C79DDAB5198263195D078C8B01DF1FFE /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EA0FDECA39FD657BB93ADF34A70F258 /* LockOwnerType.swift */; }; + C7E343559158D03F717C616F79FAA006 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + C82125EACE158B19FA2CF0018BAFC0F4 /* Maybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 600F1EE1652AC362DF1F4A35FDE1D317 /* Maybe.swift */; }; + C8DA26AC8F4DEB0733EB64C8182A4C57 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + C96C853D60B6AC78AC076E1193BCB9B2 /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6E235EE582F96D0A9CBEDEFD5B50391 /* Concat.swift */; }; + CA72BC15AF30D94744BF51159C71553F /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AF99D2169C0DB0E0EBACC378A353BDE /* BinaryDisposable.swift */; }; + CB3ACAC0625702DEC5BBB5F9AC0CC737 /* RxTableViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF0655088DDF1DB2A8A3E4A1C172991E /* RxTableViewReactiveArrayDataSource.swift */; }; + CB944DCA1B4D8E929A4AC948A92B7303 /* RxAlamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E58FF48ED163CB55597E534C20E56B2 /* RxAlamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CBD71EAFFBA54C97123839A8EA5A9B85 /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9093FA572EC11FFFA9D8797CCF6163E /* SerialDispatchQueueScheduler.swift */; }; + CDCA01B605A086576DBB75F8C3A24337 /* RetryPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = E60059A145C699C90DE97ABE2451727D /* RetryPolicy.swift */; }; + CE08483A41A5535019BE5E198792480B /* KVORepresentable+Swift.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0E0D9AD1AEDD0834A8A02649DECA298 /* KVORepresentable+Swift.swift */; }; + CE52BD963045285270BE40A22D9D0CF2 /* Completable+AndThen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15CFA59DAC63CC23DF0513E8D31E78C9 /* Completable+AndThen.swift */; }; + CF32140300489AD5D6D5A74E4605FDAF /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 29B1B7B244B0253C248351A34368BD45 /* DispatchQueue+Extensions.swift */; }; + D02814A36ADDAFE6CC2B1EF4DCAD7FEC /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 34661D3B62FCC5B6CEBD9806B3A397D4 /* Repeat.swift */; }; + D04234BAA0FD845DB7F2BE5226BEBDC7 /* Enumerated.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD3C2A9316A45C1B52CDDC4C9B39AE33 /* Enumerated.swift */; }; + D091D9EA20CEB92609BF1E622E8CA348 /* SnapKit-SnapKit_Privacy in Resources */ = {isa = PBXBuildFile; fileRef = B9DCB5EC0B1CDADD221717CADDF62359 /* SnapKit-SnapKit_Privacy */; }; + D1D035C24CB13D5110CCA6C00A9E7812 /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFE1667CB2EE82F6909B686F19E568BE /* ObservableType.swift */; }; + D2004A03ADD62CD0C4649710F32A91F5 /* NSTextStorage+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBEB130BD704B0C5130C4F805B724932 /* NSTextStorage+Rx.swift */; }; + D2C293D847E95B01671EB3E6A32F11C7 /* WKWebView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D82E05E5FDF3DB13CC8C3F30B72A4691 /* WKWebView+Rx.swift */; }; + D32A0967B67610F1D80FFFD8FEC6E91C /* RxRelay-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = EADD0B8EA9DE297A536E739730E4FAEE /* RxRelay-dummy.m */; }; + D3AB490FA372E1922315D4F2E5709254 /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C3CED74C2352634FFCCBF22DD716882 /* InfiniteSequence.swift */; }; + D3BC528010D39EB2D79585A671FD80B6 /* UIScrollView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DB527180CF7411F64A3ADCAEB4C3840 /* UIScrollView+Rx.swift */; }; + D47B1058991EEC007A109B8E354EDB80 /* ObservableConvertibleType+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 357CED460E06EF4C7E0754EAC799EA25 /* ObservableConvertibleType+Signal.swift */; }; + D4933D17DC286C3DABCFD930BED56DD9 /* UIGestureRecognizer+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86C0D14AAB2AAD0385245B785EA851F7 /* UIGestureRecognizer+Rx.swift */; }; + D5A41118FE6AA9C5BF9D1F2ED254BFBD /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09A9663C9879D623393F018ED8776E10 /* InfiniteSequence.swift */; }; + D5AC68A26EC8E5548872DD8EC3A5CE8A /* Infallible+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D5B13475418FD00FB9355C56D674055 /* Infallible+Concurrency.swift */; }; + D6739D499FC4C4C4A24F9487B651D6A9 /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFC77F4E23C70CD93A47CABAD78FAB7C /* CombineLatest.swift */; }; + D6FDE9DFAC4AA548A9A4E2D6BBCE54FC /* ControlProperty+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3DA89887308B70205F4B0421B2EB1FA /* ControlProperty+Driver.swift */; }; + D7BB9B5EC40F4BBEB3D3587F6CE1BBD7 /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C35FF43E9CE7B3E34D07E3C3309933C6 /* Generate.swift */; }; + D7C02EADB2F327E5B74A5F2FC4D8605D /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AA4BD3512F86242262A2CC6E8A6E671 /* ConcurrentDispatchQueueScheduler.swift */; }; + D8F699E18D1A745F740D462C82CF8F7D /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69A5EC209674BAE5B76AEE43BF2B1232 /* Never.swift */; }; + D92AEF78B87F929D88D5C876ABBAD79A /* ConstraintLayoutSupportDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ABC2DF46B51629A6695E65591FC9C89 /* ConstraintLayoutSupportDSL.swift */; }; + D936EF159A167C7E4C5E5764C22F458F /* Then-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 609F4B4729FA21AA97F7492A1833A37F /* Then-dummy.m */; }; + DA0BE77A7A651CA6CF552CFB76498A1A /* PrimitiveSequence+Concurrency.swift in Sources */ = {isa = PBXBuildFile; fileRef = 215FE19303243AF33A524E2C73798AA5 /* PrimitiveSequence+Concurrency.swift */; }; + DA0EB35C2657F248A6CE170DBB8FEC63 /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1321A2D900535D6706FF8C96B32A3E70 /* MainScheduler.swift */; }; + DA97AA043A435ED164636D7C796627B2 /* AsSingle.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2D8AB442909361F46B93FCDA9E1B377 /* AsSingle.swift */; }; + DC567EB29336818EFE922AA49C244CB8 /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E10C69CCF0E170490EB0796D7C9132B6 /* ObserverType.swift */; }; + DCF67DD166A569F7663D87D7613F5A81 /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA270E69766A528F6C252B8D594EFC85 /* GroupBy.swift */; }; + DDDDE4944E4F58779DCE4F9D13C3C3D6 /* RxRelay-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 551A99AAA754D66BC9B9D15DCDF7EACD /* RxRelay-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DE71610B229DF6E2B65A8574BAF21414 /* SectionedViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90FDABF3938FF99C7EC73D7B2E4D59FB /* SectionedViewDataSourceType.swift */; }; + DE896085DFDD686BDBDEFB776F0D683A /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6015ECB04C1A101AA3ACF1973701C4DC /* DispatchQueue+Alamofire.swift */; }; + DE8F5B68839128A005EE3549A1149B09 /* RequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6753BF7348B5A3D7429739E50967F11 /* RequestInterceptor.swift */; }; + E09EA7C05D6F7CE8A2BCC4351B5CA7F6 /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95971C125003F3C8BC037EC583EA6C65 /* OperationQueueScheduler.swift */; }; + E191C07587A61250ED02EED7C768F167 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F3BC906B82C0BA809FA7A006E9FDE4B /* SerialDisposable.swift */; }; + E1DF012617FAE80DB7AAAAD80FB35810 /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26644356CB01B40CCAC26CC547A90468 /* RefCountDisposable.swift */; }; + E22F4170FF8A3C8A4305F8BDC9552E7E /* Binder.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5A78867A3237CA87A509AA5FF1847D8 /* Binder.swift */; }; + E22FE301DD72E4B55C97E0BC1FEA333D /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = E088DC517E18FF6BB77CE0A435AA7909 /* Using.swift */; }; + E3B95BD6FECF47BD76B10B0930CE03F0 /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83A844506F3A3A3682788357FF0BB818 /* ElementAt.swift */; }; + E4ECC8CEF025558337BFE6C253E1978E /* TakeWithPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9128491820B7D216054C0F99BC51CA9 /* TakeWithPredicate.swift */; }; + E597135D1327F849825F6C787FCDA90B /* PrimitiveSequence+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 458B18CA0C3579E691AE9516CCEF46E0 /* PrimitiveSequence+Zip+arity.swift */; }; + E6763D63381C8B7F674990191EF2F701 /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70DAD8AD0ADC993DD702BFDD88594528 /* Range.swift */; }; + E6ED06AC318A34F7744B32CEC759CDA9 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07E5CD1EDE77CDF12E316AB3F9E336FB /* Response.swift */; }; + E77F518B1CCB851E2ACE42F72DCED664 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */; }; + E94B31DCAF75D93405D3BAE188604EB2 /* ConstraintConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8E85C8B3B758271FBF09BC3E5CEC6F1 /* ConstraintConfig.swift */; }; + E9EFE2594783B175CCA9E2F5C5E3D8C9 /* DispatchQueueConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9816D93AB70CEC89C550C39068DE76E3 /* DispatchQueueConfiguration.swift */; }; + EA5FE4B4B3BF04976C37430E4F3721EF /* RxPickerViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE89C8A29E610492DC15D221F7BB17EF /* RxPickerViewDelegateProxy.swift */; }; + EB411C0C5F796794B3278016F3FA4E28 /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F1B8ECC7CC13ABD0433DB33B72BE6BE /* DisposeBase.swift */; }; + EF66D3C7A616CA086085ECF4293AED68 /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = B49CB6099B826BB7C3E1B0BCA9BD0BBF /* SchedulerType.swift */; }; + EF6DD06709E5EFD67031FF9B5901A827 /* RxTableViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6613A2AD11F440C53FFC2EA71865D23E /* RxTableViewDelegateProxy.swift */; }; + EFC90283F9AB43BB6FF377812BD3673F /* ConstraintPriority.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88BFF837CA381EA3A2714AC4C217B60E /* ConstraintPriority.swift */; }; + F13EF636FEE7C1F1C9942B5E7A02CDB1 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3543A589FB81C5F237FCEED859A1968A /* Observable.swift */; }; + F1DB0A012011FAF9188226D6CF1D82DD /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2C196D1F5E9C56E488832F1ED5AFE05 /* Zip+arity.swift */; }; + F2DDF679DF721DDA14A53744DD540092 /* NSSlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9E2BF9DFC6C02DC2152D00A85787A2B /* NSSlider+Rx.swift */; }; + F3216E564106722FB415537C86BF54FB /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBB441ED9C0BFE86D03DC41FB747AA78 /* Lock.swift */; }; + F366D04DEA0EBBCA9CA4F1F4E29695E8 /* ConstraintDSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6415A2C1FAF5F11CFA70B3027001115A /* ConstraintDSL.swift */; }; + F3B4A826460EF6A9B19849D1E7AF6A52 /* ControlEvent+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 676A41E002058A633CC31923D4187BB3 /* ControlEvent+Signal.swift */; }; + F3B517F56C11ADB67A5F42588A8B4219 /* Infallible+CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92BB718D88F12981397378C76D1E5AB3 /* Infallible+CombineLatest+arity.swift */; }; + F3DD3662056E91B939B7EF29104F28F7 /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 262C2D4447F7009D62A72F9AF36C13D6 /* VirtualTimeConverterType.swift */; }; + F4DD0AD58DDD5641BDEAEA6CF44FF0ED /* Protected.swift in Sources */ = {isa = PBXBuildFile; fileRef = 817C9EE380F66DDDD7CC07882A9DC6A0 /* Protected.swift */; }; + F5AF27692F3A5C9087F015B5C40A35E7 /* RxTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D22E2519CEAF1998AFE01A72B8C340A /* RxTarget.swift */; }; + F60E2B85B28D1E27FD52F9B0D62A50C8 /* _RXKVOObserver.m in Sources */ = {isa = PBXBuildFile; fileRef = 8F470C483FA371DD807C56B35BDB6180 /* _RXKVOObserver.m */; }; + F75490D19F11ED1416851A08B5B9BAE9 /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A3D818F7C4D3D0F113884FC5686E7FD /* SynchronizedUnsubscribeType.swift */; }; + F7774F70F3F7CD7E11F01BD8B62FFF15 /* URLSession+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F8B1C43AE360FF396F257FB7C94FDC1 /* URLSession+Rx.swift */; }; + F7E576E007A81E0EFD2E0849CB17878D /* WebSocketRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21CC94C5FDB0F32FC69042BB19754ABE /* WebSocketRequest.swift */; }; + F94703ED86C58DDBE5A2503D148CD040 /* ConstraintRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7495CCAD78765F06C5A3E7A3C7604DF2 /* ConstraintRelation.swift */; }; + F9821B669566BA01F845426DC6834E76 /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76C139ACE15066DF7A8CBF8A0575DCE8 /* Observable+Bind.swift */; }; + FAF7C9C4F9B6AE2CE9F5866B210D9275 /* SharedSequence+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FDE66F4BC83BF2EB6189F7D5567F8D5 /* SharedSequence+Operators.swift */; }; + FB9F07AFD07781E7EE473C23EF284909 /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 097F7060ACADB226898016D0AF219503 /* CombineLatest+arity.swift */; }; + FCD9660A73D7E00EA19E2F2295876E04 /* NSTextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCB055F55762E3DAC2DF05014739D6A4 /* NSTextView+Rx.swift */; }; + FCE62086E1AB54A4F61EBCDBA15C1510 /* EventMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5386F24245845ECCFA55AEF85C65890B /* EventMonitor.swift */; }; + FE9261A1344AF922C1EFCB457B938425 /* BehaviorRelay+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA7221B722804C0A49047ABF71912A73 /* BehaviorRelay+Driver.swift */; }; + FED2CCFCF5AAAC005EF2433AE5CE1140 /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2739CF11DFFA921E381968F888BED535 /* ToArray.swift */; }; + FFD7E1B8FA0F3960BE24DA2D20647332 /* ConstraintRelatableTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0834FAFB93CFA2836086CB41458DD3D /* ConstraintRelatableTarget.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0D93EC402991C60FD361F56E92A25367 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + 1A8785CA077D46458A29E5D436BA4864 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 27632CD24208F6346689C82FC555FFCD /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + 2B5A5B6D8B07663BFD23F6BA17283BAA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6; + remoteInfo = RxCocoa; + }; + 2E645EDA0A1A7B3E59716294D626288F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 4614F7CA44712A47869911BDAAD610B0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + 66A32866EA9D5F837D5417305531DA06 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + 8AB03F3D7894A28FD360F381CF32E53E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8A8DB685241263AFDF5E6B20FE67B93A; + remoteInfo = "SnapKit-SnapKit_Privacy"; + }; + 99EC8DB108C3EE277D62F3DDBA8CE2EA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 1A538A5499B1706F0983D6826042657B; + remoteInfo = RxAlamofire; + }; + 9AD87D77F545A26560FE9149D224487B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; + remoteInfo = Alamofire; + }; + B6285EBA579A04B32BF960279A30DA73 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 19622742EBA51E823D6DAE3F8CDBFAD4; + remoteInfo = SnapKit; + }; + C2011E55B914B9BD6A243023BCE38AD7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 976126A1CE06DC6E162563800E1BDF14; + remoteInfo = "Alamofire-Alamofire"; + }; + CF9D6B472B16D142CE13F3528AE4B95F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + F8B9D3173046460791BE1A3BDD218850 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = C17AEFC79E770A2906EFAAB1A3757406; + remoteInfo = Then; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0051A092B5D5F8009D2DE02ADDE9DE32 /* SnapKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SnapKit-Info.plist"; sourceTree = ""; }; + 01E338C96A64806AD5F7BC07C1F70508 /* RxAlamofire.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxAlamofire.debug.xcconfig; sourceTree = ""; }; + 0223457AB5E07E184142B3486A399FF5 /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + 022BDA7BA5349EFBEB9329EEA40E85A7 /* ConstraintLayoutGuide+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintLayoutGuide+Extensions.swift"; path = "Sources/ConstraintLayoutGuide+Extensions.swift"; sourceTree = ""; }; + 025E3D37026435B0D9CEB7B8A3A67F95 /* Zip+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+Collection.swift"; path = "RxSwift/Observables/Zip+Collection.swift"; sourceTree = ""; }; + 026C02E8CE81519DBD52B3123FA8E7E6 /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Timeout.swift; sourceTree = ""; }; + 029ACF334268DD6E08782744E5E583B1 /* RxTabBarControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift; sourceTree = ""; }; + 02E615620C3410BBAE6D6999743D7F42 /* SwiftSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftSupport.swift; path = RxSwift/SwiftSupport/SwiftSupport.swift; sourceTree = ""; }; + 033D7E05C973861E1CE97E8839C306D0 /* ResourceBundle-Alamofire-Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-Alamofire-Alamofire-Info.plist"; sourceTree = ""; }; + 0395BB4AE5E323E8FA71EC99861881EB /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + 03CAC0BE6778E17AEE82829B73CFE34F /* ControlTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlTarget.swift; path = RxCocoa/Common/ControlTarget.swift; sourceTree = ""; }; + 068488A1E3F95BF0A3399FE55E490D6B /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + 06F1307E057BB52BBE74D77F011C13AE /* UIBarButtonItem+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIBarButtonItem+Rx.swift"; path = "RxCocoa/iOS/UIBarButtonItem+Rx.swift"; sourceTree = ""; }; + 0700B3295EFF8C509D89B5A64B4152F3 /* Pods-ChatBot-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ChatBot-umbrella.h"; sourceTree = ""; }; + 07358E96DEF41D60D0B8AFE3003DA996 /* Dematerialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Dematerialize.swift; path = RxSwift/Observables/Dematerialize.swift; sourceTree = ""; }; + 07A1828624A230EAA59435008992BB8D /* RxAlamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxAlamofire.modulemap; sourceTree = ""; }; + 07E5CD1EDE77CDF12E316AB3F9E336FB /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Core/Response.swift; sourceTree = ""; }; + 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "Alamofire-Alamofire"; path = Alamofire.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 097F7060ACADB226898016D0AF219503 /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/CombineLatest+arity.swift"; sourceTree = ""; }; + 09A9663C9879D623393F018ED8776E10 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 09BFFFE07F21014134381D50352C279C /* ControlEvent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlEvent.swift; path = RxCocoa/Traits/ControlEvent.swift; sourceTree = ""; }; + 0B2D1274E08FB6DDEC02B498198422B6 /* Decode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Decode.swift; path = RxSwift/Observables/Decode.swift; sourceTree = ""; }; + 0BE3D39C8F07748932F044C9079EF373 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + 0D015391A1C86DCE1D900FDF55440501 /* _RX.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RX.m; path = RxCocoa/Runtime/_RX.m; sourceTree = ""; }; + 0D22E2519CEAF1998AFE01A72B8C340A /* RxTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTarget.swift; path = RxCocoa/Common/RxTarget.swift; sourceTree = ""; }; + 0D2E5604E8A78A3AE6B8C2C88A765F06 /* SchedulerType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift"; sourceTree = ""; }; + 0DEF302201F515462E0B3D7AD6BD2208 /* Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Create.swift; path = RxSwift/Observables/Create.swift; sourceTree = ""; }; + 0EA0FDECA39FD657BB93ADF34A70F258 /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + 0F1FADAD5E198D7CC5DCC5C8AD271E48 /* _RXDelegateProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXDelegateProxy.h; path = RxCocoa/Runtime/include/_RXDelegateProxy.h; sourceTree = ""; }; + 0F334446FFE4A761CC9A75558CE34C48 /* ConstraintOffsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintOffsetTarget.swift; path = Sources/ConstraintOffsetTarget.swift; sourceTree = ""; }; + 0FE241258B132522FA585541CFAF35D6 /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 11A6FDC99A0C74007C61727E532845B5 /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RxSwift/Observables/Optional.swift; sourceTree = ""; }; + 11B76877E7B02FE48A3692B3F0A370F1 /* RequestCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestCompression.swift; path = Source/Features/RequestCompression.swift; sourceTree = ""; }; + 127E27FD04D13F2FFD7E2365153EB850 /* RxTableViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift; sourceTree = ""; }; + 12CCC5D2BC32920261F210B0BF386F79 /* _RXObjCRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXObjCRuntime.h; path = RxCocoa/Runtime/include/_RXObjCRuntime.h; sourceTree = ""; }; + 12D85D660A383DAC2F0A428AF7C324E9 /* RxAlamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxAlamofire-prefix.pch"; sourceTree = ""; }; + 1321A2D900535D6706FF8C96B32A3E70 /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + 155951FD9ECB1880E00F8DDBF5772131 /* ConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintItem.swift; path = Sources/ConstraintItem.swift; sourceTree = ""; }; + 157BBE9A61CA66643BC96A13F65E5448 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + 15BF47FD9953789FB51066C568FAC41B /* _RXKVOObserver.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXKVOObserver.h; path = RxCocoa/Runtime/include/_RXKVOObserver.h; sourceTree = ""; }; + 15CFA59DAC63CC23DF0513E8D31E78C9 /* Completable+AndThen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Completable+AndThen.swift"; path = "RxSwift/Traits/PrimitiveSequence/Completable+AndThen.swift"; sourceTree = ""; }; + 15F42CF91B11E49FD5E0A9C5D71E3D1E /* NSControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSControl+Rx.swift"; path = "RxCocoa/macOS/NSControl+Rx.swift"; sourceTree = ""; }; + 16669C5C88E94E1D44FD7DC175608B70 /* UISwitch+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISwitch+Rx.swift"; path = "RxCocoa/iOS/UISwitch+Rx.swift"; sourceTree = ""; }; + 171AD31BA80C89E3807389F00BEA8E63 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = Sources/PrivacyInfo.xcprivacy; sourceTree = ""; }; + 17E11CC2C615ADE1CDCDC3F1B78972E6 /* DataRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataRequest.swift; path = Source/Core/DataRequest.swift; sourceTree = ""; }; + 187E85CC75BB26EA4718340FCF30FBF1 /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + 18F7F490A910E7E0D76C88A07216708D /* _RX.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RX.h; path = RxCocoa/Runtime/include/_RX.h; sourceTree = ""; }; + 1A231BA2298FF45B24675E00AA527578 /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + 1AD61CEB655920AB20FCFEEEBF886775 /* Then.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Then.swift; path = Sources/Then/Then.swift; sourceTree = ""; }; + 1B0753BA67BAB44F48140522DDD0AE2F /* LayoutConstraintItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraintItem.swift; path = Sources/LayoutConstraintItem.swift; sourceTree = ""; }; + 1B4399861D55D60894AAEDEA32A28597 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + 1B5E3F734AD887EDA517B37DBE5936B2 /* Then.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Then.debug.xcconfig; sourceTree = ""; }; + 1C0343E12CDBD4EB4F143FAB1B9C5B50 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + 1D6AF93AED3381C5C6CAB28DA53C2F76 /* RxCocoa-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-umbrella.h"; sourceTree = ""; }; + 1D6C875FAFBA5D8A03FACC057BF76588 /* RxAlamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxAlamofire-Info.plist"; sourceTree = ""; }; + 1D80F36289073915F26ABAEA35BD714C /* UIPickerView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIPickerView+Rx.swift"; path = "RxCocoa/iOS/UIPickerView+Rx.swift"; sourceTree = ""; }; + 1E7710C5413799170315818DA4E26E9B /* UILayoutSupport+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UILayoutSupport+Extensions.swift"; path = "Sources/UILayoutSupport+Extensions.swift"; sourceTree = ""; }; + 1F52E08AC945B9B081C5AECB2D4570D3 /* NSButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSButton+Rx.swift"; path = "RxCocoa/macOS/NSButton+Rx.swift"; sourceTree = ""; }; + 20D58F5BF41746D384B92E60F2A4FA68 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + 2117299940DBD9DE65E632C927B27BA2 /* HTTPMethod.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPMethod.swift; path = Source/Core/HTTPMethod.swift; sourceTree = ""; }; + 215FE19303243AF33A524E2C73798AA5 /* PrimitiveSequence+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PrimitiveSequence+Concurrency.swift"; path = "RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Concurrency.swift"; sourceTree = ""; }; + 21CC94C5FDB0F32FC69042BB19754ABE /* WebSocketRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocketRequest.swift; path = Source/Core/WebSocketRequest.swift; sourceTree = ""; }; + 2259138BEDFCE536D81C60D9D8647DED /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/Features/NetworkReachabilityManager.swift; sourceTree = ""; }; + 22F0E7B9E39A41E1992AB24925CDA083 /* UITableView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITableView+Rx.swift"; path = "RxCocoa/iOS/UITableView+Rx.swift"; sourceTree = ""; }; + 23378430FBA0F2A76F6D502BD6EB0BE8 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; includeInIndex = 1; name = PrivacyInfo.xcprivacy; path = Source/PrivacyInfo.xcprivacy; sourceTree = ""; }; + 2440B278D21A210A9CA8F5F7A3386025 /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Switch.swift; sourceTree = ""; }; + 24583429FDC6518EBA768A112CAACD99 /* RxPickerViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift; sourceTree = ""; }; + 247A3B30DFF905EA0A027E44FFDFC16E /* RxSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.debug.xcconfig; sourceTree = ""; }; + 24F1AE4D88714B12AF62EC96947C5E0C /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Just.swift; sourceTree = ""; }; + 262C2D4447F7009D62A72F9AF36C13D6 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 264943C6B3A3AA13E3CDE698CA29690E /* GroupedObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupedObservable.swift; path = RxSwift/GroupedObservable.swift; sourceTree = ""; }; + 26644356CB01B40CCAC26CC547A90468 /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + 26771536FF580C386E574A2B02751833 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Core/Notifications.swift; sourceTree = ""; }; + 26819537DAF4920F3DE8BEB827D735A7 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/Core/ParameterEncoding.swift; sourceTree = ""; }; + 2739CF11DFFA921E381968F888BED535 /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/ToArray.swift; sourceTree = ""; }; + 2803A96DBC9553A5D49174E70363DFEE /* RxCocoa-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxCocoa-Info.plist"; sourceTree = ""; }; + 287D872BA20DCC059B3FDE9891FD1566 /* SwitchIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwitchIfEmpty.swift; path = RxSwift/Observables/SwitchIfEmpty.swift; sourceTree = ""; }; + 2974CD805B71D9119CCD669B17B0438D /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/SingleAsync.swift; sourceTree = ""; }; + 29B1B7B244B0253C248351A34368BD45 /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 2A3D818F7C4D3D0F113884FC5686E7FD /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + 2AE4C07C0E4F8BB1308A67E29DEDB0F4 /* NSTextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextField+Rx.swift"; path = "RxCocoa/macOS/NSTextField+Rx.swift"; sourceTree = ""; }; + 2D967B721BF4CCD0A468C726FA0EB96B /* Alamofire.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.release.xcconfig; sourceTree = ""; }; + 2DCB0CDBC1CB97F3EF3EECDC0FF6896D /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 2DDD33F99EB662F0680B72FD8C3703DB /* MultipartUpload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartUpload.swift; path = Source/Features/MultipartUpload.swift; sourceTree = ""; }; + 2EB0DCE44FD0616E133E3C72DA1C5A34 /* ConstraintPriorityTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriorityTarget.swift; path = Sources/ConstraintPriorityTarget.swift; sourceTree = ""; }; + 2EC959663E46239A9F10441CD817D621 /* Pods-ChatBot-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ChatBot-frameworks.sh"; sourceTree = ""; }; + 2EDECA2A62722B870D23D09F0F0ECBEF /* ObservableConvertibleType+Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Infallible.swift"; path = "RxSwift/Traits/Infallible/ObservableConvertibleType+Infallible.swift"; sourceTree = ""; }; + 2F10AEB2ECC626E8F02B4E5A0D25E513 /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + 2F1B8ECC7CC13ABD0433DB33B72BE6BE /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + 2F33A0C1E70FC803B717A82FF7B656FF /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DefaultIfEmpty.swift; path = RxSwift/Observables/DefaultIfEmpty.swift; sourceTree = ""; }; + 2F8F216EF495C675DA9C3CD40CD8FB7D /* Then-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Then-prefix.pch"; sourceTree = ""; }; + 2FF2B70AFEA833EA39A3F259BAFC3B0D /* RxCollectionViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift; sourceTree = ""; }; + 3076DC3B5B5110925CDB6D08D2D2374F /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Throttle.swift; sourceTree = ""; }; + 3279EA9AD5D4A54540E377F973965A63 /* NSObject+Rx+KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+KVORepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift"; sourceTree = ""; }; + 32838C2216414C2BAEE665FA80370246 /* SnapKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-prefix.pch"; sourceTree = ""; }; + 3343B5BBE4004D26874C5F274DB6C119 /* First.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = First.swift; path = RxSwift/Observables/First.swift; sourceTree = ""; }; + 33C482FE51B8DB5C9C06EFC86B6A38F1 /* Pods-ChatBot.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ChatBot.debug.xcconfig"; sourceTree = ""; }; + 33D725EA40F13C08F36A24B9E06F4E0B /* PublishRelay+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PublishRelay+Signal.swift"; path = "RxCocoa/Traits/Signal/PublishRelay+Signal.swift"; sourceTree = ""; }; + 34661D3B62FCC5B6CEBD9806B3A397D4 /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Repeat.swift; sourceTree = ""; }; + 34E8380CBACC761166B203FC3CCB5C78 /* UploadRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = UploadRequest.swift; path = Source/Core/UploadRequest.swift; sourceTree = ""; }; + 34F46AFCC949DA69E26A2EBEAD1CD992 /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + 34FFB5EB43171CE65201569598E30A4E /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + 3543A589FB81C5F237FCEED859A1968A /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + 357CED460E06EF4C7E0754EAC799EA25 /* ObservableConvertibleType+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Signal.swift"; path = "RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift"; sourceTree = ""; }; + 366F04E49BB35F3ACC09667286ED9BDB /* AlamofireExtended.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireExtended.swift; path = Source/Features/AlamofireExtended.swift; sourceTree = ""; }; + 3752B5340A880B4107093D0C1A2EF50B /* URLEncodedFormEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLEncodedFormEncoder.swift; path = Source/Features/URLEncodedFormEncoder.swift; sourceTree = ""; }; + 38D856B4C6C703EDEBE7F4A2DD975718 /* Typealiases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Typealiases.swift; path = Sources/Typealiases.swift; sourceTree = ""; }; + 3C3CED74C2352634FFCCBF22DD716882 /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 3D114EF866038D865BB2CA522AE5DB6D /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + 3E8F346691EC094F615279F3FF4FDE02 /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + 3EE3D362AFB2DDFEE36E454BB2B4CCE4 /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + 3F1AE265260ED8EED87AB300B83FAB93 /* RxCocoa-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-prefix.pch"; sourceTree = ""; }; + 3F3BC906B82C0BA809FA7A006E9FDE4B /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + 3F55EB8DF2BC73493BDA426C5D5FBB38 /* PublishRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishRelay.swift; path = RxRelay/PublishRelay.swift; sourceTree = ""; }; + 40281A10694C95424518F246D0F1B9E3 /* Infallible+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Bind.swift"; path = "RxCocoa/Common/Infallible+Bind.swift"; sourceTree = ""; }; + 415901951242B664A2B911C62154C000 /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Buffer.swift; sourceTree = ""; }; + 4279D69741987540D0F56531AE01ABC8 /* UIDatePicker+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIDatePicker+Rx.swift"; path = "RxCocoa/iOS/UIDatePicker+Rx.swift"; sourceTree = ""; }; + 4430E98B15C737B4092B51994223EDBD /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + 449F164ADAF01D26FCA0CCF5FEBC8092 /* RxPickerViewAdapter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewAdapter.swift; path = RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift; sourceTree = ""; }; + 45550170E3AB9B8C96A76506A721CB85 /* ResourceBundle-SnapKit_Privacy-SnapKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-SnapKit_Privacy-SnapKit-Info.plist"; sourceTree = ""; }; + 458B18CA0C3579E691AE9516CCEF46E0 /* PrimitiveSequence+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PrimitiveSequence+Zip+arity.swift"; path = "RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Zip+arity.swift"; sourceTree = ""; }; + 45B1BCE02DC2388F30FBDBF9DB7EA27F /* RxTextViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift; sourceTree = ""; }; + 47D78FC4251E65A4B297FCA01575EE27 /* ConstraintMakerRelatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerRelatable.swift; path = Sources/ConstraintMakerRelatable.swift; sourceTree = ""; }; + 48E1C71FAD56AC66CA256D8B5D952C16 /* NSObject+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx.swift"; path = "RxCocoa/Foundation/NSObject+Rx.swift"; sourceTree = ""; }; + 48FA0A5D99CA478DCAC3D6AA4F0BC343 /* UITextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextView+Rx.swift"; path = "RxCocoa/iOS/UITextView+Rx.swift"; sourceTree = ""; }; + 4A7A585318011652676222B16198D0EA /* URLRequest+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLRequest+Alamofire.swift"; path = "Source/Extensions/URLRequest+Alamofire.swift"; sourceTree = ""; }; + 4AA4BD3512F86242262A2CC6E8A6E671 /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + 4B5E514669455AC7CDFC7A7F3A83C31C /* AtomicInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AtomicInt.swift; path = Platform/AtomicInt.swift; sourceTree = ""; }; + 4BC5D73D19802574E878A93DDB0A37EA /* RxRelay-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxRelay-Info.plist"; sourceTree = ""; }; + 4C2E5505F6F6A3594BDBB66B1DCD2769 /* DelegateProxyType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxyType.swift; path = RxCocoa/Common/DelegateProxyType.swift; sourceTree = ""; }; + 4D9B04EA37A48BBAE3DA14E4801DD485 /* Materialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Materialize.swift; path = RxSwift/Observables/Materialize.swift; sourceTree = ""; }; + 4D9DF43A06E832A65244893A1DA6755A /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + 4DACEC6E20113CB147731DF4D114EAF9 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/Features/ResponseSerialization.swift; sourceTree = ""; }; + 4DB527180CF7411F64A3ADCAEB4C3840 /* UIScrollView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIScrollView+Rx.swift"; path = "RxCocoa/iOS/UIScrollView+Rx.swift"; sourceTree = ""; }; + 4E5190BBD5788742C6338758F6BE977A /* UISearchController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchController+Rx.swift"; path = "RxCocoa/iOS/UISearchController+Rx.swift"; sourceTree = ""; }; + 4F10AE20C1D469556BADF31DAAE1D900 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + 4F1BDA54CA3FD66FFEBE84116D45C2DC /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + 50AAA241799F5C057429E374C1B56217 /* RxCocoa.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.release.xcconfig; sourceTree = ""; }; + 515F487FB3AAFFA95C98079E7CF98806 /* Constraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Constraint.swift; path = Sources/Constraint.swift; sourceTree = ""; }; + 51710E6F5CDA4441327AE37E1D64A62D /* RxCocoaObjCRuntimeError+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RxCocoaObjCRuntimeError+Extensions.swift"; path = "RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift"; sourceTree = ""; }; + 52D9BC489E37B4988D0B1FBF2A7FF7FE /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + 5386F24245845ECCFA55AEF85C65890B /* EventMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventMonitor.swift; path = Source/Features/EventMonitor.swift; sourceTree = ""; }; + 549CF5ED2A2E832777BBDDC43E594896 /* ObservableType+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+Extensions.swift"; path = "RxSwift/ObservableType+Extensions.swift"; sourceTree = ""; }; + 54B87B26D0094409A4830F56BD3B51F6 /* RequestTaskMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestTaskMap.swift; path = Source/Core/RequestTaskMap.swift; sourceTree = ""; }; + 55062A93A34B74A387A9688645A20D58 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + 551A99AAA754D66BC9B9D15DCDF7EACD /* RxRelay-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-umbrella.h"; sourceTree = ""; }; + 551CAD0F6423512F2D483AF73CED4994 /* SnapKit.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.release.xcconfig; sourceTree = ""; }; + 555021F007D69AA5D232C2CD69443EA4 /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/DistinctUntilChanged.swift; sourceTree = ""; }; + 560DCBC2941D96B8B2EB9C2A2728D79B /* SharedSequence+Operators+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Operators+arity.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift"; sourceTree = ""; }; + 574C212A009E9DD99FD7689219748093 /* ConstraintLayoutGuideDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuideDSL.swift; path = Sources/ConstraintLayoutGuideDSL.swift; sourceTree = ""; }; + 58B14921D76D7D8FED822C02FF79B1F7 /* StringEncoding+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "StringEncoding+Alamofire.swift"; path = "Source/Extensions/StringEncoding+Alamofire.swift"; sourceTree = ""; }; + 58C931C356BFBADA46D7D94A93E31F96 /* _RXObjCRuntime.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXObjCRuntime.m; path = RxCocoa/Runtime/_RXObjCRuntime.m; sourceTree = ""; }; + 59C926A7CDCEECF7351850331FA6041D /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Sequence.swift; sourceTree = ""; }; + 5AF99D2169C0DB0E0EBACC378A353BDE /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + 5D2330DB818D1AD381E696FC28AB475F /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Reduce.swift; sourceTree = ""; }; + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 5E2F5D5BC86EFAFEFE5DC81DA9185589 /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Timer.swift; sourceTree = ""; }; + 5F1E179320E97CEA94AB0BF098C8A150 /* ConstraintMaker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMaker.swift; path = Sources/ConstraintMaker.swift; sourceTree = ""; }; + 5FF06DB04BE117F1E668EC5B610784BF /* Then-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Then-umbrella.h"; sourceTree = ""; }; + 600F1EE1652AC362DF1F4A35FDE1D317 /* Maybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Maybe.swift; path = RxSwift/Traits/PrimitiveSequence/Maybe.swift; sourceTree = ""; }; + 6015ECB04C1A101AA3ACF1973701C4DC /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/Extensions/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 609F4B4729FA21AA97F7492A1833A37F /* Then-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Then-dummy.m"; sourceTree = ""; }; + 60A46529099F1A13A3CFA08A9D4F5825 /* ConstraintMakerEditable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerEditable.swift; path = Sources/ConstraintMakerEditable.swift; sourceTree = ""; }; + 60D8162FD7345FD61DA97E075041A37B /* RxSearchControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift; sourceTree = ""; }; + 60F6B26402A36D05D138482EDB18AB34 /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + 6415A2C1FAF5F11CFA70B3027001115A /* ConstraintDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDSL.swift; path = Sources/ConstraintDSL.swift; sourceTree = ""; }; + 648ABDA4F57CCFFCCA2E35A67A86EC81 /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + 64B8AAF028420A2370690C9C868E9514 /* DelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxy.swift; path = RxCocoa/Common/DelegateProxy.swift; sourceTree = ""; }; + 6536D1A3AA8A85023DC9EB6423385510 /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + 6554D2462B773751507D2561D0429059 /* RxPickerViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift; sourceTree = ""; }; + 6613A2AD11F440C53FFC2EA71865D23E /* RxTableViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift; sourceTree = ""; }; + 66206B9155CD697680CDD63E69552C73 /* UINavigationController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UINavigationController+Rx.swift"; path = "RxCocoa/iOS/UINavigationController+Rx.swift"; sourceTree = ""; }; + 676A41E002058A633CC31923D4187BB3 /* ControlEvent+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Signal.swift"; path = "RxCocoa/Traits/Signal/ControlEvent+Signal.swift"; sourceTree = ""; }; + 693D5828BB933F59E948083F7EAF0754 /* ItemEvents.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ItemEvents.swift; path = RxCocoa/iOS/Events/ItemEvents.swift; sourceTree = ""; }; + 69A5EC209674BAE5B76AEE43BF2B1232 /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Never.swift; sourceTree = ""; }; + 6A669D07C06527F67F9F5EA3A530BE61 /* CachedResponseHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CachedResponseHandler.swift; path = Source/Features/CachedResponseHandler.swift; sourceTree = ""; }; + 6CA3DF40C7E6460D49F6E4F2CDFE599F /* ConstraintInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsetTarget.swift; path = Sources/ConstraintInsetTarget.swift; sourceTree = ""; }; + 6D06B8A1F0B29460B3E3F01A7C318EFE /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/DelaySubscription.swift; sourceTree = ""; }; + 6D5B13475418FD00FB9355C56D674055 /* Infallible+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Concurrency.swift"; path = "RxSwift/Traits/Infallible/Infallible+Concurrency.swift"; sourceTree = ""; }; + 6DA04DDAF4253AC1E15CF4F0211613FA /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + 6DCBA6200BAAA6515261FA9034D87491 /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Skip.swift; sourceTree = ""; }; + 6EB5CB57ECB22669866D6AF3FAE88655 /* RxCollectionViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift; sourceTree = ""; }; + 7077E8FC7907912CDAB548B19E229403 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + 70B74220AE4F38E25CB0A28B625E2372 /* ControlEvent+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlEvent+Driver.swift"; sourceTree = ""; }; + 70DAD8AD0ADC993DD702BFDD88594528 /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Range.swift; sourceTree = ""; }; + 7151718F9EA2F9F76AC406B48F399B9E /* Pods-ChatBot-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ChatBot-Info.plist"; sourceTree = ""; }; + 717C05410FB264842860E5EE81C2A9FF /* UISearchBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchBar+Rx.swift"; path = "RxCocoa/iOS/UISearchBar+Rx.swift"; sourceTree = ""; }; + 73E9BC207D19E47DFDAAD9B4B44E437F /* Alamofire.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.debug.xcconfig; sourceTree = ""; }; + 73F393C2D8D48019237DF4FE1B6B73F2 /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/StartWith.swift; sourceTree = ""; }; + 7495CCAD78765F06C5A3E7A3C7604DF2 /* ConstraintRelation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelation.swift; path = Sources/ConstraintRelation.swift; sourceTree = ""; }; + 75C7AABB4BCBC0251A8595E62687915A /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Deferred.swift; sourceTree = ""; }; + 76048962C0BC28502748A6199F2B937B /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Merge.swift; sourceTree = ""; }; + 76A4001BFC51862CFE3D5E4EDAC0CAA7 /* Infallible+Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Create.swift"; path = "RxSwift/Traits/Infallible/Infallible+Create.swift"; sourceTree = ""; }; + 76C139ACE15066DF7A8CBF8A0575DCE8 /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxCocoa/Common/Observable+Bind.swift"; sourceTree = ""; }; + 77D427FA7E345AFB7C19F288B79159A9 /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Take.swift; sourceTree = ""; }; + 7924A346EAD4E87C41875A779EF066D1 /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + 7A0F56D7A7ACB744EFB305742D55986B /* SnapKit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SnapKit.debug.xcconfig; sourceTree = ""; }; + 7B43007B2F375635F0F543820879F2C5 /* ControlProperty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlProperty.swift; path = RxCocoa/Traits/ControlProperty.swift; sourceTree = ""; }; + 7B8D5B36960DB2BC65E8FBF03EE16489 /* Infallible+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Zip+arity.swift"; path = "RxSwift/Traits/Infallible/Infallible+Zip+arity.swift"; sourceTree = ""; }; + 7C29A6CB0B11367EB927BDE743C42AAE /* UITabBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBar+Rx.swift"; path = "RxCocoa/iOS/UITabBar+Rx.swift"; sourceTree = ""; }; + 7C449B8EEBBCE87868B17B7C5EE4EC28 /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Empty.swift; sourceTree = ""; }; + 7D60C3ECF2A7BA805DD9112C64977C46 /* Pods-ChatBot-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ChatBot-dummy.m"; sourceTree = ""; }; + 7D732BA10187D09CADE70C3677839C01 /* RxTextStorageDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextStorageDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift; sourceTree = ""; }; + 7D9344310635F8BA17A842C89B58FB11 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 7EA0F02CDB0C6FCF2EAD47134DEF182C /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/SubscribeOn.swift; sourceTree = ""; }; + 8069A7DFF4B219ADA4811114C23D11D3 /* ObservableType+PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+PrimitiveSequence.swift"; path = "RxSwift/Traits/PrimitiveSequence/ObservableType+PrimitiveSequence.swift"; sourceTree = ""; }; + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxSwift; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8177E2BC1F4C19F652040903BA1D97C9 /* Pods-ChatBot-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ChatBot-acknowledgements.plist"; sourceTree = ""; }; + 817C9EE380F66DDDD7CC07882A9DC6A0 /* Protected.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Protected.swift; path = Source/Core/Protected.swift; sourceTree = ""; }; + 822E3D722F17EB3AF1D5F0AEC7E5CADF /* Driver+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Driver+Subscription.swift"; path = "RxCocoa/Traits/Driver/Driver+Subscription.swift"; sourceTree = ""; }; + 82841F9D4BF64720F984684A48A9DE3E /* Then-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Then-Info.plist"; sourceTree = ""; }; + 82C59C0A4CF1CC40F60AFD98B7B2FEA9 /* ConstraintDirectionalInsetTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsetTarget.swift; path = Sources/ConstraintDirectionalInsetTarget.swift; sourceTree = ""; }; + 82D156943C2BE51941A597CAB1A7058F /* DownloadRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DownloadRequest.swift; path = Source/Core/DownloadRequest.swift; sourceTree = ""; }; + 82EF1A5DB3E52E9027C29A9138C74835 /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Debug.swift; sourceTree = ""; }; + 82F1475AA0F9C33F7EA4A1459305D2AB /* RxAlamofire */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxAlamofire; path = RxAlamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 837560DFCE36E39309E60ACBC7D8310F /* ServerTrustEvaluation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustEvaluation.swift; path = Source/Features/ServerTrustEvaluation.swift; sourceTree = ""; }; + 8396FF1BD2ED3EDFD9A22B02B98B8602 /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxSwift.modulemap; sourceTree = ""; }; + 83A844506F3A3A3682788357FF0BB818 /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/ElementAt.swift; sourceTree = ""; }; + 856202112A1327779BA17C88CA19EA21 /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 859FFBDE9607E4C6AB22EFD8E96505A5 /* RxScrollViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxScrollViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift; sourceTree = ""; }; + 85E08654D83236E0605DB188B12DF8D8 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/Core/AFError.swift; sourceTree = ""; }; + 86C0D14AAB2AAD0385245B785EA851F7 /* UIGestureRecognizer+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIGestureRecognizer+Rx.swift"; path = "RxCocoa/iOS/UIGestureRecognizer+Rx.swift"; sourceTree = ""; }; + 86FA9D7D2797406E2B96DFA5433F6DC0 /* Combine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Combine.swift; path = Source/Features/Combine.swift; sourceTree = ""; }; + 8748D0DB8153052544C8742B25C8619D /* RxCollectionViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + 88BFF837CA381EA3A2714AC4C217B60E /* ConstraintPriority.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintPriority.swift; path = Sources/ConstraintPriority.swift; sourceTree = ""; }; + 89082F8D1E4CD49B61ADB867DD87D2E9 /* Session.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Session.swift; path = Source/Core/Session.swift; sourceTree = ""; }; + 896F73650AF4D2EB4B79C55847CC0198 /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Amb.swift; sourceTree = ""; }; + 89A39F4590E1023B896352835A3A02C1 /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/ObserveOn.swift; sourceTree = ""; }; + 8ACEED6A92C605A5B1876A7C7D739E7F /* UISlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISlider+Rx.swift"; path = "RxCocoa/iOS/UISlider+Rx.swift"; sourceTree = ""; }; + 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 8D964EEE828D2550E4147E863C869CBF /* Disposables.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposables.swift; path = RxSwift/Disposables/Disposables.swift; sourceTree = ""; }; + 8E1C9087459E2A949E79028C67877E46 /* UIControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIControl+Rx.swift"; path = "RxCocoa/iOS/UIControl+Rx.swift"; sourceTree = ""; }; + 8E4DC2EDF14DC98C9F492BF09D0C6F43 /* Completable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Completable.swift; path = RxSwift/Traits/PrimitiveSequence/Completable.swift; sourceTree = ""; }; + 8F470C483FA371DD807C56B35BDB6180 /* _RXKVOObserver.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXKVOObserver.m; path = RxCocoa/Runtime/_RXKVOObserver.m; sourceTree = ""; }; + 8F8B1C43AE360FF396F257FB7C94FDC1 /* URLSession+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSession+Rx.swift"; path = "RxCocoa/Foundation/URLSession+Rx.swift"; sourceTree = ""; }; + 8FC5CC519367BF482C3936349FEFE33F /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/RetryWhen.swift; sourceTree = ""; }; + 8FDE66F4BC83BF2EB6189F7D5567F8D5 /* SharedSequence+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Operators.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift"; sourceTree = ""; }; + 903786903B96AF67D7A9F33F39784FD8 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Source/Features/RedirectHandler.swift; sourceTree = ""; }; + 90FDABF3938FF99C7EC73D7B2E4D59FB /* SectionedViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SectionedViewDataSourceType.swift; path = RxCocoa/Common/SectionedViewDataSourceType.swift; sourceTree = ""; }; + 9195910E446A0D67F0E1C2D10308382C /* SnapKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SnapKit-dummy.m"; sourceTree = ""; }; + 92BB718D88F12981397378C76D1E5AB3 /* Infallible+CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+CombineLatest+arity.swift"; path = "RxSwift/Traits/Infallible/Infallible+CombineLatest+arity.swift"; sourceTree = ""; }; + 9317E4947CA2FE1B5D5999034C09CCA7 /* Then */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Then; path = Then.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9398B7D245E1A375E3295C501C9E4C0E /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + 93FA24BD28C89D77F31B4C8729895EE0 /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Producer.swift; sourceTree = ""; }; + 95971C125003F3C8BC037EC583EA6C65 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + 95B6C010BFBF729113881E2867C2A4DE /* SharedSequence+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Concurrency.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift"; sourceTree = ""; }; + 973A568267D079EB1AE5A7C115C76219 /* URLConvertible+URLRequestConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLConvertible+URLRequestConvertible.swift"; path = "Source/Core/URLConvertible+URLRequestConvertible.swift"; sourceTree = ""; }; + 9744F3AFEABC868B5FEC030B3F516431 /* Single.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Single.swift; path = RxSwift/Traits/PrimitiveSequence/Single.swift; sourceTree = ""; }; + 979486118B3E90C08386079D57962701 /* SnapKit */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SnapKit; path = SnapKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9816D93AB70CEC89C550C39068DE76E3 /* DispatchQueueConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueConfiguration.swift; path = RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift; sourceTree = ""; }; + 98B577F905A0DA8FFFBBC48596B8D5FE /* AsyncSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncSubject.swift; path = RxSwift/Subjects/AsyncSubject.swift; sourceTree = ""; }; + 994826F0C4A5067DB8BF11B0BA848B8C /* SnapKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SnapKit-umbrella.h"; sourceTree = ""; }; + 9992B8D05DD99854D51E1DFAD535B4FF /* Observable+Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Concurrency.swift"; path = "RxSwift/Observable+Concurrency.swift"; sourceTree = ""; }; + 99E955E7BAAB58DBCD9038D19F4B5AD3 /* UIStepper+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIStepper+Rx.swift"; path = "RxCocoa/iOS/UIStepper+Rx.swift"; sourceTree = ""; }; + 9A09382CD3E7BD02B20B236979C9EADB /* PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrimitiveSequence.swift; path = RxSwift/Traits/PrimitiveSequence/PrimitiveSequence.swift; sourceTree = ""; }; + 9A8884BCDC6691051F7F78C5B82BBDBF /* ConstraintMultiplierTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMultiplierTarget.swift; path = Sources/ConstraintMultiplierTarget.swift; sourceTree = ""; }; + 9ABC2DF46B51629A6695E65591FC9C89 /* ConstraintLayoutSupportDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupportDSL.swift; path = Sources/ConstraintLayoutSupportDSL.swift; sourceTree = ""; }; + 9B0B37F547380C5FDA244EFB99AD02B1 /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + 9B74AF3B54FBE109EB58A9D28762BE51 /* Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Driver.swift; path = RxCocoa/Traits/Driver/Driver.swift; sourceTree = ""; }; + 9D43AE76EB42DD34137D60B072365019 /* RxCocoa.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoa.h; path = RxCocoa/RxCocoa.h; sourceTree = ""; }; + 9D883AB68A43C2C17FDA723730E4EFE1 /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9DD265E1057FFAD9BEAC51E6D8D280C4 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + 9DDFA8FDE05F071E9CB3CFFD7D1198AF /* TextInput.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextInput.swift; path = RxCocoa/Common/TextInput.swift; sourceTree = ""; }; + 9E58FF48ED163CB55597E534C20E56B2 /* RxAlamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxAlamofire-umbrella.h"; sourceTree = ""; }; + 9F701B3583B6D6A3A47DC899C241FED9 /* RxSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.release.xcconfig; sourceTree = ""; }; + A011A770240CFFC6D8C74720E1157413 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + A0685B997231AAB114364A3E6B1FD607 /* RxWKNavigationDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxWKNavigationDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift; sourceTree = ""; }; + A1FB810038811058EBE7EFDE05AF5B4E /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Scan.swift; sourceTree = ""; }; + A1FCEE06CE8D7B2AFE2BA9986718C750 /* RxAlamofire.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxAlamofire.release.xcconfig; sourceTree = ""; }; + A29B85E2CA3EF2226C302B57291E39AB /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + A2D8AB442909361F46B93FCDA9E1B377 /* AsSingle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsSingle.swift; path = RxSwift/Observables/AsSingle.swift; sourceTree = ""; }; + A377A735091D700527D978D7E7CF36CD /* Then.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Then.release.xcconfig; sourceTree = ""; }; + A3DA89887308B70205F4B0421B2EB1FA /* ControlProperty+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlProperty+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlProperty+Driver.swift"; sourceTree = ""; }; + A6448B431D76DF0FA9F48124C92878F7 /* RxRelay.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.release.xcconfig; sourceTree = ""; }; + A886D886268384F906A6A2155C50E9FD /* Signal+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Signal+Subscription.swift"; path = "RxCocoa/Traits/Signal/Signal+Subscription.swift"; sourceTree = ""; }; + A8F4CCB3C159644E08405B0F8E4C14A9 /* ParameterEncoder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoder.swift; path = Source/Core/ParameterEncoder.swift; sourceTree = ""; }; + A9128491820B7D216054C0F99BC51CA9 /* TakeWithPredicate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWithPredicate.swift; path = RxSwift/Observables/TakeWithPredicate.swift; sourceTree = ""; }; + A93419B2646DBDECDCBD65C3F85BF74C /* RxCocoa.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.debug.xcconfig; sourceTree = ""; }; + A9C24B3F6BCE4CFFC79D6D04A8CA4BD8 /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + AA270E69766A528F6C252B8D594EFC85 /* GroupBy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupBy.swift; path = RxSwift/Observables/GroupBy.swift; sourceTree = ""; }; + AA6454A978E347158CC842593733A41A /* RxRelay.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxRelay.modulemap; sourceTree = ""; }; + AABAC47B80C383925BE599657469267F /* ConstraintView+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintView+Extensions.swift"; path = "Sources/ConstraintView+Extensions.swift"; sourceTree = ""; }; + AAD4894D57791CCD7B1178232EDBB2FA /* ConstraintMakerPrioritizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerPrioritizable.swift; path = Sources/ConstraintMakerPrioritizable.swift; sourceTree = ""; }; + AB1066583F16C904E8CC5ECDBC6DD7F8 /* ReplayRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplayRelay.swift; path = RxRelay/ReplayRelay.swift; sourceTree = ""; }; + AB89EF4D9559D8D6C4CDB06E28D07A55 /* Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Infallible.swift; path = RxSwift/Traits/Infallible/Infallible.swift; sourceTree = ""; }; + ABBD6176CB612613A563ACD310276DDC /* RxRelay-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-prefix.pch"; sourceTree = ""; }; + AC09B2025A8B2ECE8AC4C2D1261A8757 /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+Collection.swift"; path = "RxSwift/Observables/CombineLatest+Collection.swift"; sourceTree = ""; }; + AC95EA39E18B08E75EA4D0FF6728BAB5 /* RxAlamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxAlamofire.swift; path = Sources/RxAlamofire/RxAlamofire.swift; sourceTree = ""; }; + AD5AFD8EB6E9537884257E4F1C42F8B1 /* Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Signal.swift; path = RxCocoa/Traits/Signal/Signal.swift; sourceTree = ""; }; + ADA4AA34A4B5698D80B54272AC22D86A /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Sample.swift; sourceTree = ""; }; + ADEE96E8C029C202DA706F1269584A45 /* NSObject+Rx+RawRepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+RawRepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift"; sourceTree = ""; }; + AE89C8A29E610492DC15D221F7BB17EF /* RxPickerViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift; sourceTree = ""; }; + AEC2726887ABD33AFCEFD85345582ACB /* RxTabBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift; sourceTree = ""; }; + AF29834581204BB9C286730AFE098802 /* OperationQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "OperationQueue+Alamofire.swift"; path = "Source/Extensions/OperationQueue+Alamofire.swift"; sourceTree = ""; }; + AF83526A1A4E8DE771306E1B676F2D8D /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Do.swift; sourceTree = ""; }; + B070E8A56551165C933D48C2D56D1A93 /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/TakeLast.swift; sourceTree = ""; }; + B12A085B5C37FE16D2A829B6816C93A4 /* URLSessionConfiguration+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSessionConfiguration+Alamofire.swift"; path = "Source/Extensions/URLSessionConfiguration+Alamofire.swift"; sourceTree = ""; }; + B169FA280492A036981BE5A43BF8337B /* RxCocoa.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxCocoa.modulemap; sourceTree = ""; }; + B1C8536CD5EEA7448B5B8AFA116E6AE4 /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + B27B198BB3480203B55645C028400B99 /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + B33EE3BFA18047A99158FD5A117AECAB /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Filter.swift; sourceTree = ""; }; + B49CB6099B826BB7C3E1B0BCA9BD0BBF /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + B4D9A55B60B97A971CA56B8A6B8E61B5 /* NotificationCenter+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NotificationCenter+Rx.swift"; path = "RxCocoa/Foundation/NotificationCenter+Rx.swift"; sourceTree = ""; }; + B4E41B3F95C8C68CDA816C5625843760 /* ConstraintDirectionalInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDirectionalInsets.swift; path = Sources/ConstraintDirectionalInsets.swift; sourceTree = ""; }; + B52E420BECBD89CE2E82F8EE79CDCAC5 /* ConstraintMakerRelatable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ConstraintMakerRelatable+Extensions.swift"; path = "Sources/ConstraintMakerRelatable+Extensions.swift"; sourceTree = ""; }; + B6753BF7348B5A3D7429739E50967F11 /* RequestInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestInterceptor.swift; path = Source/Features/RequestInterceptor.swift; sourceTree = ""; }; + B67C30AE79B9114C47A26A2610553526 /* ConstraintView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintView.swift; path = Sources/ConstraintView.swift; sourceTree = ""; }; + B847CFA9EC1D1B3959AFBEFD46E6A491 /* ConstraintLayoutSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutSupport.swift; path = Sources/ConstraintLayoutSupport.swift; sourceTree = ""; }; + B8DC8A713001D7BBFFCC38A262D3280C /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Sink.swift; sourceTree = ""; }; + B9093FA572EC11FFFA9D8797CCF6163E /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + B924D032B5D54E217EEA5D0B35C8E119 /* LayoutConstraint.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LayoutConstraint.swift; path = Sources/LayoutConstraint.swift; sourceTree = ""; }; + B96D597D387E7288923EE8C66B59C328 /* ShareReplayScope.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplayScope.swift; path = RxSwift/Observables/ShareReplayScope.swift; sourceTree = ""; }; + B98456D107AAC8F527122AD29B590FDF /* Bag+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bag+Rx.swift"; path = "RxSwift/Extensions/Bag+Rx.swift"; sourceTree = ""; }; + B9A3AD3EE0EEF6835B65809B55230CE0 /* ConstraintMakerFinalizable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerFinalizable.swift; path = Sources/ConstraintMakerFinalizable.swift; sourceTree = ""; }; + B9DCB5EC0B1CDADD221717CADDF62359 /* SnapKit-SnapKit_Privacy */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "SnapKit-SnapKit_Privacy"; path = SnapKit_Privacy.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + BA2BAD104F63EA5D8CF3DF2BFBB5B852 /* RxCollectionViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift; sourceTree = ""; }; + BA524373C17A6B9855D3A7609533BDB1 /* Reactive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reactive.swift; path = RxSwift/Reactive.swift; sourceTree = ""; }; + BA7221B722804C0A49047ABF71912A73 /* BehaviorRelay+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BehaviorRelay+Driver.swift"; path = "RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift"; sourceTree = ""; }; + BA92A72939FDF2DAAE299309646D27DF /* Date+Dispatch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Date+Dispatch.swift"; path = "RxSwift/Date+Dispatch.swift"; sourceTree = ""; }; + BADC91F4D42F59A8002D134BBD2701F9 /* BehaviorRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorRelay.swift; path = RxRelay/BehaviorRelay.swift; sourceTree = ""; }; + BC148DD3BD6D5B3B9DA8CE61B451C3A5 /* Delay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delay.swift; path = RxSwift/Observables/Delay.swift; sourceTree = ""; }; + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxCocoa; path = RxCocoa.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + BCA11FA51DBB607BC021DDD68D7290F2 /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + BCADE0A5DD41C1CFA84326E28BA08D0C /* RxCocoaRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoaRuntime.h; path = RxCocoa/Runtime/include/RxCocoaRuntime.h; sourceTree = ""; }; + BCD53B5B06599985FA89579262B41DC3 /* Then.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Then.modulemap; sourceTree = ""; }; + BD3C2A9316A45C1B52CDDC4C9B39AE33 /* Enumerated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Enumerated.swift; path = RxSwift/Observables/Enumerated.swift; sourceTree = ""; }; + C0786D5A312B4358DA30CD934FEBE630 /* ConstraintLayoutGuide.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintLayoutGuide.swift; path = Sources/ConstraintLayoutGuide.swift; sourceTree = ""; }; + C0E167C7E239F77C09B30A1B1BFD6A6A /* RxCollectionViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift; sourceTree = ""; }; + C23BE9C5A3B2DC55606551EA6D075F2D /* ConstraintMakerExtendable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintMakerExtendable.swift; path = Sources/ConstraintMakerExtendable.swift; sourceTree = ""; }; + C2842A835037EED44792264951C5EF03 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/Core/SessionDelegate.swift; sourceTree = ""; }; + C31AF98ADA4531DCCCD5C8CFD6F7B304 /* DataStreamRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataStreamRequest.swift; path = Source/Core/DataStreamRequest.swift; sourceTree = ""; }; + C35FF43E9CE7B3E34D07E3C3309933C6 /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Generate.swift; sourceTree = ""; }; + C3AAC8A11121C5761C45996057A91DA7 /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = RxRelay/Utils.swift; sourceTree = ""; }; + C3C2E5E9E33DDA1D3861DF17AF42F587 /* AuthenticationInterceptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationInterceptor.swift; path = Source/Features/AuthenticationInterceptor.swift; sourceTree = ""; }; + C4C1CAED9B312C0017A9D1B4ED53BD59 /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + C5193DE9E3B442CA0110473C426592C5 /* UISegmentedControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISegmentedControl+Rx.swift"; path = "RxCocoa/iOS/UISegmentedControl+Rx.swift"; sourceTree = ""; }; + C530A5336F0A017F2BD09AA4B88BCEB5 /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + C62983CB803ED24DE720CAC5F8A2A145 /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/AddRef.swift; sourceTree = ""; }; + C70DE0C182608023CED8EE3975A99DC0 /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/SkipUntil.swift; sourceTree = ""; }; + C793E0D03758DB7853AE24B522404141 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Catch.swift; sourceTree = ""; }; + C7A240C434861DE54869DA90A5E98CAE /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + C802EF4ECE0E3EE6E85F5E458E1B0D23 /* Pods-ChatBot-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ChatBot-acknowledgements.markdown"; sourceTree = ""; }; + C857C2A40F26662E363000C1696FEB51 /* HTTPHeaders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHeaders.swift; path = Source/Core/HTTPHeaders.swift; sourceTree = ""; }; + C913AE49B5DF5454F9459CB36E6CA8EB /* ObservableConvertibleType+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Driver.swift"; path = "RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift"; sourceTree = ""; }; + C9B8857FCB950426B60F8110D84C1AC4 /* NSView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSView+Rx.swift"; path = "RxCocoa/macOS/NSView+Rx.swift"; sourceTree = ""; }; + CA3CD2CFFEE20CF1E7847E5A73EBAB70 /* RxRelay.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.debug.xcconfig; sourceTree = ""; }; + CAAB78B8DEFFFA4EE62B77E879B0C0C6 /* RxNavigationControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxNavigationControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift; sourceTree = ""; }; + CBB441ED9C0BFE86D03DC41FB747AA78 /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + CCB808C5F7B22550C5478F209F2BC2A0 /* _RXDelegateProxy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXDelegateProxy.m; path = RxCocoa/Runtime/_RXDelegateProxy.m; sourceTree = ""; }; + CDBDCC4538898CA2A08F40F3200FA34B /* RxTableViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift; sourceTree = ""; }; + CEEA3119C2BCD2D17617CA0D51444126 /* UITabBarController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBarController+Rx.swift"; path = "RxCocoa/iOS/UITabBarController+Rx.swift"; sourceTree = ""; }; + CEFC74A4645C52AF239D907E90151564 /* UICollectionView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+Rx.swift"; path = "RxCocoa/iOS/UICollectionView+Rx.swift"; sourceTree = ""; }; + CFE1667CB2EE82F6909B686F19E568BE /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + D0A501FFBCFD40E47979265C4AD9AA21 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + D0FD2684DAE63430FC2CE7152FD687BB /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + D17A927600BDBCA8E9CBD704B1A90D7F /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + D2190511B07DED7D99673E56238DAC2D /* RxSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxSwift-Info.plist"; sourceTree = ""; }; + D2CBF621C3C27D36361AA1E26D1F30EC /* UIActivityIndicatorView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActivityIndicatorView+Rx.swift"; path = "RxCocoa/iOS/UIActivityIndicatorView+Rx.swift"; sourceTree = ""; }; + D45D06B40D5FB020BB5498EDE9146C96 /* SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SharedSequence.swift; path = RxCocoa/Traits/SharedSequence/SharedSequence.swift; sourceTree = ""; }; + D47B73D1968879B897EFCC72DC84ACE6 /* ConstraintAttributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintAttributes.swift; path = Sources/ConstraintAttributes.swift; sourceTree = ""; }; + D50184859B7E7B2FCD142F2D0FF83501 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Error.swift; sourceTree = ""; }; + D57C9E5D77F803BC1396D2443A0EC94E /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + D592E632CF9AA82F2DDE3C8C185C7D6B /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + D5A209EE9411D05FC10172B94E7B984A /* ConstraintConstantTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConstantTarget.swift; path = Sources/ConstraintConstantTarget.swift; sourceTree = ""; }; + D82CFCB2EA1D63276A4C46484CFDD495 /* Infallible+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Operators.swift"; path = "RxSwift/Traits/Infallible/Infallible+Operators.swift"; sourceTree = ""; }; + D82E05E5FDF3DB13CC8C3F30B72A4691 /* WKWebView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "WKWebView+Rx.swift"; path = "RxCocoa/iOS/WKWebView+Rx.swift"; sourceTree = ""; }; + D8AFCD63B50C52323EA2A928D1F65F35 /* Pods-ChatBot.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ChatBot.modulemap"; sourceTree = ""; }; + D907F5AF8F8C83891B2BBAE238EEDF4E /* Pods-ChatBot */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-ChatBot"; path = Pods_ChatBot.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D92259428C053D17FB1662BE8F4C5AB0 /* RxSearchBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift; sourceTree = ""; }; + D96B4C2B995A47D34B2F206E566FAA48 /* UIButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Rx.swift"; path = "RxCocoa/iOS/UIButton+Rx.swift"; sourceTree = ""; }; + DAC809D021BADB863C6366F88736744E /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + DBA5035607E0250F9BBE850962674564 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Map.swift; sourceTree = ""; }; + DC66BBEA2109E95F813B2386F89B2421 /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + DDD59AB6E70B0DC2C150D58C0919F3A9 /* UITextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextField+Rx.swift"; path = "RxCocoa/iOS/UITextField+Rx.swift"; sourceTree = ""; }; + DF6DA301B5D12B9ECBE093FB99BF3A1E /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + E088DC517E18FF6BB77CE0A435AA7909 /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Using.swift; sourceTree = ""; }; + E08CBB4AA59577D9B90F839FADB5B1B1 /* UIRefreshControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIRefreshControl+Rx.swift"; path = "RxCocoa/iOS/UIRefreshControl+Rx.swift"; sourceTree = ""; }; + E10C69CCF0E170490EB0796D7C9132B6 /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + E13A6F27F214D661B9C164F1CCCF44EF /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Zip.swift; sourceTree = ""; }; + E16732205A2478CA55E13CBBA6F67A9B /* Pods-ChatBot.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ChatBot.release.xcconfig"; sourceTree = ""; }; + E49C4101B06D09B0670CAA5BE93F2101 /* KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KVORepresentable.swift; path = RxCocoa/Foundation/KVORepresentable.swift; sourceTree = ""; }; + E5B5C55A7858F6D27FE4FFF3DBC68E0B /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/WithLatestFrom.swift; sourceTree = ""; }; + E60059A145C699C90DE97ABE2451727D /* RetryPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryPolicy.swift; path = Source/Features/RetryPolicy.swift; sourceTree = ""; }; + E6C67A01F1DC5F2579165A141A0F18CB /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Core/Request.swift; sourceTree = ""; }; + E6C721E38859015E49325A6D611B1474 /* Result+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Result+Alamofire.swift"; path = "Source/Extensions/Result+Alamofire.swift"; sourceTree = ""; }; + E882E636762C2DE2DB0044AD197FADF4 /* CompactMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompactMap.swift; path = RxSwift/Observables/CompactMap.swift; sourceTree = ""; }; + E8E85C8B3B758271FBF09BC3E5CEC6F1 /* ConstraintConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintConfig.swift; path = Sources/ConstraintConfig.swift; sourceTree = ""; }; + E9D61CA24837D23444AC17D5836E6548 /* RxCocoa.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCocoa.swift; path = RxCocoa/RxCocoa.swift; sourceTree = ""; }; + EADD0B8EA9DE297A536E739730E4FAEE /* RxRelay-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxRelay-dummy.m"; sourceTree = ""; }; + EBE34063EEA4DA55E61FFD61C170D3C3 /* RxCocoa-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxCocoa-dummy.m"; sourceTree = ""; }; + EBEB130BD704B0C5130C4F805B724932 /* NSTextStorage+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextStorage+Rx.swift"; path = "RxCocoa/iOS/NSTextStorage+Rx.swift"; sourceTree = ""; }; + ECD7DA76959F3C43286DB917F3A24AEF /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Window.swift; sourceTree = ""; }; + EFD0B757EB0E416B72363ACA30B7ACE3 /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + EFE4765EE6079E252FB352B1B09F0BFC /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + F0472F405283317F7A29275AEE20318B /* Debugging.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debugging.swift; path = Sources/Debugging.swift; sourceTree = ""; }; + F081D86BE1B4AE213A4230C5E17511CC /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + F0834FAFB93CFA2836086CB41458DD3D /* ConstraintRelatableTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintRelatableTarget.swift; path = Sources/ConstraintRelatableTarget.swift; sourceTree = ""; }; + F0E0D9AD1AEDD0834A8A02649DECA298 /* KVORepresentable+Swift.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+Swift.swift"; path = "RxCocoa/Foundation/KVORepresentable+Swift.swift"; sourceTree = ""; }; + F14D3772A585D66A164FAAA5400B93C2 /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxRelay/Observable+Bind.swift"; sourceTree = ""; }; + F24C61086DB2D41E0DF3945457E23C55 /* ConstraintDescription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintDescription.swift; path = Sources/ConstraintDescription.swift; sourceTree = ""; }; + F28F1ADB6CBBC92FA78ACCF525C8EF07 /* ConstraintViewDSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintViewDSL.swift; path = Sources/ConstraintViewDSL.swift; sourceTree = ""; }; + F2C196D1F5E9C56E488832F1ED5AFE05 /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Zip+arity.swift"; sourceTree = ""; }; + F35C9AC9D3F988492AAD9272FA8C5769 /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + F56E65F457FF030938F76858DC819B98 /* UIApplication+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIApplication+Rx.swift"; path = "RxCocoa/iOS/UIApplication+Rx.swift"; sourceTree = ""; }; + F5805F7F760294D2321395AB23D42525 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Multicast.swift; sourceTree = ""; }; + F586CD775793113152D995CE9D789F97 /* RxTableViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + F5A78867A3237CA87A509AA5FF1847D8 /* Binder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Binder.swift; path = RxSwift/Binder.swift; sourceTree = ""; }; + F5B5F214EE60E508D3B0518968BA0356 /* ConstraintInsets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConstraintInsets.swift; path = Sources/ConstraintInsets.swift; sourceTree = ""; }; + F6143E4D935DFB640B30ECA62AF2B02F /* SnapKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SnapKit.modulemap; sourceTree = ""; }; + F6453BF98D49C0179F6FB62D15AB8577 /* KVORepresentable+CoreGraphics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+CoreGraphics.swift"; path = "RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift"; sourceTree = ""; }; + F65E9E56914D2BF791EDE0C25C959805 /* WithUnretained.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithUnretained.swift; path = RxSwift/Observables/WithUnretained.swift; sourceTree = ""; }; + F6E235EE582F96D0A9CBEDEFD5B50391 /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Concat.swift; sourceTree = ""; }; + F71ECD032FB1811FA8D4AF1F399795DD /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Features/Validation.swift; sourceTree = ""; }; + F9A124024F0B360DAD35804DA6ADCCDC /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + F9E2BF9DFC6C02DC2152D00A85787A2B /* NSSlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSSlider+Rx.swift"; path = "RxCocoa/macOS/NSSlider+Rx.swift"; sourceTree = ""; }; + FAD9C633108582A231FE0655F51AE6F9 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/Features/MultipartFormData.swift; sourceTree = ""; }; + FAE64EECD8849FB0FB04ADB2D28964CF /* AsMaybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsMaybe.swift; path = RxSwift/Observables/AsMaybe.swift; sourceTree = ""; }; + FB1F996427CD250487436CB2849D1CD4 /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + FB37A5874127201ED9091268DDC59E33 /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + FB4645A6E0537F17A5B8C5893424C888 /* ObservableConvertibleType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift"; sourceTree = ""; }; + FBF192D9799B34F2F85E30E9984C0C31 /* Debounce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debounce.swift; path = RxSwift/Observables/Debounce.swift; sourceTree = ""; }; + FBFD850A4CBDB294862616A563E3AB71 /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + FCB055F55762E3DAC2DF05014739D6A4 /* NSTextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextView+Rx.swift"; path = "RxCocoa/macOS/NSTextView+Rx.swift"; sourceTree = ""; }; + FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + FE15C650A3A7D5EE93DE5F1B93B631FF /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/SkipWhile.swift; sourceTree = ""; }; + FF0655088DDF1DB2A8A3E4A1C172991E /* RxTableViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift; sourceTree = ""; }; + FF53BD35610DA8DDEB1ADB7A43CF5CCC /* Concurrency.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concurrency.swift; path = Source/Features/Concurrency.swift; sourceTree = ""; }; + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxRelay; path = RxRelay.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FFAF002049961423F31CDABAB1A70EB5 /* RxAlamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxAlamofire-dummy.m"; sourceTree = ""; }; + FFC77F4E23C70CD93A47CABAD78FAB7C /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/CombineLatest.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 19E52EE8B50024F5B029EE655DDFF330 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7AED511539D268220A6E16660639CDC4 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 23B4B06C495089CE8C5BC43B115E6A5F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 98E92B6037FB3E656FC53323547FC07E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 31E61577D868411A42FE876CF77E772E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4D0CEDE610B1814B54BF5FB05DBC61A0 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E77F518B1CCB851E2ACE42F72DCED664 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6F322A20F88D816DF7B97BF4CF8A39F9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C8DA26AC8F4DEB0733EB64C8182A4C57 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6F796DCACF7FECDF5C5CEF6AFE7BC0FF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C7E343559158D03F717C616F79FAA006 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 92A489FF3CED98B4EDAB0741F3306323 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A5C342523C3577E7122B4B43929BA8F3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3B901DF82C6576019330391D0F470B31 /* CFNetwork.framework in Frameworks */, + 84BEB9E439780B1E0DEF56459E3D3352 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B110F4A89B80E9EA29019FC5CA16B326 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5E3BF2B719B3A034C173D16B3ABF682E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E877FC0D3719519B688F3E17FF0228B2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987A730911012C32AF6695D7B54E35C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0870B84D8C3A4A8EFB53F0F948F686E2 /* SnapKit */ = { + isa = PBXGroup; + children = ( + 515F487FB3AAFFA95C98079E7CF98806 /* Constraint.swift */, + D47B73D1968879B897EFCC72DC84ACE6 /* ConstraintAttributes.swift */, + E8E85C8B3B758271FBF09BC3E5CEC6F1 /* ConstraintConfig.swift */, + D5A209EE9411D05FC10172B94E7B984A /* ConstraintConstantTarget.swift */, + F24C61086DB2D41E0DF3945457E23C55 /* ConstraintDescription.swift */, + B4E41B3F95C8C68CDA816C5625843760 /* ConstraintDirectionalInsets.swift */, + 82C59C0A4CF1CC40F60AFD98B7B2FEA9 /* ConstraintDirectionalInsetTarget.swift */, + 6415A2C1FAF5F11CFA70B3027001115A /* ConstraintDSL.swift */, + F5B5F214EE60E508D3B0518968BA0356 /* ConstraintInsets.swift */, + 6CA3DF40C7E6460D49F6E4F2CDFE599F /* ConstraintInsetTarget.swift */, + 155951FD9ECB1880E00F8DDBF5772131 /* ConstraintItem.swift */, + C0786D5A312B4358DA30CD934FEBE630 /* ConstraintLayoutGuide.swift */, + 022BDA7BA5349EFBEB9329EEA40E85A7 /* ConstraintLayoutGuide+Extensions.swift */, + 574C212A009E9DD99FD7689219748093 /* ConstraintLayoutGuideDSL.swift */, + B847CFA9EC1D1B3959AFBEFD46E6A491 /* ConstraintLayoutSupport.swift */, + 9ABC2DF46B51629A6695E65591FC9C89 /* ConstraintLayoutSupportDSL.swift */, + 5F1E179320E97CEA94AB0BF098C8A150 /* ConstraintMaker.swift */, + 60A46529099F1A13A3CFA08A9D4F5825 /* ConstraintMakerEditable.swift */, + C23BE9C5A3B2DC55606551EA6D075F2D /* ConstraintMakerExtendable.swift */, + B9A3AD3EE0EEF6835B65809B55230CE0 /* ConstraintMakerFinalizable.swift */, + AAD4894D57791CCD7B1178232EDBB2FA /* ConstraintMakerPrioritizable.swift */, + 47D78FC4251E65A4B297FCA01575EE27 /* ConstraintMakerRelatable.swift */, + B52E420BECBD89CE2E82F8EE79CDCAC5 /* ConstraintMakerRelatable+Extensions.swift */, + 9A8884BCDC6691051F7F78C5B82BBDBF /* ConstraintMultiplierTarget.swift */, + 0F334446FFE4A761CC9A75558CE34C48 /* ConstraintOffsetTarget.swift */, + 88BFF837CA381EA3A2714AC4C217B60E /* ConstraintPriority.swift */, + 2EB0DCE44FD0616E133E3C72DA1C5A34 /* ConstraintPriorityTarget.swift */, + F0834FAFB93CFA2836086CB41458DD3D /* ConstraintRelatableTarget.swift */, + 7495CCAD78765F06C5A3E7A3C7604DF2 /* ConstraintRelation.swift */, + B67C30AE79B9114C47A26A2610553526 /* ConstraintView.swift */, + AABAC47B80C383925BE599657469267F /* ConstraintView+Extensions.swift */, + F28F1ADB6CBBC92FA78ACCF525C8EF07 /* ConstraintViewDSL.swift */, + F0472F405283317F7A29275AEE20318B /* Debugging.swift */, + B924D032B5D54E217EEA5D0B35C8E119 /* LayoutConstraint.swift */, + 1B0753BA67BAB44F48140522DDD0AE2F /* LayoutConstraintItem.swift */, + 38D856B4C6C703EDEBE7F4A2DD975718 /* Typealiases.swift */, + 1E7710C5413799170315818DA4E26E9B /* UILayoutSupport+Extensions.swift */, + 9087D75CEDB9282D319CED4E92C8AC9B /* Resources */, + 46A43A76897C5734AB828FEB511E2237 /* Support Files */, + ); + name = SnapKit; + path = SnapKit; + sourceTree = ""; + }; + 0CB80B3ED6D8A3CFEA1E1D3BD460F330 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 85E08654D83236E0605DB188B12DF8D8 /* AFError.swift */, + 2DCB0CDBC1CB97F3EF3EECDC0FF6896D /* Alamofire.swift */, + 366F04E49BB35F3ACC09667286ED9BDB /* AlamofireExtended.swift */, + C3C2E5E9E33DDA1D3861DF17AF42F587 /* AuthenticationInterceptor.swift */, + 6A669D07C06527F67F9F5EA3A530BE61 /* CachedResponseHandler.swift */, + 86FA9D7D2797406E2B96DFA5433F6DC0 /* Combine.swift */, + FF53BD35610DA8DDEB1ADB7A43CF5CCC /* Concurrency.swift */, + 17E11CC2C615ADE1CDCDC3F1B78972E6 /* DataRequest.swift */, + C31AF98ADA4531DCCCD5C8CFD6F7B304 /* DataStreamRequest.swift */, + 6015ECB04C1A101AA3ACF1973701C4DC /* DispatchQueue+Alamofire.swift */, + 82D156943C2BE51941A597CAB1A7058F /* DownloadRequest.swift */, + 5386F24245845ECCFA55AEF85C65890B /* EventMonitor.swift */, + C857C2A40F26662E363000C1696FEB51 /* HTTPHeaders.swift */, + 2117299940DBD9DE65E632C927B27BA2 /* HTTPMethod.swift */, + FAD9C633108582A231FE0655F51AE6F9 /* MultipartFormData.swift */, + 2DDD33F99EB662F0680B72FD8C3703DB /* MultipartUpload.swift */, + 2259138BEDFCE536D81C60D9D8647DED /* NetworkReachabilityManager.swift */, + 26771536FF580C386E574A2B02751833 /* Notifications.swift */, + AF29834581204BB9C286730AFE098802 /* OperationQueue+Alamofire.swift */, + A8F4CCB3C159644E08405B0F8E4C14A9 /* ParameterEncoder.swift */, + 26819537DAF4920F3DE8BEB827D735A7 /* ParameterEncoding.swift */, + 817C9EE380F66DDDD7CC07882A9DC6A0 /* Protected.swift */, + 903786903B96AF67D7A9F33F39784FD8 /* RedirectHandler.swift */, + E6C67A01F1DC5F2579165A141A0F18CB /* Request.swift */, + 11B76877E7B02FE48A3692B3F0A370F1 /* RequestCompression.swift */, + B6753BF7348B5A3D7429739E50967F11 /* RequestInterceptor.swift */, + 54B87B26D0094409A4830F56BD3B51F6 /* RequestTaskMap.swift */, + 07E5CD1EDE77CDF12E316AB3F9E336FB /* Response.swift */, + 4DACEC6E20113CB147731DF4D114EAF9 /* ResponseSerialization.swift */, + E6C721E38859015E49325A6D611B1474 /* Result+Alamofire.swift */, + E60059A145C699C90DE97ABE2451727D /* RetryPolicy.swift */, + 837560DFCE36E39309E60ACBC7D8310F /* ServerTrustEvaluation.swift */, + 89082F8D1E4CD49B61ADB867DD87D2E9 /* Session.swift */, + C2842A835037EED44792264951C5EF03 /* SessionDelegate.swift */, + 58B14921D76D7D8FED822C02FF79B1F7 /* StringEncoding+Alamofire.swift */, + 34E8380CBACC761166B203FC3CCB5C78 /* UploadRequest.swift */, + 973A568267D079EB1AE5A7C115C76219 /* URLConvertible+URLRequestConvertible.swift */, + 3752B5340A880B4107093D0C1A2EF50B /* URLEncodedFormEncoder.swift */, + 4A7A585318011652676222B16198D0EA /* URLRequest+Alamofire.swift */, + B12A085B5C37FE16D2A829B6816C93A4 /* URLSessionConfiguration+Alamofire.swift */, + F71ECD032FB1811FA8D4AF1F399795DD /* Validation.swift */, + 21CC94C5FDB0F32FC69042BB19754ABE /* WebSocketRequest.swift */, + B10172C5620C6818265C98BD80E1AD57 /* Resources */, + 2A27EA1E5BD3F26546F3624C1142A976 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 61C8CC330A5CA84DA2F5F1D32AB07069 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 239D13D9E3DD8B316233DC34EB7233DA /* Products */ = { + isa = PBXGroup; + children = ( + 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */, + 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */, + D907F5AF8F8C83891B2BBAE238EEDF4E /* Pods-ChatBot */, + 82F1475AA0F9C33F7EA4A1459305D2AB /* RxAlamofire */, + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */, + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */, + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */, + 979486118B3E90C08386079D57962701 /* SnapKit */, + B9DCB5EC0B1CDADD221717CADDF62359 /* SnapKit-SnapKit_Privacy */, + 9317E4947CA2FE1B5D5999034C09CCA7 /* Then */, + ); + name = Products; + sourceTree = ""; + }; + 2948E91ADB71D1F2B6E3DBAB0DEBE072 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 2D0EF0384DEF69DD4E5EDAB18B650E1A /* Pods-ChatBot */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 2A27EA1E5BD3F26546F3624C1142A976 /* Support Files */ = { + isa = PBXGroup; + children = ( + 34FFB5EB43171CE65201569598E30A4E /* Alamofire.modulemap */, + 7D9344310635F8BA17A842C89B58FB11 /* Alamofire-dummy.m */, + 20D58F5BF41746D384B92E60F2A4FA68 /* Alamofire-Info.plist */, + D0A501FFBCFD40E47979265C4AD9AA21 /* Alamofire-prefix.pch */, + A011A770240CFFC6D8C74720E1157413 /* Alamofire-umbrella.h */, + 73E9BC207D19E47DFDAAD9B4B44E437F /* Alamofire.debug.xcconfig */, + 2D967B721BF4CCD0A468C726FA0EB96B /* Alamofire.release.xcconfig */, + 033D7E05C973861E1CE97E8839C306D0 /* ResourceBundle-Alamofire-Alamofire-Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 2D0EF0384DEF69DD4E5EDAB18B650E1A /* Pods-ChatBot */ = { + isa = PBXGroup; + children = ( + D8AFCD63B50C52323EA2A928D1F65F35 /* Pods-ChatBot.modulemap */, + C802EF4ECE0E3EE6E85F5E458E1B0D23 /* Pods-ChatBot-acknowledgements.markdown */, + 8177E2BC1F4C19F652040903BA1D97C9 /* Pods-ChatBot-acknowledgements.plist */, + 7D60C3ECF2A7BA805DD9112C64977C46 /* Pods-ChatBot-dummy.m */, + 2EC959663E46239A9F10441CD817D621 /* Pods-ChatBot-frameworks.sh */, + 7151718F9EA2F9F76AC406B48F399B9E /* Pods-ChatBot-Info.plist */, + 0700B3295EFF8C509D89B5A64B4152F3 /* Pods-ChatBot-umbrella.h */, + 33C482FE51B8DB5C9C06EFC86B6A38F1 /* Pods-ChatBot.debug.xcconfig */, + E16732205A2478CA55E13CBBA6F67A9B /* Pods-ChatBot.release.xcconfig */, + ); + name = "Pods-ChatBot"; + path = "Target Support Files/Pods-ChatBot"; + sourceTree = ""; + }; + 39E28C59438097898E1DAE60CC7D3AAA /* Support Files */ = { + isa = PBXGroup; + children = ( + AA6454A978E347158CC842593733A41A /* RxRelay.modulemap */, + EADD0B8EA9DE297A536E739730E4FAEE /* RxRelay-dummy.m */, + 4BC5D73D19802574E878A93DDB0A37EA /* RxRelay-Info.plist */, + ABBD6176CB612613A563ACD310276DDC /* RxRelay-prefix.pch */, + 551A99AAA754D66BC9B9D15DCDF7EACD /* RxRelay-umbrella.h */, + CA3CD2CFFEE20CF1E7847E5A73EBAB70 /* RxRelay.debug.xcconfig */, + A6448B431D76DF0FA9F48124C92878F7 /* RxRelay.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxRelay"; + sourceTree = ""; + }; + 438EC45761C2FC2E01D68DA9F479BDC7 /* Support Files */ = { + isa = PBXGroup; + children = ( + B169FA280492A036981BE5A43BF8337B /* RxCocoa.modulemap */, + EBE34063EEA4DA55E61FFD61C170D3C3 /* RxCocoa-dummy.m */, + 2803A96DBC9553A5D49174E70363DFEE /* RxCocoa-Info.plist */, + 3F1AE265260ED8EED87AB300B83FAB93 /* RxCocoa-prefix.pch */, + 1D6AF93AED3381C5C6CAB28DA53C2F76 /* RxCocoa-umbrella.h */, + A93419B2646DBDECDCBD65C3F85BF74C /* RxCocoa.debug.xcconfig */, + 50AAA241799F5C057429E374C1B56217 /* RxCocoa.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxCocoa"; + sourceTree = ""; + }; + 46A43A76897C5734AB828FEB511E2237 /* Support Files */ = { + isa = PBXGroup; + children = ( + 45550170E3AB9B8C96A76506A721CB85 /* ResourceBundle-SnapKit_Privacy-SnapKit-Info.plist */, + F6143E4D935DFB640B30ECA62AF2B02F /* SnapKit.modulemap */, + 9195910E446A0D67F0E1C2D10308382C /* SnapKit-dummy.m */, + 0051A092B5D5F8009D2DE02ADDE9DE32 /* SnapKit-Info.plist */, + 32838C2216414C2BAEE665FA80370246 /* SnapKit-prefix.pch */, + 994826F0C4A5067DB8BF11B0BA848B8C /* SnapKit-umbrella.h */, + 7A0F56D7A7ACB744EFB305742D55986B /* SnapKit.debug.xcconfig */, + 551CAD0F6423512F2D483AF73CED4994 /* SnapKit.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/SnapKit"; + sourceTree = ""; + }; + 5BA720C75267C5F4769914A6C443D218 /* Core */ = { + isa = PBXGroup; + children = ( + AC95EA39E18B08E75EA4D0FF6728BAB5 /* RxAlamofire.swift */, + ); + name = Core; + sourceTree = ""; + }; + 61C8CC330A5CA84DA2F5F1D32AB07069 /* iOS */ = { + isa = PBXGroup; + children = ( + 8D3D57353834825F7B52B816066B7789 /* CFNetwork.framework */, + FD0CE05D5D076B1B5190EE5DF97FD54E /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 7B38E215F9D7B86EB28E047E4C2DB871 /* Then */ = { + isa = PBXGroup; + children = ( + 1AD61CEB655920AB20FCFEEEBF886775 /* Then.swift */, + A508DEE091E9906DD82B1623C754D882 /* Support Files */, + ); + name = Then; + path = Then; + sourceTree = ""; + }; + 9087D75CEDB9282D319CED4E92C8AC9B /* Resources */ = { + isa = PBXGroup; + children = ( + 171AD31BA80C89E3807389F00BEA8E63 /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + 94FE54094D1125C18D6F145B16A382B0 /* RxSwift */ = { + isa = PBXGroup; + children = ( + C62983CB803ED24DE720CAC5F8A2A145 /* AddRef.swift */, + 896F73650AF4D2EB4B79C55847CC0198 /* Amb.swift */, + 3EE3D362AFB2DDFEE36E454BB2B4CCE4 /* AnonymousDisposable.swift */, + C4C1CAED9B312C0017A9D1B4ED53BD59 /* AnonymousObserver.swift */, + 1B4399861D55D60894AAEDEA32A28597 /* AnyObserver.swift */, + FAE64EECD8849FB0FB04ADB2D28964CF /* AsMaybe.swift */, + A2D8AB442909361F46B93FCDA9E1B377 /* AsSingle.swift */, + 3D114EF866038D865BB2CA522AE5DB6D /* AsyncLock.swift */, + 98B577F905A0DA8FFFBBC48596B8D5FE /* AsyncSubject.swift */, + 4B5E514669455AC7CDFC7A7F3A83C31C /* AtomicInt.swift */, + DC66BBEA2109E95F813B2386F89B2421 /* Bag.swift */, + B98456D107AAC8F527122AD29B590FDF /* Bag+Rx.swift */, + D17A927600BDBCA8E9CBD704B1A90D7F /* BehaviorSubject.swift */, + 5AF99D2169C0DB0E0EBACC378A353BDE /* BinaryDisposable.swift */, + F5A78867A3237CA87A509AA5FF1847D8 /* Binder.swift */, + 9B0B37F547380C5FDA244EFB99AD02B1 /* BooleanDisposable.swift */, + 415901951242B664A2B911C62154C000 /* Buffer.swift */, + 7077E8FC7907912CDAB548B19E229403 /* Cancelable.swift */, + C793E0D03758DB7853AE24B522404141 /* Catch.swift */, + FFC77F4E23C70CD93A47CABAD78FAB7C /* CombineLatest.swift */, + 097F7060ACADB226898016D0AF219503 /* CombineLatest+arity.swift */, + AC09B2025A8B2ECE8AC4C2D1261A8757 /* CombineLatest+Collection.swift */, + E882E636762C2DE2DB0044AD197FADF4 /* CompactMap.swift */, + 8E4DC2EDF14DC98C9F492BF09D0C6F43 /* Completable.swift */, + 15CFA59DAC63CC23DF0513E8D31E78C9 /* Completable+AndThen.swift */, + 4D9DF43A06E832A65244893A1DA6755A /* CompositeDisposable.swift */, + F6E235EE582F96D0A9CBEDEFD5B50391 /* Concat.swift */, + 4AA4BD3512F86242262A2CC6E8A6E671 /* ConcurrentDispatchQueueScheduler.swift */, + 4F1BDA54CA3FD66FFEBE84116D45C2DC /* ConcurrentMainScheduler.swift */, + 9398B7D245E1A375E3295C501C9E4C0E /* ConnectableObservableType.swift */, + 0DEF302201F515462E0B3D7AD6BD2208 /* Create.swift */, + 4430E98B15C737B4092B51994223EDBD /* CurrentThreadScheduler.swift */, + BA92A72939FDF2DAAE299309646D27DF /* Date+Dispatch.swift */, + FBF192D9799B34F2F85E30E9984C0C31 /* Debounce.swift */, + 82EF1A5DB3E52E9027C29A9138C74835 /* Debug.swift */, + 0B2D1274E08FB6DDEC02B498198422B6 /* Decode.swift */, + 2F33A0C1E70FC803B717A82FF7B656FF /* DefaultIfEmpty.swift */, + 75C7AABB4BCBC0251A8595E62687915A /* Deferred.swift */, + BC148DD3BD6D5B3B9DA8CE61B451C3A5 /* Delay.swift */, + 6D06B8A1F0B29460B3E3F01A7C318EFE /* DelaySubscription.swift */, + 07358E96DEF41D60D0B8AFE3003DA996 /* Dematerialize.swift */, + F081D86BE1B4AE213A4230C5E17511CC /* DispatchQueue+Extensions.swift */, + 9816D93AB70CEC89C550C39068DE76E3 /* DispatchQueueConfiguration.swift */, + FB1F996427CD250487436CB2849D1CD4 /* Disposable.swift */, + 8D964EEE828D2550E4147E863C869CBF /* Disposables.swift */, + 1A231BA2298FF45B24675E00AA527578 /* DisposeBag.swift */, + 2F1B8ECC7CC13ABD0433DB33B72BE6BE /* DisposeBase.swift */, + 555021F007D69AA5D232C2CD69443EA4 /* DistinctUntilChanged.swift */, + AF83526A1A4E8DE771306E1B676F2D8D /* Do.swift */, + 83A844506F3A3A3682788357FF0BB818 /* ElementAt.swift */, + 7C449B8EEBBCE87868B17B7C5EE4EC28 /* Empty.swift */, + BD3C2A9316A45C1B52CDDC4C9B39AE33 /* Enumerated.swift */, + D50184859B7E7B2FCD142F2D0FF83501 /* Error.swift */, + 34F46AFCC949DA69E26A2EBEAD1CD992 /* Errors.swift */, + 3E8F346691EC094F615279F3FF4FDE02 /* Event.swift */, + B33EE3BFA18047A99158FD5A117AECAB /* Filter.swift */, + 3343B5BBE4004D26874C5F274DB6C119 /* First.swift */, + C35FF43E9CE7B3E34D07E3C3309933C6 /* Generate.swift */, + AA270E69766A528F6C252B8D594EFC85 /* GroupBy.swift */, + 264943C6B3A3AA13E3CDE698CA29690E /* GroupedObservable.swift */, + 157BBE9A61CA66643BC96A13F65E5448 /* HistoricalScheduler.swift */, + 4F10AE20C1D469556BADF31DAAE1D900 /* HistoricalSchedulerTimeConverter.swift */, + BCA11FA51DBB607BC021DDD68D7290F2 /* ImmediateSchedulerType.swift */, + AB89EF4D9559D8D6C4CDB06E28D07A55 /* Infallible.swift */, + 92BB718D88F12981397378C76D1E5AB3 /* Infallible+CombineLatest+arity.swift */, + 6D5B13475418FD00FB9355C56D674055 /* Infallible+Concurrency.swift */, + 76A4001BFC51862CFE3D5E4EDAC0CAA7 /* Infallible+Create.swift */, + D82CFCB2EA1D63276A4C46484CFDD495 /* Infallible+Operators.swift */, + 7B8D5B36960DB2BC65E8FBF03EE16489 /* Infallible+Zip+arity.swift */, + 09A9663C9879D623393F018ED8776E10 /* InfiniteSequence.swift */, + C530A5336F0A017F2BD09AA4B88BCEB5 /* InvocableScheduledItem.swift */, + 0223457AB5E07E184142B3486A399FF5 /* InvocableType.swift */, + 24F1AE4D88714B12AF62EC96947C5E0C /* Just.swift */, + CBB441ED9C0BFE86D03DC41FB747AA78 /* Lock.swift */, + 0EA0FDECA39FD657BB93ADF34A70F258 /* LockOwnerType.swift */, + 1321A2D900535D6706FF8C96B32A3E70 /* MainScheduler.swift */, + DBA5035607E0250F9BBE850962674564 /* Map.swift */, + 4D9B04EA37A48BBAE3DA14E4801DD485 /* Materialize.swift */, + 600F1EE1652AC362DF1F4A35FDE1D317 /* Maybe.swift */, + 76048962C0BC28502748A6199F2B937B /* Merge.swift */, + F5805F7F760294D2321395AB23D42525 /* Multicast.swift */, + 69A5EC209674BAE5B76AEE43BF2B1232 /* Never.swift */, + D57C9E5D77F803BC1396D2443A0EC94E /* NopDisposable.swift */, + 3543A589FB81C5F237FCEED859A1968A /* Observable.swift */, + 9992B8D05DD99854D51E1DFAD535B4FF /* Observable+Concurrency.swift */, + 7924A346EAD4E87C41875A779EF066D1 /* ObservableConvertibleType.swift */, + 2EDECA2A62722B870D23D09F0F0ECBEF /* ObservableConvertibleType+Infallible.swift */, + CFE1667CB2EE82F6909B686F19E568BE /* ObservableType.swift */, + 549CF5ED2A2E832777BBDDC43E594896 /* ObservableType+Extensions.swift */, + 8069A7DFF4B219ADA4811114C23D11D3 /* ObservableType+PrimitiveSequence.swift */, + 89A39F4590E1023B896352835A3A02C1 /* ObserveOn.swift */, + 55062A93A34B74A387A9688645A20D58 /* ObserverBase.swift */, + E10C69CCF0E170490EB0796D7C9132B6 /* ObserverType.swift */, + 95971C125003F3C8BC037EC583EA6C65 /* OperationQueueScheduler.swift */, + 11A6FDC99A0C74007C61727E532845B5 /* Optional.swift */, + 0BE3D39C8F07748932F044C9079EF373 /* Platform.Darwin.swift */, + F9A124024F0B360DAD35804DA6ADCCDC /* Platform.Linux.swift */, + 9A09382CD3E7BD02B20B236979C9EADB /* PrimitiveSequence.swift */, + 215FE19303243AF33A524E2C73798AA5 /* PrimitiveSequence+Concurrency.swift */, + 458B18CA0C3579E691AE9516CCEF46E0 /* PrimitiveSequence+Zip+arity.swift */, + 9D883AB68A43C2C17FDA723730E4EFE1 /* PriorityQueue.swift */, + 93FA24BD28C89D77F31B4C8729895EE0 /* Producer.swift */, + 2F10AEB2ECC626E8F02B4E5A0D25E513 /* PublishSubject.swift */, + 0FE241258B132522FA585541CFAF35D6 /* Queue.swift */, + 70DAD8AD0ADC993DD702BFDD88594528 /* Range.swift */, + BA524373C17A6B9855D3A7609533BDB1 /* Reactive.swift */, + 0395BB4AE5E323E8FA71EC99861881EB /* RecursiveLock.swift */, + 187E85CC75BB26EA4718340FCF30FBF1 /* RecursiveScheduler.swift */, + 5D2330DB818D1AD381E696FC28AB475F /* Reduce.swift */, + 26644356CB01B40CCAC26CC547A90468 /* RefCountDisposable.swift */, + 34661D3B62FCC5B6CEBD9806B3A397D4 /* Repeat.swift */, + 856202112A1327779BA17C88CA19EA21 /* ReplaySubject.swift */, + 8FC5CC519367BF482C3936349FEFE33F /* RetryWhen.swift */, + D0FD2684DAE63430FC2CE7152FD687BB /* Rx.swift */, + FBFD850A4CBDB294862616A563E3AB71 /* RxMutableBox.swift */, + ADA4AA34A4B5698D80B54272AC22D86A /* Sample.swift */, + A1FB810038811058EBE7EFDE05AF5B4E /* Scan.swift */, + EFE4765EE6079E252FB352B1B09F0BFC /* ScheduledDisposable.swift */, + 9DD265E1057FFAD9BEAC51E6D8D280C4 /* ScheduledItem.swift */, + FB37A5874127201ED9091268DDC59E33 /* ScheduledItemType.swift */, + F35C9AC9D3F988492AAD9272FA8C5769 /* SchedulerServices+Emulation.swift */, + B49CB6099B826BB7C3E1B0BCA9BD0BBF /* SchedulerType.swift */, + 59C926A7CDCEECF7351850331FA6041D /* Sequence.swift */, + B9093FA572EC11FFFA9D8797CCF6163E /* SerialDispatchQueueScheduler.swift */, + 3F3BC906B82C0BA809FA7A006E9FDE4B /* SerialDisposable.swift */, + B96D597D387E7288923EE8C66B59C328 /* ShareReplayScope.swift */, + 9744F3AFEABC868B5FEC030B3F516431 /* Single.swift */, + DF6DA301B5D12B9ECBE093FB99BF3A1E /* SingleAssignmentDisposable.swift */, + 2974CD805B71D9119CCD669B17B0438D /* SingleAsync.swift */, + B8DC8A713001D7BBFFCC38A262D3280C /* Sink.swift */, + 6DCBA6200BAAA6515261FA9034D87491 /* Skip.swift */, + C70DE0C182608023CED8EE3975A99DC0 /* SkipUntil.swift */, + FE15C650A3A7D5EE93DE5F1B93B631FF /* SkipWhile.swift */, + 73F393C2D8D48019237DF4FE1B6B73F2 /* StartWith.swift */, + B27B198BB3480203B55645C028400B99 /* SubjectType.swift */, + 7EA0F02CDB0C6FCF2EAD47134DEF182C /* SubscribeOn.swift */, + 52D9BC489E37B4988D0B1FBF2A7FF7FE /* SubscriptionDisposable.swift */, + 02E615620C3410BBAE6D6999743D7F42 /* SwiftSupport.swift */, + 2440B278D21A210A9CA8F5F7A3386025 /* Switch.swift */, + 287D872BA20DCC059B3FDE9891FD1566 /* SwitchIfEmpty.swift */, + 6DA04DDAF4253AC1E15CF4F0211613FA /* SynchronizedDisposeType.swift */, + C7A240C434861DE54869DA90A5E98CAE /* SynchronizedOnType.swift */, + 2A3D818F7C4D3D0F113884FC5686E7FD /* SynchronizedUnsubscribeType.swift */, + 068488A1E3F95BF0A3399FE55E490D6B /* TailRecursiveSink.swift */, + 77D427FA7E345AFB7C19F288B79159A9 /* Take.swift */, + B070E8A56551165C933D48C2D56D1A93 /* TakeLast.swift */, + A9128491820B7D216054C0F99BC51CA9 /* TakeWithPredicate.swift */, + 3076DC3B5B5110925CDB6D08D2D2374F /* Throttle.swift */, + 026C02E8CE81519DBD52B3123FA8E7E6 /* Timeout.swift */, + 5E2F5D5BC86EFAFEFE5DC81DA9185589 /* Timer.swift */, + 2739CF11DFFA921E381968F888BED535 /* ToArray.swift */, + E088DC517E18FF6BB77CE0A435AA7909 /* Using.swift */, + 262C2D4447F7009D62A72F9AF36C13D6 /* VirtualTimeConverterType.swift */, + 60F6B26402A36D05D138482EDB18AB34 /* VirtualTimeScheduler.swift */, + ECD7DA76959F3C43286DB917F3A24AEF /* Window.swift */, + E5B5C55A7858F6D27FE4FFF3DBC68E0B /* WithLatestFrom.swift */, + F65E9E56914D2BF791EDE0C25C959805 /* WithUnretained.swift */, + E13A6F27F214D661B9C164F1CCCF44EF /* Zip.swift */, + F2C196D1F5E9C56E488832F1ED5AFE05 /* Zip+arity.swift */, + 025E3D37026435B0D9CEB7B8A3A67F95 /* Zip+Collection.swift */, + A6B44FA36A70D38081D48AFC33C6F326 /* Support Files */, + ); + name = RxSwift; + path = RxSwift; + sourceTree = ""; + }; + 989D03EA24A70CDC956CE591015FBA14 /* RxAlamofire */ = { + isa = PBXGroup; + children = ( + 5BA720C75267C5F4769914A6C443D218 /* Core */, + D32F1CD76691808B840A6F6CE1840DDF /* Support Files */, + ); + name = RxAlamofire; + path = RxAlamofire; + sourceTree = ""; + }; + 9DA662C9AD7BAE1AAF2417A523D91AED /* Pods */ = { + isa = PBXGroup; + children = ( + 0CB80B3ED6D8A3CFEA1E1D3BD460F330 /* Alamofire */, + 989D03EA24A70CDC956CE591015FBA14 /* RxAlamofire */, + A0C1A167F55B1DF15A96BEA43E0B873A /* RxCocoa */, + D91E7ACFCBCE44A6019606EBB97EA283 /* RxRelay */, + 94FE54094D1125C18D6F145B16A382B0 /* RxSwift */, + 0870B84D8C3A4A8EFB53F0F948F686E2 /* SnapKit */, + 7B38E215F9D7B86EB28E047E4C2DB871 /* Then */, + ); + name = Pods; + sourceTree = ""; + }; + A0C1A167F55B1DF15A96BEA43E0B873A /* RxCocoa */ = { + isa = PBXGroup; + children = ( + 18F7F490A910E7E0D76C88A07216708D /* _RX.h */, + 0D015391A1C86DCE1D900FDF55440501 /* _RX.m */, + 0F1FADAD5E198D7CC5DCC5C8AD271E48 /* _RXDelegateProxy.h */, + CCB808C5F7B22550C5478F209F2BC2A0 /* _RXDelegateProxy.m */, + 15BF47FD9953789FB51066C568FAC41B /* _RXKVOObserver.h */, + 8F470C483FA371DD807C56B35BDB6180 /* _RXKVOObserver.m */, + 12CCC5D2BC32920261F210B0BF386F79 /* _RXObjCRuntime.h */, + 58C931C356BFBADA46D7D94A93E31F96 /* _RXObjCRuntime.m */, + A29B85E2CA3EF2226C302B57291E39AB /* Bag.swift */, + BA7221B722804C0A49047ABF71912A73 /* BehaviorRelay+Driver.swift */, + 09BFFFE07F21014134381D50352C279C /* ControlEvent.swift */, + 70B74220AE4F38E25CB0A28B625E2372 /* ControlEvent+Driver.swift */, + 676A41E002058A633CC31923D4187BB3 /* ControlEvent+Signal.swift */, + 7B43007B2F375635F0F543820879F2C5 /* ControlProperty.swift */, + A3DA89887308B70205F4B0421B2EB1FA /* ControlProperty+Driver.swift */, + 03CAC0BE6778E17AEE82829B73CFE34F /* ControlTarget.swift */, + 64B8AAF028420A2370690C9C868E9514 /* DelegateProxy.swift */, + 4C2E5505F6F6A3594BDBB66B1DCD2769 /* DelegateProxyType.swift */, + 29B1B7B244B0253C248351A34368BD45 /* DispatchQueue+Extensions.swift */, + 9B74AF3B54FBE109EB58A9D28762BE51 /* Driver.swift */, + 822E3D722F17EB3AF1D5F0AEC7E5CADF /* Driver+Subscription.swift */, + 40281A10694C95424518F246D0F1B9E3 /* Infallible+Bind.swift */, + 3C3CED74C2352634FFCCBF22DD716882 /* InfiniteSequence.swift */, + 693D5828BB933F59E948083F7EAF0754 /* ItemEvents.swift */, + E49C4101B06D09B0670CAA5BE93F2101 /* KVORepresentable.swift */, + F6453BF98D49C0179F6FB62D15AB8577 /* KVORepresentable+CoreGraphics.swift */, + F0E0D9AD1AEDD0834A8A02649DECA298 /* KVORepresentable+Swift.swift */, + B4D9A55B60B97A971CA56B8A6B8E61B5 /* NotificationCenter+Rx.swift */, + 1F52E08AC945B9B081C5AECB2D4570D3 /* NSButton+Rx.swift */, + 15F42CF91B11E49FD5E0A9C5D71E3D1E /* NSControl+Rx.swift */, + 48E1C71FAD56AC66CA256D8B5D952C16 /* NSObject+Rx.swift */, + 3279EA9AD5D4A54540E377F973965A63 /* NSObject+Rx+KVORepresentable.swift */, + ADEE96E8C029C202DA706F1269584A45 /* NSObject+Rx+RawRepresentable.swift */, + F9E2BF9DFC6C02DC2152D00A85787A2B /* NSSlider+Rx.swift */, + 2AE4C07C0E4F8BB1308A67E29DEDB0F4 /* NSTextField+Rx.swift */, + EBEB130BD704B0C5130C4F805B724932 /* NSTextStorage+Rx.swift */, + FCB055F55762E3DAC2DF05014739D6A4 /* NSTextView+Rx.swift */, + C9B8857FCB950426B60F8110D84C1AC4 /* NSView+Rx.swift */, + 76C139ACE15066DF7A8CBF8A0575DCE8 /* Observable+Bind.swift */, + C913AE49B5DF5454F9459CB36E6CA8EB /* ObservableConvertibleType+Driver.swift */, + FB4645A6E0537F17A5B8C5893424C888 /* ObservableConvertibleType+SharedSequence.swift */, + 357CED460E06EF4C7E0754EAC799EA25 /* ObservableConvertibleType+Signal.swift */, + 1C0343E12CDBD4EB4F143FAB1B9C5B50 /* Platform.Darwin.swift */, + 6536D1A3AA8A85023DC9EB6423385510 /* Platform.Linux.swift */, + D592E632CF9AA82F2DDE3C8C185C7D6B /* PriorityQueue.swift */, + 33D725EA40F13C08F36A24B9E06F4E0B /* PublishRelay+Signal.swift */, + DAC809D021BADB863C6366F88736744E /* Queue.swift */, + B1C8536CD5EEA7448B5B8AFA116E6AE4 /* RecursiveLock.swift */, + 9D43AE76EB42DD34137D60B072365019 /* RxCocoa.h */, + E9D61CA24837D23444AC17D5836E6548 /* RxCocoa.swift */, + 51710E6F5CDA4441327AE37E1D64A62D /* RxCocoaObjCRuntimeError+Extensions.swift */, + BCADE0A5DD41C1CFA84326E28BA08D0C /* RxCocoaRuntime.h */, + 8748D0DB8153052544C8742B25C8619D /* RxCollectionViewDataSourcePrefetchingProxy.swift */, + 2FF2B70AFEA833EA39A3F259BAFC3B0D /* RxCollectionViewDataSourceProxy.swift */, + BA2BAD104F63EA5D8CF3DF2BFBB5B852 /* RxCollectionViewDataSourceType.swift */, + C0E167C7E239F77C09B30A1B1BFD6A6A /* RxCollectionViewDelegateProxy.swift */, + 6EB5CB57ECB22669866D6AF3FAE88655 /* RxCollectionViewReactiveArrayDataSource.swift */, + CAAB78B8DEFFFA4EE62B77E879B0C0C6 /* RxNavigationControllerDelegateProxy.swift */, + 449F164ADAF01D26FCA0CCF5FEBC8092 /* RxPickerViewAdapter.swift */, + 24583429FDC6518EBA768A112CAACD99 /* RxPickerViewDataSourceProxy.swift */, + 6554D2462B773751507D2561D0429059 /* RxPickerViewDataSourceType.swift */, + AE89C8A29E610492DC15D221F7BB17EF /* RxPickerViewDelegateProxy.swift */, + 859FFBDE9607E4C6AB22EFD8E96505A5 /* RxScrollViewDelegateProxy.swift */, + D92259428C053D17FB1662BE8F4C5AB0 /* RxSearchBarDelegateProxy.swift */, + 60D8162FD7345FD61DA97E075041A37B /* RxSearchControllerDelegateProxy.swift */, + 029ACF334268DD6E08782744E5E583B1 /* RxTabBarControllerDelegateProxy.swift */, + AEC2726887ABD33AFCEFD85345582ACB /* RxTabBarDelegateProxy.swift */, + F586CD775793113152D995CE9D789F97 /* RxTableViewDataSourcePrefetchingProxy.swift */, + CDBDCC4538898CA2A08F40F3200FA34B /* RxTableViewDataSourceProxy.swift */, + 127E27FD04D13F2FFD7E2365153EB850 /* RxTableViewDataSourceType.swift */, + 6613A2AD11F440C53FFC2EA71865D23E /* RxTableViewDelegateProxy.swift */, + FF0655088DDF1DB2A8A3E4A1C172991E /* RxTableViewReactiveArrayDataSource.swift */, + 0D22E2519CEAF1998AFE01A72B8C340A /* RxTarget.swift */, + 7D732BA10187D09CADE70C3677839C01 /* RxTextStorageDelegateProxy.swift */, + 45B1BCE02DC2388F30FBDBF9DB7EA27F /* RxTextViewDelegateProxy.swift */, + A0685B997231AAB114364A3E6B1FD607 /* RxWKNavigationDelegateProxy.swift */, + 0D2E5604E8A78A3AE6B8C2C88A765F06 /* SchedulerType+SharedSequence.swift */, + 90FDABF3938FF99C7EC73D7B2E4D59FB /* SectionedViewDataSourceType.swift */, + D45D06B40D5FB020BB5498EDE9146C96 /* SharedSequence.swift */, + 95B6C010BFBF729113881E2867C2A4DE /* SharedSequence+Concurrency.swift */, + 8FDE66F4BC83BF2EB6189F7D5567F8D5 /* SharedSequence+Operators.swift */, + 560DCBC2941D96B8B2EB9C2A2728D79B /* SharedSequence+Operators+arity.swift */, + AD5AFD8EB6E9537884257E4F1C42F8B1 /* Signal.swift */, + A886D886268384F906A6A2155C50E9FD /* Signal+Subscription.swift */, + 9DDFA8FDE05F071E9CB3CFFD7D1198AF /* TextInput.swift */, + D2CBF621C3C27D36361AA1E26D1F30EC /* UIActivityIndicatorView+Rx.swift */, + F56E65F457FF030938F76858DC819B98 /* UIApplication+Rx.swift */, + 06F1307E057BB52BBE74D77F011C13AE /* UIBarButtonItem+Rx.swift */, + D96B4C2B995A47D34B2F206E566FAA48 /* UIButton+Rx.swift */, + CEFC74A4645C52AF239D907E90151564 /* UICollectionView+Rx.swift */, + 8E1C9087459E2A949E79028C67877E46 /* UIControl+Rx.swift */, + 4279D69741987540D0F56531AE01ABC8 /* UIDatePicker+Rx.swift */, + 86C0D14AAB2AAD0385245B785EA851F7 /* UIGestureRecognizer+Rx.swift */, + 66206B9155CD697680CDD63E69552C73 /* UINavigationController+Rx.swift */, + 1D80F36289073915F26ABAEA35BD714C /* UIPickerView+Rx.swift */, + E08CBB4AA59577D9B90F839FADB5B1B1 /* UIRefreshControl+Rx.swift */, + 4DB527180CF7411F64A3ADCAEB4C3840 /* UIScrollView+Rx.swift */, + 717C05410FB264842860E5EE81C2A9FF /* UISearchBar+Rx.swift */, + 4E5190BBD5788742C6338758F6BE977A /* UISearchController+Rx.swift */, + C5193DE9E3B442CA0110473C426592C5 /* UISegmentedControl+Rx.swift */, + 8ACEED6A92C605A5B1876A7C7D739E7F /* UISlider+Rx.swift */, + 99E955E7BAAB58DBCD9038D19F4B5AD3 /* UIStepper+Rx.swift */, + 16669C5C88E94E1D44FD7DC175608B70 /* UISwitch+Rx.swift */, + 7C29A6CB0B11367EB927BDE743C42AAE /* UITabBar+Rx.swift */, + CEEA3119C2BCD2D17617CA0D51444126 /* UITabBarController+Rx.swift */, + 22F0E7B9E39A41E1992AB24925CDA083 /* UITableView+Rx.swift */, + DDD59AB6E70B0DC2C150D58C0919F3A9 /* UITextField+Rx.swift */, + 48FA0A5D99CA478DCAC3D6AA4F0BC343 /* UITextView+Rx.swift */, + 8F8B1C43AE360FF396F257FB7C94FDC1 /* URLSession+Rx.swift */, + D82E05E5FDF3DB13CC8C3F30B72A4691 /* WKWebView+Rx.swift */, + 438EC45761C2FC2E01D68DA9F479BDC7 /* Support Files */, + ); + name = RxCocoa; + path = RxCocoa; + sourceTree = ""; + }; + A508DEE091E9906DD82B1623C754D882 /* Support Files */ = { + isa = PBXGroup; + children = ( + BCD53B5B06599985FA89579262B41DC3 /* Then.modulemap */, + 609F4B4729FA21AA97F7492A1833A37F /* Then-dummy.m */, + 82841F9D4BF64720F984684A48A9DE3E /* Then-Info.plist */, + 2F8F216EF495C675DA9C3CD40CD8FB7D /* Then-prefix.pch */, + 5FF06DB04BE117F1E668EC5B610784BF /* Then-umbrella.h */, + 1B5E3F734AD887EDA517B37DBE5936B2 /* Then.debug.xcconfig */, + A377A735091D700527D978D7E7CF36CD /* Then.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Then"; + sourceTree = ""; + }; + A6B44FA36A70D38081D48AFC33C6F326 /* Support Files */ = { + isa = PBXGroup; + children = ( + 8396FF1BD2ED3EDFD9A22B02B98B8602 /* RxSwift.modulemap */, + A9C24B3F6BCE4CFFC79D6D04A8CA4BD8 /* RxSwift-dummy.m */, + D2190511B07DED7D99673E56238DAC2D /* RxSwift-Info.plist */, + EFD0B757EB0E416B72363ACA30B7ACE3 /* RxSwift-prefix.pch */, + 648ABDA4F57CCFFCCA2E35A67A86EC81 /* RxSwift-umbrella.h */, + 247A3B30DFF905EA0A027E44FFDFC16E /* RxSwift.debug.xcconfig */, + 9F701B3583B6D6A3A47DC899C241FED9 /* RxSwift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + B10172C5620C6818265C98BD80E1AD57 /* Resources */ = { + isa = PBXGroup; + children = ( + 23378430FBA0F2A76F6D502BD6EB0BE8 /* PrivacyInfo.xcprivacy */, + ); + name = Resources; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 1628BF05B4CAFDCC3549A101F5A10A17 /* Frameworks */, + 9DA662C9AD7BAE1AAF2417A523D91AED /* Pods */, + 239D13D9E3DD8B316233DC34EB7233DA /* Products */, + 2948E91ADB71D1F2B6E3DBAB0DEBE072 /* Targets Support Files */, + ); + sourceTree = ""; + }; + D32F1CD76691808B840A6F6CE1840DDF /* Support Files */ = { + isa = PBXGroup; + children = ( + 07A1828624A230EAA59435008992BB8D /* RxAlamofire.modulemap */, + FFAF002049961423F31CDABAB1A70EB5 /* RxAlamofire-dummy.m */, + 1D6C875FAFBA5D8A03FACC057BF76588 /* RxAlamofire-Info.plist */, + 12D85D660A383DAC2F0A428AF7C324E9 /* RxAlamofire-prefix.pch */, + 9E58FF48ED163CB55597E534C20E56B2 /* RxAlamofire-umbrella.h */, + 01E338C96A64806AD5F7BC07C1F70508 /* RxAlamofire.debug.xcconfig */, + A1FCEE06CE8D7B2AFE2BA9986718C750 /* RxAlamofire.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxAlamofire"; + sourceTree = ""; + }; + D91E7ACFCBCE44A6019606EBB97EA283 /* RxRelay */ = { + isa = PBXGroup; + children = ( + BADC91F4D42F59A8002D134BBD2701F9 /* BehaviorRelay.swift */, + F14D3772A585D66A164FAAA5400B93C2 /* Observable+Bind.swift */, + 3F55EB8DF2BC73493BDA426C5D5FBB38 /* PublishRelay.swift */, + AB1066583F16C904E8CC5ECDBC6DD7F8 /* ReplayRelay.swift */, + C3AAC8A11121C5761C45996057A91DA7 /* Utils.swift */, + 39E28C59438097898E1DAE60CC7D3AAA /* Support Files */, + ); + name = RxRelay; + path = RxRelay; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 0C9ED7F80C58C162BDF0D2A96D8615F6 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 28B20C35F4E1B3DDE716C831B049ADBC /* _RX.h in Headers */, + 543824E1170EF49570C40DAE54604F21 /* _RXDelegateProxy.h in Headers */, + 4251CDB971A8B94270E34381974BC9F8 /* _RXKVOObserver.h in Headers */, + 69657DEC11BB7E4F9F5B6DE8E1148B3E /* _RXObjCRuntime.h in Headers */, + 9A151985A3D24023E8B2996BF3EBA2BB /* RxCocoa.h in Headers */, + 557AE7547352CEA86AEE5518CC1A503E /* RxCocoa-umbrella.h in Headers */, + 45F6BA1117D64D98B32E0C77670EF906 /* RxCocoaRuntime.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4DB0EF6CEAD3071A142D5892E127A13E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DDDDE4944E4F58779DCE4F9D13C3C3D6 /* RxRelay-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 555433B8A0FE35B16D9731C6CB86A899 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + CB944DCA1B4D8E929A4AC948A92B7303 /* RxAlamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A6B5D1764A95E7CEB3A264AE9B635C8A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 4A6FE838AC054F308C1EC5A8ED403008 /* Pods-ChatBot-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BAC2D8680E55166B734736C0B4DF2ACE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + C16CCA036FB752322954E1F6047D57C9 /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BD2B111EBF8A7845E42930BF05778C63 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D389E4D5F97798BE1AEEB8C317852D7 /* SnapKit-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D0482E511DA59C90F7DB62C353302CD0 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A892A3F92A4B151AD508CFCD080082A4 /* Then-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DB3F5EA19841D5A3486C9C9A020AA313 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 571142A2747CD90165F631A8AE980A0A /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4C4F25F04C086237315FCAEF7661357E /* Build configuration list for PBXNativeTarget "SnapKit" */; + buildPhases = ( + BD2B111EBF8A7845E42930BF05778C63 /* Headers */, + B52EB97EAADC4B42F512DF593D183539 /* Sources */, + 6F796DCACF7FECDF5C5CEF6AFE7BC0FF /* Frameworks */, + 8AFC96B9D49AC279B3790C99847FF1B3 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 2AA339C96F60D21C72D9475EA344A9BC /* PBXTargetDependency */, + ); + name = SnapKit; + productName = SnapKit; + productReference = 979486118B3E90C08386079D57962701 /* SnapKit */; + productType = "com.apple.product-type.framework"; + }; + 1A538A5499B1706F0983D6826042657B /* RxAlamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = F52E4AB8CBA3FFCD0B955722B49E8A01 /* Build configuration list for PBXNativeTarget "RxAlamofire" */; + buildPhases = ( + 555433B8A0FE35B16D9731C6CB86A899 /* Headers */, + C3F6FDA16E2D4FFF3DC83F1D8BB7BAAA /* Sources */, + 4D0CEDE610B1814B54BF5FB05DBC61A0 /* Frameworks */, + 8DC12BBCF616FB909C611769718B419A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 90665D8D706A61FE4B1BAF915DB22042 /* PBXTargetDependency */, + F92AC0077FF15AD9AEF0330D5246A591 /* PBXTargetDependency */, + ); + name = RxAlamofire; + productName = RxAlamofire; + productReference = 82F1475AA0F9C33F7EA4A1459305D2AB /* RxAlamofire */; + productType = "com.apple.product-type.framework"; + }; + 2336AF7E8F6779C0D1FAF85CA677B4BB /* Pods-ChatBot */ = { + isa = PBXNativeTarget; + buildConfigurationList = 231F44657D2D49D9C0A7A4B238111924 /* Build configuration list for PBXNativeTarget "Pods-ChatBot" */; + buildPhases = ( + A6B5D1764A95E7CEB3A264AE9B635C8A /* Headers */, + 770BB39B351A75C740D289D5E1F1AC3D /* Sources */, + 19E52EE8B50024F5B029EE655DDFF330 /* Frameworks */, + 65BBBF46BDF52EFC67711FFBA6102530 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 0E570A111627A0383BE5BDC57DBD6009 /* PBXTargetDependency */, + 5F437ED473134CA45885568FB8BA430C /* PBXTargetDependency */, + 06F4672486B9DFC2EADED95A17EECD79 /* PBXTargetDependency */, + 6C9C46E7B9FEFABB5B08E31449FF2FB4 /* PBXTargetDependency */, + 843578840CAFF66D287F682F79EEF365 /* PBXTargetDependency */, + B1BB387A3EDE65D0DDF20083F71AD923 /* PBXTargetDependency */, + 9FBB31D3D17680B3229BDA14DCA3E30F /* PBXTargetDependency */, + ); + name = "Pods-ChatBot"; + productName = Pods_ChatBot; + productReference = D907F5AF8F8C83891B2BBAE238EEDF4E /* Pods-ChatBot */; + productType = "com.apple.product-type.framework"; + }; + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */ = { + isa = PBXNativeTarget; + buildConfigurationList = B4BC34F594FC7791F66695A9E0AC12C9 /* Build configuration list for PBXNativeTarget "RxRelay" */; + buildPhases = ( + 4DB0EF6CEAD3071A142D5892E127A13E /* Headers */, + DCE9B867C0C49955CAA9A624906892CA /* Sources */, + 6F322A20F88D816DF7B97BF4CF8A39F9 /* Frameworks */, + 6E76F5CEECF3D01EC69E9EEF1503683E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 86E8265E7072A0D07F230B13DB76EC42 /* PBXTargetDependency */, + ); + name = RxRelay; + productName = RxRelay; + productReference = FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */; + productType = "com.apple.product-type.framework"; + }; + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1E42B460D55BA3EBE021004CC2CE312C /* Build configuration list for PBXNativeTarget "RxCocoa" */; + buildPhases = ( + 0C9ED7F80C58C162BDF0D2A96D8615F6 /* Headers */, + 3DA8F71AF3BF41150950832BA8D64BFE /* Sources */, + E877FC0D3719519B688F3E17FF0228B2 /* Frameworks */, + 5D4809C72FC4B366B262906F436A3EF1 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 05D1B6347CCB225B605DFEF8A367EA04 /* PBXTargetDependency */, + FAE6C81526E70219F29596FC822072E9 /* PBXTargetDependency */, + ); + name = RxCocoa; + productName = RxCocoa; + productReference = BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */; + productType = "com.apple.product-type.framework"; + }; + 8A8DB685241263AFDF5E6B20FE67B93A /* SnapKit-SnapKit_Privacy */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1D1AB428C97AEA54D7EC22E24323597B /* Build configuration list for PBXNativeTarget "SnapKit-SnapKit_Privacy" */; + buildPhases = ( + 904F4E3C09EA16DBA2EA2F1C5345AFEA /* Sources */, + 92A489FF3CED98B4EDAB0741F3306323 /* Frameworks */, + 1AE9ACC9C3D939BD202E957E0E55C1F5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "SnapKit-SnapKit_Privacy"; + productName = SnapKit_Privacy; + productReference = B9DCB5EC0B1CDADD221717CADDF62359 /* SnapKit-SnapKit_Privacy */; + productType = "com.apple.product-type.bundle"; + }; + 976126A1CE06DC6E162563800E1BDF14 /* Alamofire-Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = FC1E1E6045405857DBC6B878AF238235 /* Build configuration list for PBXNativeTarget "Alamofire-Alamofire" */; + buildPhases = ( + 3D6967FA54CFA003F6ABCAE318D87D9D /* Sources */, + 31E61577D868411A42FE876CF77E772E /* Frameworks */, + 0D159652B9B53BF32F73657B92C56A79 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "Alamofire-Alamofire"; + productName = Alamofire; + productReference = 085DBCE7DD98588B2ED103B1C1F36026 /* Alamofire-Alamofire */; + productType = "com.apple.product-type.bundle"; + }; + C17AEFC79E770A2906EFAAB1A3757406 /* Then */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9066CF256D5B92C1B2C5053115F4AC74 /* Build configuration list for PBXNativeTarget "Then" */; + buildPhases = ( + D0482E511DA59C90F7DB62C353302CD0 /* Headers */, + D9DF5AEE1B525A8BA763D0DFA7241A71 /* Sources */, + B110F4A89B80E9EA29019FC5CA16B326 /* Frameworks */, + 08C52A0B42B9DFC342690EC119C9DFCA /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Then; + productName = Then; + productReference = 9317E4947CA2FE1B5D5999034C09CCA7 /* Then */; + productType = "com.apple.product-type.framework"; + }; + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 7E7568C2596D611D56931D1635A0BC05 /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + BAC2D8680E55166B734736C0B4DF2ACE /* Headers */, + 3AD1BC5883CF776B0A1EFC0106FA2E9A /* Sources */, + 23B4B06C495089CE8C5BC43B115E6A5F /* Frameworks */, + 549BD814021C5F4D744A5081EEB6C637 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */; + productType = "com.apple.product-type.framework"; + }; + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = FA92BF783257A026FB1E05B4B536DD6E /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + DB3F5EA19841D5A3486C9C9A020AA313 /* Headers */, + E0C6F893D34CB935A73FBD4BD75299E5 /* Sources */, + A5C342523C3577E7122B4B43929BA8F3 /* Frameworks */, + 5CEFF03EE9A7B5D7514E35F3AD2A314D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + C1550B0652E5A5E3D6B17D869589673C /* PBXTargetDependency */, + ); + name = Alamofire; + productName = Alamofire; + productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1500; + LastUpgradeCheck = 1500; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 239D13D9E3DD8B316233DC34EB7233DA /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, + 976126A1CE06DC6E162563800E1BDF14 /* Alamofire-Alamofire */, + 2336AF7E8F6779C0D1FAF85CA677B4BB /* Pods-ChatBot */, + 1A538A5499B1706F0983D6826042657B /* RxAlamofire */, + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */, + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */, + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */, + 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */, + 8A8DB685241263AFDF5E6B20FE67B93A /* SnapKit-SnapKit_Privacy */, + C17AEFC79E770A2906EFAAB1A3757406 /* Then */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 08C52A0B42B9DFC342690EC119C9DFCA /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0D159652B9B53BF32F73657B92C56A79 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 68EFE2D24105AF72F6FB89F7C517D563 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1AE9ACC9C3D939BD202E957E0E55C1F5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 66F0BABA2924611DCE03722DD8C70691 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 549BD814021C5F4D744A5081EEB6C637 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5CEFF03EE9A7B5D7514E35F3AD2A314D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4F4B9DFA352D9958C7494D7BC24631D8 /* Alamofire-Alamofire in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5D4809C72FC4B366B262906F436A3EF1 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 65BBBF46BDF52EFC67711FFBA6102530 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6E76F5CEECF3D01EC69E9EEF1503683E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8AFC96B9D49AC279B3790C99847FF1B3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D091D9EA20CEB92609BF1E622E8CA348 /* SnapKit-SnapKit_Privacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8DC12BBCF616FB909C611769718B419A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 3AD1BC5883CF776B0A1EFC0106FA2E9A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9043DDBC3FF077FA99A6B84ED37FF5B3 /* AddRef.swift in Sources */, + 61FE62E6814C05CE7F0A45A2AC924A51 /* Amb.swift in Sources */, + 74E16C2EF9859BD51382E278FA2CA5C7 /* AnonymousDisposable.swift in Sources */, + B616C8E5078265366CA95C9444362299 /* AnonymousObserver.swift in Sources */, + C05F81983EC39D0814DCE11AD9DF225B /* AnyObserver.swift in Sources */, + B5CBB0B8314FB5E8CE1D0AF133CB4BC2 /* AsMaybe.swift in Sources */, + DA97AA043A435ED164636D7C796627B2 /* AsSingle.swift in Sources */, + 14A2DE0766AB513B0D321CF49386F8DD /* AsyncLock.swift in Sources */, + 34990DB4BE282AA7BEC367B2A21DBD20 /* AsyncSubject.swift in Sources */, + 183F4AFDEDD14DD0C1DCBF8483CD3EC0 /* AtomicInt.swift in Sources */, + 922AC6AF7A90CC9BF44AEF51A4938D95 /* Bag.swift in Sources */, + 4C51FF134747DF641E742FF87C68D82D /* Bag+Rx.swift in Sources */, + 091B0930115982BD92CC1D70D2A5BF21 /* BehaviorSubject.swift in Sources */, + CA72BC15AF30D94744BF51159C71553F /* BinaryDisposable.swift in Sources */, + E22F4170FF8A3C8A4305F8BDC9552E7E /* Binder.swift in Sources */, + C53EDBD3F6005B01E29A50BE765F50FD /* BooleanDisposable.swift in Sources */, + 10E361764348CA50879CDE3AEB5AF946 /* Buffer.swift in Sources */, + 7F5E49425D331C697D57E60DA02B8871 /* Cancelable.swift in Sources */, + 4E2A394AB9272D80EFC57512D1326B58 /* Catch.swift in Sources */, + D6739D499FC4C4C4A24F9487B651D6A9 /* CombineLatest.swift in Sources */, + FB9F07AFD07781E7EE473C23EF284909 /* CombineLatest+arity.swift in Sources */, + C54D40885EB2E2F67914570C646D216D /* CombineLatest+Collection.swift in Sources */, + 196C06A99C54F2907FCE69E594E5A00B /* CompactMap.swift in Sources */, + 34382B9F5C051B5F2A3E521C4CD421BF /* Completable.swift in Sources */, + CE52BD963045285270BE40A22D9D0CF2 /* Completable+AndThen.swift in Sources */, + 69745C24634579C0CB191EA54894DE63 /* CompositeDisposable.swift in Sources */, + C96C853D60B6AC78AC076E1193BCB9B2 /* Concat.swift in Sources */, + D7C02EADB2F327E5B74A5F2FC4D8605D /* ConcurrentDispatchQueueScheduler.swift in Sources */, + 12CCAB43B5D8AF62EB458BA947D9FC8D /* ConcurrentMainScheduler.swift in Sources */, + 10F10A61A6D185762AEF2ECBD30BDD41 /* ConnectableObservableType.swift in Sources */, + 986248DC617E2B972C64E15ABB23C737 /* Create.swift in Sources */, + C5A1A8CFFE40F903721BA7E4543C8EBA /* CurrentThreadScheduler.swift in Sources */, + 335DA9729DDCC2A2E86C484605B39A36 /* Date+Dispatch.swift in Sources */, + A72C92BAD53CAC6C4509E66A4A963164 /* Debounce.swift in Sources */, + 6298EBC46156D790A40C5D525D8BCCF3 /* Debug.swift in Sources */, + 18471091D8FB4CFBF4CF0B62D2FBDB90 /* Decode.swift in Sources */, + C5CD2F6F8BA07FF284ACBF0F4A2BEFBB /* DefaultIfEmpty.swift in Sources */, + A4BA514E9F3A3ED20E3BF8ECE83A0DA1 /* Deferred.swift in Sources */, + 9BA0BE27FCCABBBEABE945BAB46EFB7E /* Delay.swift in Sources */, + 82126B5F4739FAE8AB2D606924777273 /* DelaySubscription.swift in Sources */, + 7EE83FB2B30B2D7B4907C0E0EFC0D08D /* Dematerialize.swift in Sources */, + 4BE8D888F62311C302D0E3F3E38FA0FE /* DispatchQueue+Extensions.swift in Sources */, + E9EFE2594783B175CCA9E2F5C5E3D8C9 /* DispatchQueueConfiguration.swift in Sources */, + BF860092BECACCD23B6F6420E5AE0BE0 /* Disposable.swift in Sources */, + 7383111A52ACF20DC2BFDFA8FF1CD245 /* Disposables.swift in Sources */, + 5EB5C933162B0C6CA9EA70D9B41FF7C2 /* DisposeBag.swift in Sources */, + EB411C0C5F796794B3278016F3FA4E28 /* DisposeBase.swift in Sources */, + 8B8B57F35F62B111B5B3FB282895AFCF /* DistinctUntilChanged.swift in Sources */, + C0F89544C3BF7A670B44ED8A4F4F67B2 /* Do.swift in Sources */, + E3B95BD6FECF47BD76B10B0930CE03F0 /* ElementAt.swift in Sources */, + 91CE3762DAC54C69D81002DC4E844E32 /* Empty.swift in Sources */, + D04234BAA0FD845DB7F2BE5226BEBDC7 /* Enumerated.swift in Sources */, + 321DECDF554D08A2FFB5B9FCC8FC6C22 /* Error.swift in Sources */, + B6343A462D953EC3A9C7A7624C2E77E0 /* Errors.swift in Sources */, + 7B6F19F234DC858A8E1196F64D1C9A32 /* Event.swift in Sources */, + 4DEA4F5E8F6DA1DDA399B1BA9570D356 /* Filter.swift in Sources */, + 9569C9DA81619ACD1ADAE3EECE246C3E /* First.swift in Sources */, + D7BB9B5EC40F4BBEB3D3587F6CE1BBD7 /* Generate.swift in Sources */, + DCF67DD166A569F7663D87D7613F5A81 /* GroupBy.swift in Sources */, + 193CAAB846EDEDB62BBD22F61F64DC55 /* GroupedObservable.swift in Sources */, + 7F0A5844D1DD4C225D7914AB49F4764C /* HistoricalScheduler.swift in Sources */, + 837AEFE0DB5EF57DB35C9C6E29BBF7EE /* HistoricalSchedulerTimeConverter.swift in Sources */, + B1E2EE6C3296A1B2E79440800D431B8D /* ImmediateSchedulerType.swift in Sources */, + 487963200BA2F42138606F20D447A24D /* Infallible.swift in Sources */, + F3B517F56C11ADB67A5F42588A8B4219 /* Infallible+CombineLatest+arity.swift in Sources */, + D5AC68A26EC8E5548872DD8EC3A5CE8A /* Infallible+Concurrency.swift in Sources */, + 7B3D680ED2CDD36A46922B03C0031676 /* Infallible+Create.swift in Sources */, + 22F92D32F00189DC7B856E133736B0AE /* Infallible+Operators.swift in Sources */, + 418FC5C699A40AC43367B53199BAAB3E /* Infallible+Zip+arity.swift in Sources */, + D5A41118FE6AA9C5BF9D1F2ED254BFBD /* InfiniteSequence.swift in Sources */, + 5C2AA24533F5C397A3140A0F0764DBC8 /* InvocableScheduledItem.swift in Sources */, + 30883E7D247064BE76D27A675FAADD67 /* InvocableType.swift in Sources */, + 792B9812F1A39EECA4834C5036081DBA /* Just.swift in Sources */, + F3216E564106722FB415537C86BF54FB /* Lock.swift in Sources */, + C79DDAB5198263195D078C8B01DF1FFE /* LockOwnerType.swift in Sources */, + DA0EB35C2657F248A6CE170DBB8FEC63 /* MainScheduler.swift in Sources */, + A768976F84C9BBF5391E70284550A251 /* Map.swift in Sources */, + B0A8DE991100FB6054B886A847E78B7E /* Materialize.swift in Sources */, + C82125EACE158B19FA2CF0018BAFC0F4 /* Maybe.swift in Sources */, + 312652D3A84692893A71F7D98FFFB0DC /* Merge.swift in Sources */, + B7EC9CAD1C5FACDB56DCDCBAB98F6D74 /* Multicast.swift in Sources */, + D8F699E18D1A745F740D462C82CF8F7D /* Never.swift in Sources */, + 3FFF0A40BDF7932C8CEBA6589210E980 /* NopDisposable.swift in Sources */, + F13EF636FEE7C1F1C9942B5E7A02CDB1 /* Observable.swift in Sources */, + 852911F432575BD76E0EB72D4E696748 /* Observable+Concurrency.swift in Sources */, + 1BDB4F8DFAF5BA5C3ED782FFB3A6C755 /* ObservableConvertibleType.swift in Sources */, + B8A4F17E7667C0565DC91A856E57AC04 /* ObservableConvertibleType+Infallible.swift in Sources */, + D1D035C24CB13D5110CCA6C00A9E7812 /* ObservableType.swift in Sources */, + 80213844BD1825B4F74CA12206958A48 /* ObservableType+Extensions.swift in Sources */, + 47DF5E4B96F64623A02142740B54D05E /* ObservableType+PrimitiveSequence.swift in Sources */, + 4C55A60758D0C53AD5052463C9333227 /* ObserveOn.swift in Sources */, + AD80EA9EFE70F246ED0FDF92EC90AD0F /* ObserverBase.swift in Sources */, + DC567EB29336818EFE922AA49C244CB8 /* ObserverType.swift in Sources */, + E09EA7C05D6F7CE8A2BCC4351B5CA7F6 /* OperationQueueScheduler.swift in Sources */, + 3C0A2E4A387C34B462746390C6D61EE6 /* Optional.swift in Sources */, + 01F4CE6D9DCBC1325DB52474E6D857FF /* Platform.Darwin.swift in Sources */, + C39EFD5DC31C8D98E9ADB90EFB336C3B /* Platform.Linux.swift in Sources */, + B60181315C9F329E45A079B377960BBB /* PrimitiveSequence.swift in Sources */, + DA0BE77A7A651CA6CF552CFB76498A1A /* PrimitiveSequence+Concurrency.swift in Sources */, + E597135D1327F849825F6C787FCDA90B /* PrimitiveSequence+Zip+arity.swift in Sources */, + 364FBFE2AFBDA63FFC062E7A329D00E1 /* PriorityQueue.swift in Sources */, + 8E482ACFEE214E8473C95E359DEFD756 /* Producer.swift in Sources */, + 40E608508D38BE4E5A94993C39E0C64E /* PublishSubject.swift in Sources */, + 72E9834B8E1B3A3443B665C3D5244474 /* Queue.swift in Sources */, + E6763D63381C8B7F674990191EF2F701 /* Range.swift in Sources */, + 250F6EBE090607C5CBDBA8CA6627CD3C /* Reactive.swift in Sources */, + 4E0D848AC4FB40F7581A16576380E435 /* RecursiveLock.swift in Sources */, + 3F9271B2430E8B7F6F0F9507C5C22A6C /* RecursiveScheduler.swift in Sources */, + 8196BA923F2CD32C92584D499B9BF86A /* Reduce.swift in Sources */, + E1DF012617FAE80DB7AAAAD80FB35810 /* RefCountDisposable.swift in Sources */, + D02814A36ADDAFE6CC2B1EF4DCAD7FEC /* Repeat.swift in Sources */, + 1D96D59ADA0DE50FCAC9E22B0BF00BA8 /* ReplaySubject.swift in Sources */, + 22D947BE5DFBE8BD471A215F9EF26183 /* RetryWhen.swift in Sources */, + 7EFCB3392E3997F1F6479F2F01053281 /* Rx.swift in Sources */, + 103F1A8C3CF6BEECD11E01B05C5BE726 /* RxMutableBox.swift in Sources */, + A6D42E6DD51B7F0AB95F5AF0BE74061B /* RxSwift-dummy.m in Sources */, + 0CB47ABA6CF2F336790A6ADADC98FBCA /* Sample.swift in Sources */, + 9FF1035938822A5C24626E11825B7BA9 /* Scan.swift in Sources */, + 2CEEECD91A44E33E3A3241FD38E3DAF5 /* ScheduledDisposable.swift in Sources */, + 2061A178B7AB446FA752910F59FEA8C4 /* ScheduledItem.swift in Sources */, + 7CF8F7E1130D35E43F09D4D9995E016E /* ScheduledItemType.swift in Sources */, + 3D367323A56C61E6B7F8D37265E2A08E /* SchedulerServices+Emulation.swift in Sources */, + EF66D3C7A616CA086085ECF4293AED68 /* SchedulerType.swift in Sources */, + A8A43FF9F100533C09FEF2BEC0F12BDA /* Sequence.swift in Sources */, + CBD71EAFFBA54C97123839A8EA5A9B85 /* SerialDispatchQueueScheduler.swift in Sources */, + E191C07587A61250ED02EED7C768F167 /* SerialDisposable.swift in Sources */, + 9A92CFEF51236FA54EB5604F1AC4D2B3 /* ShareReplayScope.swift in Sources */, + 4F2BD19DADB87C8174B6D1FB40B17537 /* Single.swift in Sources */, + 68127CAEDD4B253D26A3755302864FFE /* SingleAssignmentDisposable.swift in Sources */, + B71010996CEFF96476C9B95FCD9B0B78 /* SingleAsync.swift in Sources */, + 79FD300B87DA0ECE0491CAD22FB82C89 /* Sink.swift in Sources */, + 9984D50CE2B652B71A147BAE98FAFCF8 /* Skip.swift in Sources */, + A5B4E3C7D3A6182FA7C41B3E87921DEF /* SkipUntil.swift in Sources */, + 42344E73EA15C26857ACC338F3513C3D /* SkipWhile.swift in Sources */, + A9CFC858DF241092F03917C50BB86C16 /* StartWith.swift in Sources */, + 83F203FD35D282C29A03F28DA563C5D8 /* SubjectType.swift in Sources */, + 7D90BC34596D47F2A6B2C284CAC4A61F /* SubscribeOn.swift in Sources */, + 77409BB479A1C736C8614F9759218F85 /* SubscriptionDisposable.swift in Sources */, + 2D753CA94C0B51687DF83A74A014F321 /* SwiftSupport.swift in Sources */, + A96859B67A721D5D6FBE1743278074F9 /* Switch.swift in Sources */, + 3D88F3F5D413F6F8ED92C21BC2B16D68 /* SwitchIfEmpty.swift in Sources */, + C213B88476DC058A3D6F66FC48D2997A /* SynchronizedDisposeType.swift in Sources */, + 58BBB00C541E40923CEA876909C4EDA7 /* SynchronizedOnType.swift in Sources */, + F75490D19F11ED1416851A08B5B9BAE9 /* SynchronizedUnsubscribeType.swift in Sources */, + 542616E3D85E7777022D0AEF9FF6E377 /* TailRecursiveSink.swift in Sources */, + C07EDF0AA1783AF71B9AD7D6E4358F00 /* Take.swift in Sources */, + 7572216542D51908ECCB3B1AFF53B758 /* TakeLast.swift in Sources */, + E4ECC8CEF025558337BFE6C253E1978E /* TakeWithPredicate.swift in Sources */, + 1813B9F519EF0C8FC86FBA1FA8E6CA77 /* Throttle.swift in Sources */, + 66B4B08C5A78D74C5B0651F09C499BEC /* Timeout.swift in Sources */, + 34AD4108D936C4D7FEAE17C66067A6E4 /* Timer.swift in Sources */, + FED2CCFCF5AAAC005EF2433AE5CE1140 /* ToArray.swift in Sources */, + E22FE301DD72E4B55C97E0BC1FEA333D /* Using.swift in Sources */, + F3DD3662056E91B939B7EF29104F28F7 /* VirtualTimeConverterType.swift in Sources */, + 6AECF90899DF432E8E89F101340111C6 /* VirtualTimeScheduler.swift in Sources */, + 04A54AC2721CD67A178C2C922C6A798B /* Window.swift in Sources */, + AE2614A1E163FFE957DFA5F87B284570 /* WithLatestFrom.swift in Sources */, + 80594A8E265328F6320F5C3AA6375477 /* WithUnretained.swift in Sources */, + 4877B1401025AA36C5A2F291B02809AC /* Zip.swift in Sources */, + F1DB0A012011FAF9188226D6CF1D82DD /* Zip+arity.swift in Sources */, + B79C23BFEADABBEF33F16E7A7A442D7F /* Zip+Collection.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3D6967FA54CFA003F6ABCAE318D87D9D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3DA8F71AF3BF41150950832BA8D64BFE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 426C76C68C9FA3582F26BBB9E96316E4 /* _RX.m in Sources */, + C2D4FEEAF01038DB5C31CA401C105476 /* _RXDelegateProxy.m in Sources */, + F60E2B85B28D1E27FD52F9B0D62A50C8 /* _RXKVOObserver.m in Sources */, + C12DCA02D36C5C6167F566AFC96A6057 /* _RXObjCRuntime.m in Sources */, + 8A8AD24A8CE75FBE807EB5A9FC11E62A /* Bag.swift in Sources */, + FE9261A1344AF922C1EFCB457B938425 /* BehaviorRelay+Driver.swift in Sources */, + 1CC3FBF38E35B664C2A003664C58E2D7 /* ControlEvent.swift in Sources */, + 47D3FBF90386DABCAB70AA2CA176C8EB /* ControlEvent+Driver.swift in Sources */, + F3B4A826460EF6A9B19849D1E7AF6A52 /* ControlEvent+Signal.swift in Sources */, + 0907413AF1BF312948C6CA8289CE29AE /* ControlProperty.swift in Sources */, + D6FDE9DFAC4AA548A9A4E2D6BBCE54FC /* ControlProperty+Driver.swift in Sources */, + 81148E8E0935476F92B10881A023D0DC /* ControlTarget.swift in Sources */, + B3167FEDC691D1DDF267F855CFF33636 /* DelegateProxy.swift in Sources */, + 567E2B1BAE575E6556A2E57191BA2DA7 /* DelegateProxyType.swift in Sources */, + CF32140300489AD5D6D5A74E4605FDAF /* DispatchQueue+Extensions.swift in Sources */, + 0B5BB08F1937AD6324F0ADDD8F9E067B /* Driver.swift in Sources */, + BA5658B6C27A81FA4665E507A1ED88DA /* Driver+Subscription.swift in Sources */, + 6927E0A61FCF762B43C75325110C3D77 /* Infallible+Bind.swift in Sources */, + D3AB490FA372E1922315D4F2E5709254 /* InfiniteSequence.swift in Sources */, + 377229136C0061FE2FABE71862C2070F /* ItemEvents.swift in Sources */, + C784A7AAD94DD830A9EB5ADDEE6DE1BB /* KVORepresentable.swift in Sources */, + 5230B70A7B448918B83D3B983533D29A /* KVORepresentable+CoreGraphics.swift in Sources */, + CE08483A41A5535019BE5E198792480B /* KVORepresentable+Swift.swift in Sources */, + 5A3DE5038C0E8C2BAFC3316589D0F918 /* NotificationCenter+Rx.swift in Sources */, + B59095D5EF330419B3ADFBAD7EBC2B1F /* NSButton+Rx.swift in Sources */, + BAD3834746DAB3C038417D16101B29A2 /* NSControl+Rx.swift in Sources */, + BB72FC9215BD907A82AE928782813D6C /* NSObject+Rx.swift in Sources */, + 2087DD8278E2FC32F75C947E058EA423 /* NSObject+Rx+KVORepresentable.swift in Sources */, + 96F9E4762C05BF7B009FA52FC18C18C5 /* NSObject+Rx+RawRepresentable.swift in Sources */, + F2DDF679DF721DDA14A53744DD540092 /* NSSlider+Rx.swift in Sources */, + 5A39F3F258372FA025F08ECAFFFCF71D /* NSTextField+Rx.swift in Sources */, + D2004A03ADD62CD0C4649710F32A91F5 /* NSTextStorage+Rx.swift in Sources */, + FCD9660A73D7E00EA19E2F2295876E04 /* NSTextView+Rx.swift in Sources */, + 6DB19BEE9C42CBE8101A114524B38CE7 /* NSView+Rx.swift in Sources */, + F9821B669566BA01F845426DC6834E76 /* Observable+Bind.swift in Sources */, + 55713DE36F28B0D078ADAD60D5EE7FF4 /* ObservableConvertibleType+Driver.swift in Sources */, + 4F315C18FC854325DD5D062DD7A363D5 /* ObservableConvertibleType+SharedSequence.swift in Sources */, + D47B1058991EEC007A109B8E354EDB80 /* ObservableConvertibleType+Signal.swift in Sources */, + 2662EA3D1400EC4BD90947902CD85670 /* Platform.Darwin.swift in Sources */, + A0208B623442A26CB9157F193CBB4A7F /* Platform.Linux.swift in Sources */, + 6F803B4767FE50C12E3F0402DC0A3BE5 /* PriorityQueue.swift in Sources */, + 275C15979C1EC7DB6234974758037906 /* PublishRelay+Signal.swift in Sources */, + 72EE3F69E6154EF5C5524DE4F4EE0B5C /* Queue.swift in Sources */, + 2FCCAB4BA1D71EDB993309159D5DFA7C /* RecursiveLock.swift in Sources */, + 263A6B3B9C8592FC16697D2AB6333AC9 /* RxCocoa.swift in Sources */, + 18211EE7B495AA06EBBED1D6FD9423C0 /* RxCocoa-dummy.m in Sources */, + 84AEE29F4E7DDA962C49D6FAC6044EBC /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */, + 72FCE0D3F5EA7EB908C108DFD468B267 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */, + B5ACECCDD52AF69EBA2E11666BBAEB42 /* RxCollectionViewDataSourceProxy.swift in Sources */, + 7BA5D9B38DAEDD6A5166ECF2A498D194 /* RxCollectionViewDataSourceType.swift in Sources */, + C6A1AF1239CD2F0D4745BAA097E1E63F /* RxCollectionViewDelegateProxy.swift in Sources */, + 9F370B3928A333AD7E41680A29B1F051 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */, + 6DFB5C921332D5E14BF251A5ADA46473 /* RxNavigationControllerDelegateProxy.swift in Sources */, + 111810B8652D290C58076B92FCE40A1F /* RxPickerViewAdapter.swift in Sources */, + 782082D9F5529E63F249E8811BA6FD10 /* RxPickerViewDataSourceProxy.swift in Sources */, + 61EB40AB5F1BB5E6FDC8C5CDE06C3DE9 /* RxPickerViewDataSourceType.swift in Sources */, + EA5FE4B4B3BF04976C37430E4F3721EF /* RxPickerViewDelegateProxy.swift in Sources */, + ACA3DBC73A19F3CDF9C4FAB09988D0E6 /* RxScrollViewDelegateProxy.swift in Sources */, + 7C9C0D2AB5BB6670928CC95B4DA46814 /* RxSearchBarDelegateProxy.swift in Sources */, + A93FC5BCB5B02182D27377A3724A60B1 /* RxSearchControllerDelegateProxy.swift in Sources */, + 07550E0A8451CACE9593873C543F1B78 /* RxTabBarControllerDelegateProxy.swift in Sources */, + AAA7A11591D6E4B06124708291C37698 /* RxTabBarDelegateProxy.swift in Sources */, + 2EFF6DCB0FC66EB564B96A35840D5016 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */, + 1787EBB3723875770997006509209EDD /* RxTableViewDataSourceProxy.swift in Sources */, + 3EFE8454C7301C05A00EC9870F47968B /* RxTableViewDataSourceType.swift in Sources */, + EF6DD06709E5EFD67031FF9B5901A827 /* RxTableViewDelegateProxy.swift in Sources */, + CB3ACAC0625702DEC5BBB5F9AC0CC737 /* RxTableViewReactiveArrayDataSource.swift in Sources */, + F5AF27692F3A5C9087F015B5C40A35E7 /* RxTarget.swift in Sources */, + 3A379670D0CFBC0FCC9D0F66E944D074 /* RxTextStorageDelegateProxy.swift in Sources */, + 114F6342633413C8BBEC4169F34CFAFD /* RxTextViewDelegateProxy.swift in Sources */, + B3F14F1B196B5858BD951366FA89FA6D /* RxWKNavigationDelegateProxy.swift in Sources */, + 6BDA2BC21E394076C2E58E9269F4AABD /* SchedulerType+SharedSequence.swift in Sources */, + DE71610B229DF6E2B65A8574BAF21414 /* SectionedViewDataSourceType.swift in Sources */, + 9E8BA4FB802EDCD492DAF618CA7BFCE8 /* SharedSequence.swift in Sources */, + 768A33DCEB41CBC5C7ECF5F0220B1A97 /* SharedSequence+Concurrency.swift in Sources */, + FAF7C9C4F9B6AE2CE9F5866B210D9275 /* SharedSequence+Operators.swift in Sources */, + 9ADE1DD7C6AD8B57FD158350A66EF8D0 /* SharedSequence+Operators+arity.swift in Sources */, + 27F2BE5D6E990841E8DA1DF91CF3623B /* Signal.swift in Sources */, + 1F64C124283555FF5E1944FA37501247 /* Signal+Subscription.swift in Sources */, + 24C8FC3B11676AD57F3A7914E6621AD0 /* TextInput.swift in Sources */, + C378AC3DF57A41F6F16D01BBD7A1BB02 /* UIActivityIndicatorView+Rx.swift in Sources */, + 252B64A12E2810921E86B78ECD5BDA9D /* UIApplication+Rx.swift in Sources */, + BBD437FE6BFF63452E6B7E08DFAB4DD9 /* UIBarButtonItem+Rx.swift in Sources */, + 961B5042F0BFBD2C5FCDCCF40E2EA7CD /* UIButton+Rx.swift in Sources */, + A214A653E430C9079AA7B1090169262D /* UICollectionView+Rx.swift in Sources */, + 371CD58570B89DE6A3090CC6CE16AEE7 /* UIControl+Rx.swift in Sources */, + 2AC794BEBE17BA6257A13065584EC5DF /* UIDatePicker+Rx.swift in Sources */, + D4933D17DC286C3DABCFD930BED56DD9 /* UIGestureRecognizer+Rx.swift in Sources */, + 1F6F0B8C1A8EA633EFEBE64EB781A6B5 /* UINavigationController+Rx.swift in Sources */, + A20321979D272B922CD60B531BD05F7F /* UIPickerView+Rx.swift in Sources */, + 660E73ECB1E50185B9D21BAA127DC3A0 /* UIRefreshControl+Rx.swift in Sources */, + D3BC528010D39EB2D79585A671FD80B6 /* UIScrollView+Rx.swift in Sources */, + 057D0EC1E728D714A73210ACAF1FAC6A /* UISearchBar+Rx.swift in Sources */, + AB88D7A71BA82D3BAF097C992BFB221B /* UISearchController+Rx.swift in Sources */, + 90585B3B5526DB8ECBD1AB8EF2C4D5A2 /* UISegmentedControl+Rx.swift in Sources */, + 608DC0C8110DDFF5D8E5A43BB48A6A86 /* UISlider+Rx.swift in Sources */, + 419A11A8F7797E02FA5AAC6D8B4B3C2F /* UIStepper+Rx.swift in Sources */, + 654D9C29A846E7ED4DD5BF0BFC8D64B8 /* UISwitch+Rx.swift in Sources */, + 3EE7A29FCEE9B2A257B977E7137BC44C /* UITabBar+Rx.swift in Sources */, + 5435E924E7CE7B05B7F650C078A12F5B /* UITabBarController+Rx.swift in Sources */, + 8AEE5B74A5BAC274D6589F229D867768 /* UITableView+Rx.swift in Sources */, + B00B8088EB50EA3F0F875993C675F421 /* UITextField+Rx.swift in Sources */, + 14CAA40442778EFE3DF8B07CE170CAF7 /* UITextView+Rx.swift in Sources */, + F7774F70F3F7CD7E11F01BD8B62FFF15 /* URLSession+Rx.swift in Sources */, + D2C293D847E95B01671EB3E6A32F11C7 /* WKWebView+Rx.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 770BB39B351A75C740D289D5E1F1AC3D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 91D1A6B6C16D21E2FD1BFBA9F8785A7A /* Pods-ChatBot-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 904F4E3C09EA16DBA2EA2F1C5345AFEA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B52EB97EAADC4B42F512DF593D183539 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B133BB9C9B03481C7F1D221F35A617F2 /* Constraint.swift in Sources */, + 9779D52AD8CDA703D6EEE1C6D38E019F /* ConstraintAttributes.swift in Sources */, + E94B31DCAF75D93405D3BAE188604EB2 /* ConstraintConfig.swift in Sources */, + B3F75D115D5150C258F5E68404751010 /* ConstraintConstantTarget.swift in Sources */, + A051999781E1280746F7743BDEEA6C49 /* ConstraintDescription.swift in Sources */, + BE355F69F84788D334FDAC7D1CD9B8C4 /* ConstraintDirectionalInsets.swift in Sources */, + B4F9C9EC1B3F1689AE56BB719AE5439C /* ConstraintDirectionalInsetTarget.swift in Sources */, + F366D04DEA0EBBCA9CA4F1F4E29695E8 /* ConstraintDSL.swift in Sources */, + A0371DF7D93D9B86BD50474D4B9294FD /* ConstraintInsets.swift in Sources */, + 7052944C657F270E47777446D0E10E1C /* ConstraintInsetTarget.swift in Sources */, + 906EF891E58A035281766993F82373E3 /* ConstraintItem.swift in Sources */, + 0A5C290276F7453D9471E25BEA655842 /* ConstraintLayoutGuide.swift in Sources */, + 938CFF5F6DE6E7E8CE94373E51F3E07A /* ConstraintLayoutGuide+Extensions.swift in Sources */, + 0DA9A9D2F8960818017E26DA480FA143 /* ConstraintLayoutGuideDSL.swift in Sources */, + 13CC0CFB1C56F23BBC872801F983C1A3 /* ConstraintLayoutSupport.swift in Sources */, + D92AEF78B87F929D88D5C876ABBAD79A /* ConstraintLayoutSupportDSL.swift in Sources */, + 8640829049AE9907FE93825E5510C33D /* ConstraintMaker.swift in Sources */, + 0AD7A0DA8FF5880E3D8599062129AB12 /* ConstraintMakerEditable.swift in Sources */, + 6431218578A566C5EBF5FD166F164059 /* ConstraintMakerExtendable.swift in Sources */, + BF567AEFDD52DC43AC75122734D571E2 /* ConstraintMakerFinalizable.swift in Sources */, + 87996D11DC92EE19EAF9305DAEA4ACF2 /* ConstraintMakerPrioritizable.swift in Sources */, + 950B809760A8CE4375DCE1016FB9859F /* ConstraintMakerRelatable.swift in Sources */, + 15F68E09ADCDB843B938C490059485BD /* ConstraintMakerRelatable+Extensions.swift in Sources */, + 50E4E24710A4C5A77BE6594A10DFE773 /* ConstraintMultiplierTarget.swift in Sources */, + 56CD198002D3D45274F6719725B983CF /* ConstraintOffsetTarget.swift in Sources */, + EFC90283F9AB43BB6FF377812BD3673F /* ConstraintPriority.swift in Sources */, + 77D782DE125D322922466676E2FFA289 /* ConstraintPriorityTarget.swift in Sources */, + FFD7E1B8FA0F3960BE24DA2D20647332 /* ConstraintRelatableTarget.swift in Sources */, + F94703ED86C58DDBE5A2503D148CD040 /* ConstraintRelation.swift in Sources */, + 8868BA37E3CE7C58D26123806D543F3F /* ConstraintView.swift in Sources */, + C04DBE6AE13FC5CFD01D363A351EF76A /* ConstraintView+Extensions.swift in Sources */, + 0D665B6767B345D8C70D7E029A2A48D8 /* ConstraintViewDSL.swift in Sources */, + 1E7E37C51375285EA22294CD2ADB3159 /* Debugging.swift in Sources */, + 6E2884B29CD49EE91C48C725105F295A /* LayoutConstraint.swift in Sources */, + A35877DE0C3D6B4CF2A10E666EF5F490 /* LayoutConstraintItem.swift in Sources */, + 3DAFEDCDC5094007E329D71FE84FF704 /* SnapKit-dummy.m in Sources */, + 73F8AC99A58E5837924C056E89543B97 /* Typealiases.swift in Sources */, + 891D1BF14C8881C74262EE9DBE5D67A9 /* UILayoutSupport+Extensions.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C3F6FDA16E2D4FFF3DC83F1D8BB7BAAA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ADF998E6E827C3D8774DD20BF0929C02 /* RxAlamofire.swift in Sources */, + 3206D3B3E8A5500E86D4BBD3B2382988 /* RxAlamofire-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D9DF5AEE1B525A8BA763D0DFA7241A71 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3091F1A82E0FD6ABA766EBC91D4E5DE6 /* Then.swift in Sources */, + D936EF159A167C7E4C5E5764C22F458F /* Then-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DCE9B867C0C49955CAA9A624906892CA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 327569362E4604E125071D7CB6919726 /* BehaviorRelay.swift in Sources */, + 77CB99B19125DE660198CCF7E7FB3C7B /* Observable+Bind.swift in Sources */, + 957CD2F9CEC64BC57FA35D672AD44FF8 /* PublishRelay.swift in Sources */, + C195C44670C83CC91E8BADB11545D0B3 /* ReplayRelay.swift in Sources */, + D32A0967B67610F1D80FFFD8FEC6E91C /* RxRelay-dummy.m in Sources */, + A1F1776D3749EE20F8EB31B5E5487637 /* Utils.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E0C6F893D34CB935A73FBD4BD75299E5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AA602A49B1DC7FDED565CAD8BB89EAC1 /* AFError.swift in Sources */, + 58E936B1E7E42C0BFC119D428B70F1D8 /* Alamofire.swift in Sources */, + 68238227D42B2511FA6A26BF71E92520 /* Alamofire-dummy.m in Sources */, + 72C19C762FADC82517C344E9F47D7E50 /* AlamofireExtended.swift in Sources */, + 69261B5D3B53EBF7109D5E1DA3768CAC /* AuthenticationInterceptor.swift in Sources */, + 0F1D68554CA1AC595168E8FB4E1A6E63 /* CachedResponseHandler.swift in Sources */, + 9D8BED7F3F86BB39E7C0923D92E73F8B /* Combine.swift in Sources */, + A22A2ACF53FDC243AAAFB009005A710F /* Concurrency.swift in Sources */, + 5AD4E5B4118A1DC7D639F611044B4159 /* DataRequest.swift in Sources */, + B5C66B48EB624FEC4D2F64A50F143716 /* DataStreamRequest.swift in Sources */, + DE896085DFDD686BDBDEFB776F0D683A /* DispatchQueue+Alamofire.swift in Sources */, + 5830C6260CA2B7CD6DC74054FB29CDD1 /* DownloadRequest.swift in Sources */, + FCE62086E1AB54A4F61EBCDBA15C1510 /* EventMonitor.swift in Sources */, + 2B42D035AFF52D62722161A7772C6C08 /* HTTPHeaders.swift in Sources */, + 4337931D8B8E3F3BA03C77C1B496BEAD /* HTTPMethod.swift in Sources */, + 68995B28EE5B539CEA5A1133E4623927 /* MultipartFormData.swift in Sources */, + 795681285B4E2B121B5CD420131168F8 /* MultipartUpload.swift in Sources */, + A1506893FF52AA466B130E8B05FBE868 /* NetworkReachabilityManager.swift in Sources */, + 8DD46EE7FB9503E7634E929DDE1CBA31 /* Notifications.swift in Sources */, + 68A74F13F8FEBAA7E0EA9344DED0458B /* OperationQueue+Alamofire.swift in Sources */, + 22FAFA41450EC40132CF4B0EEE7E6788 /* ParameterEncoder.swift in Sources */, + 6F2E0DC7D8598283D088A989FDB8E5F6 /* ParameterEncoding.swift in Sources */, + F4DD0AD58DDD5641BDEAEA6CF44FF0ED /* Protected.swift in Sources */, + 9C7D314BE45AB79E96B260656C36BAEC /* RedirectHandler.swift in Sources */, + 36C78069A72BECAEB66B31FF794A09ED /* Request.swift in Sources */, + 887DB52C63E52FBD3B88F42DD8CFB421 /* RequestCompression.swift in Sources */, + DE8F5B68839128A005EE3549A1149B09 /* RequestInterceptor.swift in Sources */, + 90D847B19214926EDE5210D44A08F3C7 /* RequestTaskMap.swift in Sources */, + E6ED06AC318A34F7744B32CEC759CDA9 /* Response.swift in Sources */, + 2B230B24827053BA3E9DA0C78A796BC2 /* ResponseSerialization.swift in Sources */, + 9378157945D7B405C862A05B0D6B971B /* Result+Alamofire.swift in Sources */, + CDCA01B605A086576DBB75F8C3A24337 /* RetryPolicy.swift in Sources */, + 7AE2E0B382A14D58BE7DAA0C852DCD02 /* ServerTrustEvaluation.swift in Sources */, + 5075DC82A63A9807DFC390B4CE8046CD /* Session.swift in Sources */, + 97D7D91FC818805D8344C373CC098C32 /* SessionDelegate.swift in Sources */, + 612AE0ABB9BCD3AF0E1D29B4C063CA62 /* StringEncoding+Alamofire.swift in Sources */, + 2C4C08BB733A2101D945E8C37256F78F /* UploadRequest.swift in Sources */, + A3FD52DF5584364FFD56965394C36CF2 /* URLConvertible+URLRequestConvertible.swift in Sources */, + BC0A0C473B63B817926F4D58611281BB /* URLEncodedFormEncoder.swift in Sources */, + 92138A77DFEB4F76FCB582E97633896D /* URLRequest+Alamofire.swift in Sources */, + 6CC7E7C00730B1BF42A28B2E23CA01D6 /* URLSessionConfiguration+Alamofire.swift in Sources */, + 794FC38D15336AB502B73B012005E9BD /* Validation.swift in Sources */, + F7E576E007A81E0EFD2E0849CB17878D /* WebSocketRequest.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 05D1B6347CCB225B605DFEF8A367EA04 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 4614F7CA44712A47869911BDAAD610B0 /* PBXContainerItemProxy */; + }; + 06F4672486B9DFC2EADED95A17EECD79 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxCocoa; + target = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */; + targetProxy = 2B5A5B6D8B07663BFD23F6BA17283BAA /* PBXContainerItemProxy */; + }; + 0E570A111627A0383BE5BDC57DBD6009 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 0D93EC402991C60FD361F56E92A25367 /* PBXContainerItemProxy */; + }; + 2AA339C96F60D21C72D9475EA344A9BC /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "SnapKit-SnapKit_Privacy"; + target = 8A8DB685241263AFDF5E6B20FE67B93A /* SnapKit-SnapKit_Privacy */; + targetProxy = 8AB03F3D7894A28FD360F381CF32E53E /* PBXContainerItemProxy */; + }; + 5F437ED473134CA45885568FB8BA430C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxAlamofire; + target = 1A538A5499B1706F0983D6826042657B /* RxAlamofire */; + targetProxy = 99EC8DB108C3EE277D62F3DDBA8CE2EA /* PBXContainerItemProxy */; + }; + 6C9C46E7B9FEFABB5B08E31449FF2FB4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 27632CD24208F6346689C82FC555FFCD /* PBXContainerItemProxy */; + }; + 843578840CAFF66D287F682F79EEF365 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 2E645EDA0A1A7B3E59716294D626288F /* PBXContainerItemProxy */; + }; + 86E8265E7072A0D07F230B13DB76EC42 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 66A32866EA9D5F837D5417305531DA06 /* PBXContainerItemProxy */; + }; + 90665D8D706A61FE4B1BAF915DB22042 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; + targetProxy = 9AD87D77F545A26560FE9149D224487B /* PBXContainerItemProxy */; + }; + 9FBB31D3D17680B3229BDA14DCA3E30F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Then; + target = C17AEFC79E770A2906EFAAB1A3757406 /* Then */; + targetProxy = F8B9D3173046460791BE1A3BDD218850 /* PBXContainerItemProxy */; + }; + B1BB387A3EDE65D0DDF20083F71AD923 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SnapKit; + target = 19622742EBA51E823D6DAE3F8CDBFAD4 /* SnapKit */; + targetProxy = B6285EBA579A04B32BF960279A30DA73 /* PBXContainerItemProxy */; + }; + C1550B0652E5A5E3D6B17D869589673C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Alamofire-Alamofire"; + target = 976126A1CE06DC6E162563800E1BDF14 /* Alamofire-Alamofire */; + targetProxy = C2011E55B914B9BD6A243023BCE38AD7 /* PBXContainerItemProxy */; + }; + F92AC0077FF15AD9AEF0330D5246A591 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = CF9D6B472B16D142CE13F3528AE4B95F /* PBXContainerItemProxy */; + }; + FAE6C81526E70219F29596FC822072E9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 1A8785CA077D46458A29E5D436BA4864 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 30E0B9EFD9A5C45D0D351231E81B30B3 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + 52235FB3181E517F1F2D37DE71959EE4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1B5E3F734AD887EDA517B37DBE5936B2 /* Then.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Then/Then-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Then/Then-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Then/Then.modulemap"; + PRODUCT_MODULE_NAME = Then; + PRODUCT_NAME = Then; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 577A24D81FA00BED9154F445BE58F743 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 50AAA241799F5C057429E374C1B56217 /* RxCocoa.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxCocoa/RxCocoa-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxCocoa/RxCocoa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxCocoa/RxCocoa.modulemap"; + PRODUCT_MODULE_NAME = RxCocoa; + PRODUCT_NAME = RxCocoa; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 672CEC9F588FD8EBAA3064888BC52A93 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = CA3CD2CFFEE20CF1E7847E5A73EBAB70 /* RxRelay.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxRelay/RxRelay-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxRelay/RxRelay-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxRelay/RxRelay.modulemap"; + PRODUCT_MODULE_NAME = RxRelay; + PRODUCT_NAME = RxRelay; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 714A038955EDD712335B7293B4D7DAB3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 73E9BC207D19E47DFDAAD9B4B44E437F /* Alamofire.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 7533B27E974CBC64863C2619CF81C391 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7A0F56D7A7ACB744EFB305742D55986B /* SnapKit.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/SnapKit"; + IBSC_MODULE = SnapKit; + INFOPLIST_FILE = "Target Support Files/SnapKit/ResourceBundle-SnapKit_Privacy-SnapKit-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = SnapKit_Privacy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + 984240AE6A3D535525200348828211E3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 551CAD0F6423512F2D483AF73CED4994 /* SnapKit.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; + PRODUCT_MODULE_NAME = SnapKit; + PRODUCT_NAME = SnapKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9C0B415A54C1C30F674208B8ADAB6C17 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7A0F56D7A7ACB744EFB305742D55986B /* SnapKit.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/SnapKit/SnapKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SnapKit/SnapKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SnapKit/SnapKit.modulemap"; + PRODUCT_MODULE_NAME = SnapKit; + PRODUCT_NAME = SnapKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 9DCE1D00E6D8163230168E6736AFE116 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A377A735091D700527D978D7E7CF36CD /* Then.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Then/Then-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Then/Then-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Then/Then.modulemap"; + PRODUCT_MODULE_NAME = Then; + PRODUCT_NAME = Then; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + A506F7693419EC0E9C78E75AA2B80C47 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9F701B3583B6D6A3A47DC899C241FED9 /* RxSwift.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + BDC9FB143AB57737D6706D18BFFED24F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 73E9BC207D19E47DFDAAD9B4B44E437F /* Alamofire.debug.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Alamofire"; + IBSC_MODULE = Alamofire; + INFOPLIST_FILE = "Target Support Files/Alamofire/ResourceBundle-Alamofire-Alamofire-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + C12D9C5CC8F2071662A98F549A9E6FB4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A93419B2646DBDECDCBD65C3F85BF74C /* RxCocoa.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxCocoa/RxCocoa-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxCocoa/RxCocoa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxCocoa/RxCocoa.modulemap"; + PRODUCT_MODULE_NAME = RxCocoa; + PRODUCT_NAME = RxCocoa; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + CA60CF70D0AF64CB6C7F697460FBE2FE /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2D967B721BF4CCD0A468C726FA0EB96B /* Alamofire.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D979ADA3D8085B5AE546BEAC08E4AA56 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2D967B721BF4CCD0A468C726FA0EB96B /* Alamofire.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Alamofire"; + IBSC_MODULE = Alamofire; + INFOPLIST_FILE = "Target Support Files/Alamofire/ResourceBundle-Alamofire-Alamofire-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + EC4C54A2D4C861F91A2C109EDDDEDBFF /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A6448B431D76DF0FA9F48124C92878F7 /* RxRelay.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxRelay/RxRelay-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxRelay/RxRelay-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxRelay/RxRelay.modulemap"; + PRODUCT_MODULE_NAME = RxRelay; + PRODUCT_NAME = RxRelay; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + ED807A8114E2B104272AD6BC93FB071D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E16732205A2478CA55E13CBBA6F67A9B /* Pods-ChatBot.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-ChatBot/Pods-ChatBot-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-ChatBot/Pods-ChatBot.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + EF9B5DE537886557279DA493B7A07D2D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 01E338C96A64806AD5F7BC07C1F70508 /* RxAlamofire.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxAlamofire/RxAlamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxAlamofire/RxAlamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxAlamofire/RxAlamofire.modulemap"; + PRODUCT_MODULE_NAME = RxAlamofire; + PRODUCT_NAME = RxAlamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F4FF6A0D1970CA9705974E3CB2134802 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + F54EE6F123D1C2EC7B7A9F5BA59F0434 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 247A3B30DFF905EA0A027E44FFDFC16E /* RxSwift.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F68669B0E7FBC994372117A448AD5249 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33C482FE51B8DB5C9C06EFC86B6A38F1 /* Pods-ChatBot.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-ChatBot/Pods-ChatBot-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-ChatBot/Pods-ChatBot.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + FB0E088F6AE05667B44194FBC2C3E941 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 551CAD0F6423512F2D483AF73CED4994 /* SnapKit.release.xcconfig */; + buildSettings = { + CODE_SIGNING_ALLOWED = NO; + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/SnapKit"; + IBSC_MODULE = SnapKit; + INFOPLIST_FILE = "Target Support Files/SnapKit/ResourceBundle-SnapKit_Privacy-SnapKit-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = SnapKit_Privacy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + FFA67F3073095286D99F738C7D032FD7 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A1FCEE06CE8D7B2AFE2BA9986718C750 /* RxAlamofire.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxAlamofire/RxAlamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxAlamofire/RxAlamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxAlamofire/RxAlamofire.modulemap"; + PRODUCT_MODULE_NAME = RxAlamofire; + PRODUCT_NAME = RxAlamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1D1AB428C97AEA54D7EC22E24323597B /* Build configuration list for PBXNativeTarget "SnapKit-SnapKit_Privacy" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7533B27E974CBC64863C2619CF81C391 /* Debug */, + FB0E088F6AE05667B44194FBC2C3E941 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1E42B460D55BA3EBE021004CC2CE312C /* Build configuration list for PBXNativeTarget "RxCocoa" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C12D9C5CC8F2071662A98F549A9E6FB4 /* Debug */, + 577A24D81FA00BED9154F445BE58F743 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 231F44657D2D49D9C0A7A4B238111924 /* Build configuration list for PBXNativeTarget "Pods-ChatBot" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F68669B0E7FBC994372117A448AD5249 /* Debug */, + ED807A8114E2B104272AD6BC93FB071D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F4FF6A0D1970CA9705974E3CB2134802 /* Debug */, + 30E0B9EFD9A5C45D0D351231E81B30B3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4C4F25F04C086237315FCAEF7661357E /* Build configuration list for PBXNativeTarget "SnapKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 9C0B415A54C1C30F674208B8ADAB6C17 /* Debug */, + 984240AE6A3D535525200348828211E3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 7E7568C2596D611D56931D1635A0BC05 /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F54EE6F123D1C2EC7B7A9F5BA59F0434 /* Debug */, + A506F7693419EC0E9C78E75AA2B80C47 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9066CF256D5B92C1B2C5053115F4AC74 /* Build configuration list for PBXNativeTarget "Then" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 52235FB3181E517F1F2D37DE71959EE4 /* Debug */, + 9DCE1D00E6D8163230168E6736AFE116 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B4BC34F594FC7791F66695A9E0AC12C9 /* Build configuration list for PBXNativeTarget "RxRelay" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 672CEC9F588FD8EBAA3064888BC52A93 /* Debug */, + EC4C54A2D4C861F91A2C109EDDDEDBFF /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F52E4AB8CBA3FFCD0B955722B49E8A01 /* Build configuration list for PBXNativeTarget "RxAlamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EF9B5DE537886557279DA493B7A07D2D /* Debug */, + FFA67F3073095286D99F738C7D032FD7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA92BF783257A026FB1E05B4B536DD6E /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 714A038955EDD712335B7293B4D7DAB3 /* Debug */, + CA60CF70D0AF64CB6C7F697460FBE2FE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FC1E1E6045405857DBC6B878AF238235 /* Build configuration list for PBXNativeTarget "Alamofire-Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BDC9FB143AB57737D6706D18BFFED24F /* Debug */, + D979ADA3D8085B5AE546BEAC08E4AA56 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/ChatBot/Pods/RxAlamofire/LICENSE.md b/ChatBot/Pods/RxAlamofire/LICENSE.md new file mode 100644 index 00000000..d031fd15 --- /dev/null +++ b/ChatBot/Pods/RxAlamofire/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Junior B. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/ChatBot/Pods/RxAlamofire/README.md b/ChatBot/Pods/RxAlamofire/README.md new file mode 100644 index 00000000..e5d2ecf2 --- /dev/null +++ b/ChatBot/Pods/RxAlamofire/README.md @@ -0,0 +1,232 @@ +RxAlamofire +=== + +RxAlamofire is a [RxSwift](https://github.com/ReactiveX/RxSwift) wrapper around the elegant HTTP networking in Swift [Alamofire](https://github.com/Alamofire/Alamofire). + +![Create release](https://github.com/RxSwiftCommunity/RxAlamofire/workflows/Create%20release/badge.svg) +[![Version](https://img.shields.io/cocoapods/v/RxAlamofire.svg?style=flat)](http://cocoapods.org/pods/RxAlamofire) +[![License](https://img.shields.io/cocoapods/l/RxAlamofire.svg?style=flat)](http://cocoapods.org/pods/RxAlamofire) +[![Platform](https://img.shields.io/cocoapods/p/RxAlamofire.svg?style=flat)](http://cocoapods.org/pods/RxAlamofire) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +## Getting Started + +Wrapping RxSwift around Alamofire makes working with network requests a smoother and nicer task. Alamofire is a very powerful framework and RxSwift add the ability to compose responses in a simple and effective way. + +A basic usage is (considering a simple currency converter): + +```swift +let formatter = NSNumberFormatter() +formatter.numberStyle = .currencyStyle +formatter.currencyCode = "USD" +if let fromValue = NSNumberFormatter().numberFromString(self.fromTextField.text!) { + +RxAlamofire.requestJSON(.get, sourceStringURL) + .debug() + .subscribe(onNext: { [weak self] (r, json) in + if let dict = json as? [String: AnyObject] { + let valDict = dict["rates"] as! Dictionary + if let conversionRate = valDict["USD"] as? Float { + self?.toTextField.text = formatter + .string(from: NSNumber(value: conversionRate * fromValue)) + } + } + }, onError: { [weak self] (error) in + self?.displayError(error as NSError) + }) + .disposed(by: disposeBag) + +} else { + self.toTextField.text = "Invalid Input!" +} +``` + +## Example Usages + +Currently, the library features the following extensions: + +```swift +let stringURL = "" + +// MARK: URLSession simple and fast +let session = URLSession.shared() + +_ = session.rx + .response(.get, stringURL) + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +_ = session.rx + .json(.get, stringURL) + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +_ = session.rx + .data(.get, stringURL) + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// MARK: With Alamofire engine + +_ = json(.get, stringURL) + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// validation +_ = request(.get, stringURL) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .responseJSON() + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// progress +_ = request(.get, stringURL) + .progress() + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// just fire upload and display progress +_ = upload(Data(), urlRequest: try! RxAlamofire.urlRequest(.get, stringURL)) + .progress() + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// progress and final result +// uploading files with progress showing is processing intensive operation anyway, so +// this doesn't add much overhead +_ = request(.get, stringURL) + .flatMap { request -> Observable<(Data?, RxProgress)> in + let dataPart = request.rx + .data() + .map { d -> Data? in d } + .startWith(nil as Data?) + let progressPart = request.rx.progress() + return Observable.combineLatest(dataPart, progressPart) { ($0, $1) } + } + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + + +// MARK: Alamofire Session +// same methods with any Alamofire Session + +let session = Session.default + +// simple case +_ = session.rx.json(.get, stringURL) + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// URLHTTPResponse + JSON +_ = session.rx.responseJSON(.get, stringURL) + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// URLHTTPResponse + String +_ = session.rx.responseString(.get, stringURL) + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// URLHTTPResponse + Validation + JSON +_ = session.rx.request(.get, stringURL) + .validate(statusCode: 200 ..< 300) + .validate(contentType: ["text/json"]) + .json() + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// URLHTTPResponse + Validation + URLHTTPResponse + JSON +_ = session.rx.request(.get, stringURL) + .validate(statusCode: 200 ..< 300) + .validate(contentType: ["text/json"]) + .responseJSON() + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// URLHTTPResponse + Validation + URLHTTPResponse + String + Progress +_ = session.rx.request(.get, stringURL) + .validate(statusCode: 200 ..< 300) + .validate(contentType: ["text/something"]) + .flatMap { request -> Observable<(String?, RxProgress)> in + let stringPart = request.rx + .string() + .map { d -> String? in d } + .startWith(nil as String?) + let progressPart = request.rx.progress() + return Observable.combineLatest(stringPart, progressPart) { ($0, $1) } + } + .observeOn(MainScheduler.instance) + .subscribe { print($0) } + +// Interceptor + URLHTTPResponse + Validation + JSON +let adapter = // Some RequestAdapter +let retrier = // Some RequestRetrier +let interceptor = Interceptor(adapter: adapter, retrier: retrier) +_ = session.rx.request(.get, stringURL) + .validate() + .validate(contentType: ["text/json"]) + .responseJSON() + .observeOn(MainScheduler.instance) + .subscribe { print($0) } +``` + +## Installation + +There are three ways to install RxAlamofire + +### CocoaPods + +Just add to your project's `Podfile`: + +``` +pod 'RxAlamofire' +``` + +### Carthage + +Add following to `Cartfile`: + +``` +github "RxSwiftCommunity/RxAlamofire" ~> 6.1 +``` + +### Swift Package manager + +Create a `Package.swift` file + +``` +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "TestRxAlamofire", + + dependencies: [ + .package(url: "https://github.com/RxSwiftCommunity/RxAlamofire.git", + from: "6.1.0"), + ], + + targets: [ + .target( + name: "TestRxAlamofire", + dependencies: ["RxAlamofire"]) + ] +) + +``` + +### Manually + +To manual install this extension you should get the `RxAlamofire/Source/RxAlamofire.swift` imported into your project, alongside RxSwift and Alamofire. + +## Requirements + +RxAlamofire requires Swift 5.1 and dedicated versions of Alamofire (5.4.1) and RxSwift (6.0.0). + +For the last RxSwift 5.1 support, please use RxAlamofire 5.7.1. + +For the last Swift 5.0 support, please use RxAlamofire 5.1.0. + +For the last Swift 4.2 support, please use RxAlamofire 4.5.0. diff --git a/ChatBot/Pods/RxAlamofire/Sources/RxAlamofire/RxAlamofire.swift b/ChatBot/Pods/RxAlamofire/Sources/RxAlamofire/RxAlamofire.swift new file mode 100644 index 00000000..4f116231 --- /dev/null +++ b/ChatBot/Pods/RxAlamofire/Sources/RxAlamofire/RxAlamofire.swift @@ -0,0 +1,1589 @@ +// swiftlint:disable file_length +import Alamofire +import Foundation +import RxSwift + +/// Default instance of unknown error +public let RxAlamofireUnknownError = NSError(domain: "RxAlamofireDomain", code: -1, userInfo: nil) + +// MARK: Convenience functions + +/** + Creates a NSMutableURLRequest using all necessary parameters. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - returns: An instance of `NSMutableURLRequest` + */ + +public func urlRequest(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + throws -> Foundation.URLRequest { + var mutableURLRequest = Foundation.URLRequest(url: try url.asURL()) + mutableURLRequest.httpMethod = method.rawValue + + if let headers = headers { + for header in headers { + mutableURLRequest.setValue(header.value, forHTTPHeaderField: header.name) + } + } + + if let parameters = parameters { + mutableURLRequest = try encoding.encode(mutableURLRequest, with: parameters) + } + + return mutableURLRequest +} + +// MARK: Request + +/** + Creates an observable of the generated `Request`. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of a the `Request` + */ +public func request(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return Alamofire.Session.default.rx.request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +/** + Creates an observable of the generated `Request`. + + - parameter urlRequest: An object adopting `URLRequestConvertible` + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of a the `Request` + */ +public func request(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return Alamofire.Session.default.rx.request(urlRequest: urlRequest, interceptor: interceptor) +} + +// MARK: response + +/** + Creates an observable of the `NSHTTPURLResponse` instance. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `NSHTTPURLResponse` + */ +public func requestResponse(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return Alamofire.Session.default.rx.response(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +/** + Creates an observable of the `NSHTTPURLResponse` instance. + + - parameter urlRequest: An object adopting `URLRequestConvertible` + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `NSHTTPURLResponse` + */ +public func requestResponse(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.response() } +} + +/** + Creates an observable of the returned data. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `NSHTTPURLResponse` + */ +public func response(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return Alamofire.Session.default.rx.response(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +// MARK: data + +/** + Creates an observable of the `(NSHTTPURLResponse, NSData)` instance. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of a tuple containing `(NSHTTPURLResponse, NSData)` + */ +public func requestData(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, Data)> { + return Alamofire.Session.default.rx.responseData(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +/** + Creates an observable of the `(NSHTTPURLResponse, NSData)` instance. + + - parameter urlRequest: An object adopting `URLRequestConvertible` + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of a tuple containing `(NSHTTPURLResponse, NSData)` + */ +public func requestData(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, Data)> { + return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseData() } +} + +/** + Creates an observable of the returned data. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `NSData` + */ +public func data(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return Alamofire.Session.default.rx.data(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +// MARK: string + +/** + Creates an observable of the returned decoded string and response. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, String)` + */ +public func requestString(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, String)> { + return Alamofire.Session.default.rx.responseString(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +/** + Creates an observable of the returned decoded string and response. + + - parameter urlRequest: An object adopting `URLRequestConvertible` + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, String)` + */ +public func requestString(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, String)> { + return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseString() } +} + +/** + Creates an observable of the returned decoded string. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `String` + */ +public func string(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return Alamofire.Session.default.rx.string(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +// MARK: JSON + +/** + Creates an observable of the returned decoded JSON as `AnyObject` and the response. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)` + */ +public func requestJSON(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, Any)> { + return Alamofire.Session.default.rx.responseJSON(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +/** + Creates an observable of the returned decoded JSON as `AnyObject` and the response. + + - parameter urlRequest: An object adopting `URLRequestConvertible` + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)` + */ +public func requestJSON(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, Any)> { + return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseJSON() } +} + +/** + Creates an observable of the returned decoded JSON. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the decoded JSON as `Any` + */ +public func json(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return Alamofire.Session.default.rx.json(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +// MARK: Decodable + +/** + Creates an observable of the returned decoded Decodable as `T` and the response. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, T)` + */ +public func requestDecodable(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, T)> { + return Alamofire.Session.default.rx.responseDecodable(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +/** + Creates an observable of the returned decoded Decodable as `T` and the response. + + - parameter urlRequest: An object adopting `URLRequestConvertible` + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, T)` + */ +public func requestDecodable(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable<(HTTPURLResponse, T)> { + return request(urlRequest, interceptor: interceptor).flatMap { $0.rx.responseDecodable() } +} + +/** + Creates an observable of the returned decoded Decodable. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the decoded Decodable as `T` + */ +public func decodable(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return Alamofire.Session.default.rx.decodable(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) +} + +// MARK: Upload + +/** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter file: An instance of NSURL holding the information of the local file. + - parameter urlRequest: The request object to start the upload. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: The observable of `UploadRequest` for the created request. + */ +public func upload(_ file: URL, + urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(file, urlRequest: urlRequest, interceptor: interceptor) +} + +/** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter file: An instance of `URL` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ +public func upload(_ file: URL, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(file, to: url, method: method, headers: headers) +} + +/** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter file: An instance of `URL` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ +public func upload(_ file: URL, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(file, to: url, method: method, headers: headers) +} + +/** + Returns an observable of a request using the shared manager instance to upload any data to a specified URL. + The request is started immediately. + + - parameter data: An instance of NSData holdint the data to upload. + - parameter urlRequest: The request object to start the upload. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: The observable of `UploadRequest` for the created request. + */ +public func upload(_ data: Data, + urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(data, urlRequest: urlRequest, interceptor: interceptor) +} + +/** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter data: An instance of `Data` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ +public func upload(_ data: Data, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(data, to: url, method: method, headers: headers) +} + +/** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter data: An instance of `Data` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ +public func upload(_ data: Data, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(data, to: url, method: method, headers: headers) +} + +/** + Returns an observable of a request using the shared manager instance to upload any stream to a specified URL. + The request is started immediately. + + - parameter stream: The stream to upload. + - parameter urlRequest: The request object to start the upload. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: The observable of `Request` for the created upload request. + */ +public func upload(_ stream: InputStream, + urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(stream, urlRequest: urlRequest, interceptor: interceptor) +} + +/** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter stream: The `InputStream` to upload. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ +public func upload(_ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(stream, to: url, method: method, headers: headers) +} + +/** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter stream: The `InputStream` to upload. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ +public func upload(_ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(stream, to: url, method: method, headers: headers) +} + +/** + Returns an observable of a request using the shared manager instance to upload any stream to a specified URL. + The request is started immediately. + + - parameter multipartFormData: The block for building `MultipartFormData`. + - parameter urlRequest: The request object to start the upload. + - returns: The observable of `UploadRequest` for the created upload request. + */ +public func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + urlRequest: URLRequestConvertible) -> Observable { + return Alamofire.Session.default.rx.upload(multipartFormData: multipartFormData, urlRequest: urlRequest) +} + +/** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter multipartFormData: The block for building `MultipartFormData`. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ +public func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers) +} + +/** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter multipartFormData: The block for building `MultipartFormData`. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ +public func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return Alamofire.Session.default.rx.upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers) +} + +// MARK: Download + +/** + Creates a download request using the shared manager instance for the specified URL request. + - parameter urlRequest: The URL request. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + - returns: The observable of `DownloadRequest` for the created download request. + */ +public func download(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + to destination: @escaping DownloadRequest.Destination) -> Observable { + return Alamofire.Session.default.rx.download(urlRequest, interceptor: interceptor, to: destination) +} + +// MARK: Resume Data + +/** + Creates a request using the shared manager instance for downloading from the resume data produced from a + previous request cancellation. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional + information. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + - returns: The observable of `Request` for the created download request. + */ +public func download(resumeData: Data, + interceptor: RequestInterceptor? = nil, + to destination: @escaping DownloadRequest.Destination) -> Observable { + return Alamofire.Session.default.rx.download(resumeData: resumeData, interceptor: interceptor, to: destination) +} + +// MARK: Manager - Extension of Manager + +extension Alamofire.Session: ReactiveCompatible {} + +protocol RxAlamofireRequest { + func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) + func resume() -> Self + func cancel() -> Self +} + +protocol RxAlamofireResponse { + var error: Error? { get } +} + +extension DataResponse: RxAlamofireResponse { + var error: Error? { + switch result { + case let .failure(error): + return error + default: + return nil + } + } +} + +extension DownloadResponse: RxAlamofireResponse { + var error: Error? { + switch result { + case let .failure(error): + return error + default: + return nil + } + } +} + +extension DataRequest: RxAlamofireRequest { + func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) { + response { response in + completionHandler(response) + } + } +} + +extension DownloadRequest: RxAlamofireRequest { + func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) { + response { response in + completionHandler(response) + } + } +} + +public extension Reactive where Base: Alamofire.Session { + // MARK: Generic request convenience + + /** + Creates an observable of the DataRequest. + + - parameter createRequest: A function used to create a `Request` using a `Manager` + + - returns: A generic observable of created data request + */ + internal func request(_ createRequest: @escaping (Alamofire.Session) throws -> R) -> Observable { + return Observable.create { observer -> Disposable in + let request: R + do { + request = try createRequest(self.base) + observer.on(.next(request)) + request.responseWith(completionHandler: { response in + if let error = response.error { + observer.on(.error(error)) + } else { + observer.on(.completed) + } + }) + + if !self.base.startRequestsImmediately { + _ = request.resume() + } + + return Disposables.create { + _ = request.cancel() + } + } catch { + observer.on(.error(error)) + return Disposables.create() + } + } + } + + /** + Creates an observable of the `Request`. + + - parameter method: Alamofire method object + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the `Request` + */ + func request(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return request { manager in + manager.request(url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) + } + } + + /** + Creates an observable of the `Request`. + + - parameter URLRequest: An object adopting `URLRequestConvertible` + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the `Request` + */ + func request(urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) + -> Observable { + return request { manager in + manager.request(urlRequest, interceptor: interceptor) + } + } + + // MARK: response + + /** + Creates an observable of the response + + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `NSHTTPURLResponse` + */ + func response(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.response() } + } + + // MARK: data + + /** + Creates an observable of the data. + + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, NSData)` + */ + func responseData(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, Data)> { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.responseData() } + } + + /** + Creates an observable of the data. + + - parameter URLRequest: An object adopting `URLRequestConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `NSData` + */ + func data(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.data() } + } + + // MARK: string + + /** + Creates an observable of the tuple `(NSHTTPURLResponse, String)`. + + - parameter url: An object adopting `URLRequestConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, String)` + */ + func responseString(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, String)> { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.responseString() } + } + + /** + Creates an observable of the data encoded as String. + + - parameter url: An object adopting `URLConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `String` + */ + func string(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor) + .flatMap { (request) -> Observable in + request.rx.string() + } + } + + // MARK: JSON + + /** + Creates an observable of the data decoded from JSON and processed as tuple `(NSHTTPURLResponse, AnyObject)`. + + - parameter url: An object adopting `URLRequestConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)` + */ + func responseJSON(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, Any)> { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.responseJSON() } + } + + /** + Creates an observable of the data decoded from JSON and processed as `AnyObject`. + + - parameter URLRequest: An object adopting `URLRequestConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `AnyObject` + */ + func json(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.json() } + } + + // MARK: Decodable + + /** + Creates an observable of the data decoded from Decodable and processed as tuple `(NSHTTPURLResponse, T)`. + + - parameter url: An object adopting `URLRequestConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of the tuple `(NSHTTPURLResponse, T)` + */ + func responseDecodable(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable<(HTTPURLResponse, T)> { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.responseDecodable() } + } + + /** + Creates an observable of the data decoded from Decodable and processed as `T`. + + - parameter URLRequest: An object adopting `URLRequestConvertible` + - parameter parameters: A dictionary containing all necessary options + - parameter encoding: The kind of encoding used to process parameters + - parameter header: A dictionary containing all the additional headers + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: An observable of `T` + */ + func decodable(_ method: HTTPMethod, + _ url: URLConvertible, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + interceptor: RequestInterceptor? = nil) + -> Observable { + return request(method, + url, + parameters: parameters, + encoding: encoding, + headers: headers, + interceptor: interceptor).flatMap { $0.rx.decodable() } + } + + // MARK: Upload + + /** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter file: An instance of NSURL holding the information of the local file. + - parameter urlRequest: The request object to start the upload. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: The observable of `AnyObject` for the created request. + */ + func upload(_ file: URL, + urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return request { manager in + manager.upload(file, with: urlRequest, interceptor: interceptor) + } + } + + /** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter file: An instance of `URL` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ + func upload(_ file: URL, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return request { manager in + manager.upload(file, to: url, method: method, headers: headers) + } + } + + /** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter file: An instance of `URL` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ + func upload(_ file: URL, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return upload(file, to: url, method: method, headers: headers) + .flatMap { $0.rx.progress() } + } + + /** + Returns an observable of a request using the shared manager instance to upload any data to a specified URL. + The request is started immediately. + + - parameter data: An instance of Data holdint the data to upload. + - parameter urlRequest: The request object to start the upload. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: The observable of `UploadRequest` for the created request. + */ + func upload(_ data: Data, + urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return request { manager in + manager.upload(data, with: urlRequest, interceptor: interceptor) + } + } + + /** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter data: An instance of `Data` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ + func upload(_ data: Data, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return request { manager in + manager.upload(data, to: url, method: method, headers: headers) + } + } + + /** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter data: An instance of `Data` holding the information of the local file. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ + func upload(_ data: Data, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return upload(data, to: url, method: method, headers: headers) + .flatMap { $0.rx.progress() } + } + + /** + Returns an observable of a request using the shared manager instance to upload any stream to a specified URL. + The request is started immediately. + + - parameter stream: The stream to upload. + - parameter urlRequest: The request object to start the upload. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - returns: The observable of `(NSData?, RxProgress)` for the created upload request. + */ + func upload(_ stream: InputStream, + urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil) -> Observable { + return request { manager in + manager.upload(stream, with: urlRequest, interceptor: interceptor) + } + } + + /** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter stream: The `InputStream` to upload. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ + func upload(_ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return request { manager in + manager.upload(stream, to: url, method: method, headers: headers) + } + } + + /** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter stream: The `InputStream` to upload. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ + func upload(_ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return upload(stream, to: url, method: method, headers: headers) + .flatMap { $0.rx.progress() } + } + + /** + Returns an observable of a request using the shared manager instance to upload any stream to a specified URL. + The request is started immediately. + + - parameter multipartFormData: The block for building `MultipartFormData`. + - parameter urlRequest: The request object to start the upload. + - returns: The observable of `UploadRequest` for the created upload request. + */ + func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + urlRequest: URLRequestConvertible) -> Observable { + return request { manager in + manager.upload(multipartFormData: multipartFormData, with: urlRequest) + } + } + + /** + Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter multipartFormData: The block for building `MultipartFormData`. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `UploadRequest` for the created request. + */ + func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return request { manager in + manager.upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers) + } + } + + /** + Returns an observable of a request progress using the shared manager instance to upload a specific file to a specified URL. + The request is started immediately. + + - parameter multipartFormData: The block for building `MultipartFormData`. + - parameter url: An object adopting `URLConvertible` + - parameter method: Alamofire method object + - parameter headers: A `HTTPHeaders` containing all the additional headers + - returns: The observable of `RxProgress` for the created request. + */ + func upload(multipartFormData: @escaping (MultipartFormData) -> Void, + to url: URLConvertible, + method: HTTPMethod, + headers: HTTPHeaders? = nil) -> Observable { + return upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers) + .flatMap { $0.rx.progress() } + } + + // MARK: Download + + /** + Creates a download request using the shared manager instance for the specified URL request. + - parameter urlRequest: The URL request. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + - returns: The observable of `(NSData?, RxProgress)` for the created download request. + */ + func download(_ urlRequest: URLRequestConvertible, + interceptor: RequestInterceptor? = nil, + to destination: @escaping DownloadRequest.Destination) -> Observable { + return request { manager in + manager.download(urlRequest, interceptor: interceptor, to: destination) + } + } + + /** + Creates a request using the shared manager instance for downloading with a resume data produced from a + previous request cancellation. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional + information. + - parameter interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + - returns: The observable of `(NSData?, RxProgress)` for the created download request. + */ + func download(resumeData: Data, + interceptor: RequestInterceptor? = nil, + to destination: @escaping DownloadRequest.Destination) -> Observable { + return request { manager in + manager.download(resumingWith: resumeData, interceptor: interceptor, to: destination) + } + } +} + +// MARK: Request - Common Response Handlers + +public extension ObservableType where Element == DataRequest { + func responseJSON() -> Observable> { + return flatMap { $0.rx.responseJSON() } + } + + func json(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable { + return flatMap { $0.rx.json(options: options) } + } + + func responseString(encoding: String.Encoding? = nil) -> Observable<(HTTPURLResponse, String)> { + return flatMap { $0.rx.responseString(encoding: encoding) } + } + + func string(encoding: String.Encoding? = nil) -> Observable { + return flatMap { $0.rx.string(encoding: encoding) } + } + + func responseData() -> Observable<(HTTPURLResponse, Data)> { + return flatMap { $0.rx.responseData() } + } + + func response() -> Observable { + return flatMap { $0.rx.response() } + } + + func data() -> Observable { + return flatMap { $0.rx.data() } + } + + func progress() -> Observable { + return flatMap { $0.rx.progress() } + } +} + +// MARK: Request - Validation + +public extension ObservableType where Element == DataRequest { + func validate(statusCode: S) -> Observable where S.Element == Int { + return map { $0.validate(statusCode: statusCode) } + } + + func validate() -> Observable { + return map { $0.validate() } + } + + func validate(contentType acceptableContentTypes: S) -> Observable where S.Iterator.Element == String { + return map { $0.validate(contentType: acceptableContentTypes) } + } + + func validate(_ validation: @escaping DataRequest.Validation) -> Observable { + return map { $0.validate(validation) } + } +} + +extension Request: ReactiveCompatible {} + +public extension Reactive where Base: DataRequest { + // MARK: Defaults + + /** + Transform a request into an observable of the response + + - parameter queue: The dispatch queue to use. + - returns: The observable of `NSHTTPURLResponse` for the created request. + */ + func response(queue: DispatchQueue = .main) + -> Observable { + return Observable.create { observer in + let dataRequest = self.base + .response(queue: queue) { (packedResponse) -> Void in + switch packedResponse.result { + case .success: + if let httpResponse = packedResponse.response { + observer.on(.next(httpResponse)) + observer.on(.completed) + } else { + observer.on(.error(RxAlamofireUnknownError)) + } + case let .failure(error): + observer.on(.error(error as Error)) + } + } + return Disposables.create { + dataRequest.cancel() + } + } + } + + /** + Transform a request into an observable of the response and serialized object. + + - parameter queue: The dispatch queue to use. + - parameter responseSerializer: The the serializer. + - returns: The observable of `(NSHTTPURLResponse, T.SerializedObject)` for the created download request. + */ + func responseResult(queue: DispatchQueue = .main, + responseSerializer: T) + -> Observable<(HTTPURLResponse, T.SerializedObject)> { + return Observable.create { observer in + let dataRequest = self.base + .response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in + switch packedResponse.result { + case let .success(result): + if let httpResponse = packedResponse.response { + observer.on(.next((httpResponse, result))) + observer.on(.completed) + } else { + observer.on(.error(RxAlamofireUnknownError)) + } + case let .failure(error): + observer.on(.error(error as Error)) + } + } + return Disposables.create { + dataRequest.cancel() + } + } + } + + func responseJSON() -> Observable> { + return Observable.create { observer in + let request = self.base + + request.responseJSON { response in + switch response.result { + case .success: + observer.on(.next(response)) + observer.on(.completed) + case let .failure(error): + observer.on(.error(error)) + } + } + + return Disposables.create { + request.cancel() + } + } + } + + /** + Transform a request into an observable of the serialized object. + + - parameter queue: The dispatch queue to use. + - parameter responseSerializer: The the serializer. + - returns: The observable of `T.SerializedObject` for the created download request. + */ + func result(queue: DispatchQueue = .main, + responseSerializer: T) + -> Observable { + return Observable.create { observer in + let dataRequest = self.base + .response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in + switch packedResponse.result { + case let .success(result): + if packedResponse.response != nil { + observer.on(.next(result)) + observer.on(.completed) + } else { + observer.on(.error(RxAlamofireUnknownError)) + } + case let .failure(error): + observer.on(.error(error as Error)) + } + } + return Disposables.create { + dataRequest.cancel() + } + } + } + + /** + Returns an `Observable` of NSData for the current request. + + - parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false` + + - returns: An instance of `Observable` + */ + func responseData() -> Observable<(HTTPURLResponse, Data)> { + return responseResult(responseSerializer: DataResponseSerializer()) + } + + func data() -> Observable { + return result(responseSerializer: DataResponseSerializer()) + } + + /** + Returns an `Observable` of a String for the current request + + - parameter encoding: Type of the string encoding, **default:** `nil` + + - returns: An instance of `Observable` + */ + func responseString(encoding: String.Encoding? = nil) -> Observable<(HTTPURLResponse, String)> { + return responseResult(responseSerializer: StringResponseSerializer(encoding: encoding)) + } + + func string(encoding: String.Encoding? = nil) -> Observable { + return result(responseSerializer: StringResponseSerializer(encoding: encoding)) + } + + /** + Returns an `Observable` of a serialized JSON for the current request. + + - parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments` + + - returns: An instance of `Observable` + */ + func responseJSON(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<(HTTPURLResponse, Any)> { + return responseResult(responseSerializer: JSONResponseSerializer(options: options)) + } + + /** + Returns an `Observable` of a serialized JSON for the current request. + + - parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments` + + - returns: An instance of `Observable` + */ + func json(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable { + return result(responseSerializer: JSONResponseSerializer(options: options)) + } + + /** + Returns an `Observable` of a serialized Decodable for the current request. + + - parameter decoder: The `DataDecoder`. `JSONDecoder()` by default. + + - returns: An instance of `Observable<(HTTPURLResponse, T)>` + */ + func responseDecodable(decoder: Alamofire.DataDecoder = JSONDecoder()) -> Observable<(HTTPURLResponse, T)> { + return responseResult(responseSerializer: DecodableResponseSerializer(decoder: decoder)) + } + + /** + Returns an `Observable` of a serialized Decodable for the current request. + + - parameter decoder: The `DataDecoder`. `JSONDecoder()` by default. + + - returns: An instance of `Observable` + */ + func decodable(decoder: Alamofire.DataDecoder = JSONDecoder()) -> Observable { + return result(responseSerializer: DecodableResponseSerializer(decoder: decoder)) + } +} + +public extension Reactive where Base: Request { + // MARK: Request - Upload and download progress + + /** + Returns an `Observable` for the current progress status. + + Parameters on observed tuple: + + 1. bytes written so far. + 1. total bytes to write. + + - returns: An instance of `Observable` + */ + func progress() -> Observable { + return Observable.create { observer in + let handler: Request.ProgressHandler = { progress in + let rxProgress = RxProgress(bytesWritten: progress.completedUnitCount, + totalBytes: progress.totalUnitCount) + observer.on(.next(rxProgress)) + + if rxProgress.bytesWritten >= rxProgress.totalBytes { + observer.on(.completed) + } + } + + // Try in following order: + // - UploadRequest (Inherits from DataRequest, so we test the discrete case first) + // - DownloadRequest + // - DataRequest + if let uploadReq = self.base as? UploadRequest { + uploadReq.uploadProgress(closure: handler) + } else if let downloadReq = self.base as? DownloadRequest { + downloadReq.downloadProgress(closure: handler) + } else if let dataReq = self.base as? DataRequest { + dataReq.downloadProgress(closure: handler) + } + + return Disposables.create() + } + // warm up a bit :) + .startWith(RxProgress(bytesWritten: 0, totalBytes: 0)) + } +} + +// MARK: RxProgress +public struct RxProgress { + public let bytesWritten: Int64 + public let totalBytes: Int64 + + public init(bytesWritten: Int64, totalBytes: Int64) { + self.bytesWritten = bytesWritten + self.totalBytes = totalBytes + } +} + +public extension RxProgress { + var bytesRemaining: Int64 { + return totalBytes - bytesWritten + } + + var completed: Float { + if totalBytes > 0 { + return Float(bytesWritten) / Float(totalBytes) + } else { + return 0 + } + } +} + +extension RxProgress: Equatable {} + +public func ==(lhs: RxProgress, rhs: RxProgress) -> Bool { + return lhs.bytesWritten == rhs.bytesWritten && + lhs.totalBytes == rhs.totalBytes +} diff --git a/ChatBot/Pods/RxCocoa/LICENSE.md b/ChatBot/Pods/RxCocoa/LICENSE.md new file mode 100644 index 00000000..e32511b3 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ChatBot/Pods/RxCocoa/Platform/DataStructures/Bag.swift b/ChatBot/Pods/RxCocoa/Platform/DataStructures/Bag.swift new file mode 100644 index 00000000..5720a3b4 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/DataStructures/Bag.swift @@ -0,0 +1,181 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + private var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + lhs.rawValue == rhs.rawValue +} diff --git a/ChatBot/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift b/ChatBot/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 00000000..75d7bea7 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,23 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Iterator = AnyIterator + + private let repeatedValue: Element + + init(repeatedValue: Element) { + self.repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = self.repeatedValue + return AnyIterator { repeatedValue } + } +} diff --git a/ChatBot/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift b/ChatBot/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 00000000..9ed856b9 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let hasHigherPriority: (Element, Element) -> Bool + private let isEqual: (Element, Element) -> Bool + + private var elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + self.hasHigherPriority = hasHigherPriority + self.isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + elements.append(element) + bubbleToHigherPriority(elements.count - 1) + } + + func peek() -> Element? { + elements.first + } + + var isEmpty: Bool { + elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< elements.count { + if self.isEqual(elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == elements.count - 1 + if !removingLast { + elements.swapAt(index, elements.count - 1) + } + + _ = elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard self.hasHigherPriority(elements[unbalancedIndex], elements[parentIndex]) else { break } + elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < elements.count && self.hasHigherPriority(elements[leftChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < elements.count && self.hasHigherPriority(elements[rightChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + elements.debugDescription + } +} diff --git a/ChatBot/Pods/RxCocoa/Platform/DataStructures/Queue.swift b/ChatBot/Pods/RxCocoa/Platform/DataStructures/Queue.swift new file mode 100644 index 00000000..625d4733 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/DataStructures/Queue.swift @@ -0,0 +1,148 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let resizeFactor = 2 + + private var storage: ContiguousArray + private var innerCount = 0 + private var pushNextIndex = 0 + private let initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + initialCapacity = capacity + + storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = pushNextIndex - count + return index < 0 ? index + storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { count == 0 } + + /// - returns: Number of elements inside queue. + var count: Int { innerCount } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = self.count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = storage[0 ..< numberOfElementsInSecondBatch] + + self.innerCount = count + pushNextIndex = count + storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == storage.count { + resizeTo(Swift.max(storage.count, 1) * resizeFactor) + } + + storage[pushNextIndex] = element + pushNextIndex += 1 + innerCount += 1 + + if pushNextIndex >= storage.count { + pushNextIndex -= storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + storage[index] = nil + innerCount -= 1 + } + + return storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = storage.count / (resizeFactor * resizeFactor) + if count < downsizeLimit && downsizeLimit >= initialCapacity { + resizeTo(storage.count / resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var innerCount = count + + return AnyIterator { + if innerCount == 0 { + return nil + } + + defer { + innerCount -= 1 + i += 1 + } + + if i >= self.storage.count { + i -= self.storage.count + } + + return self.storage[i] + } + } +} diff --git a/ChatBot/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift b/ChatBot/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 00000000..aaf24cae --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/ChatBot/Pods/RxCocoa/Platform/Platform.Darwin.swift b/ChatBot/Pods/RxCocoa/Platform/Platform.Darwin.swift new file mode 100644 index 00000000..eacc1943 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/Platform.Darwin.swift @@ -0,0 +1,35 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/ChatBot/Pods/RxCocoa/Platform/Platform.Linux.swift b/ChatBot/Pods/RxCocoa/Platform/Platform.Linux.swift new file mode 100644 index 00000000..52a3e3af --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/Platform.Linux.swift @@ -0,0 +1,32 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import Foundation + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + if let newValue = value { + Thread.current.threadDictionary[key] = newValue + } + else { + Thread.current.threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/ChatBot/Pods/RxCocoa/Platform/RecursiveLock.swift b/ChatBot/Pods/RxCocoa/Platform/RecursiveLock.swift new file mode 100644 index 00000000..10b9bbb0 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/ChatBot/Pods/RxCocoa/README.md b/ChatBot/Pods/RxCocoa/README.md new file mode 100644 index 00000000..a95d9e0c --- /dev/null +++ b/ChatBot/Pods/RxCocoa/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.5.0' + pod 'RxCocoa', '6.5.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.5.0' + pod 'RxTest', '6.5.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.5.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.5.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift new file mode 100644 index 00000000..231c3fe5 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift @@ -0,0 +1,88 @@ +// +// ControlTarget.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) || os(macOS) + +import RxSwift + +#if os(iOS) || os(tvOS) + import UIKit + + typealias Control = UIKit.UIControl +#elseif os(macOS) + import Cocoa + + typealias Control = Cocoa.NSControl +#endif + +// This should be only used from `MainScheduler` +final class ControlTarget: RxTarget { + typealias Callback = (Control) -> Void + + let selector: Selector = #selector(ControlTarget.eventHandler(_:)) + + weak var control: Control? +#if os(iOS) || os(tvOS) + let controlEvents: UIControl.Event +#endif + var callback: Callback? + #if os(iOS) || os(tvOS) + init(control: Control, controlEvents: UIControl.Event, callback: @escaping Callback) { + MainScheduler.ensureRunningOnMainThread() + + self.control = control + self.controlEvents = controlEvents + self.callback = callback + + super.init() + + control.addTarget(self, action: selector, for: controlEvents) + + let method = self.method(for: selector) + if method == nil { + rxFatalError("Can't find method") + } + } +#elseif os(macOS) + init(control: Control, callback: @escaping Callback) { + MainScheduler.ensureRunningOnMainThread() + + self.control = control + self.callback = callback + + super.init() + + control.target = self + control.action = self.selector + + let method = self.method(for: self.selector) + if method == nil { + rxFatalError("Can't find method") + } + } +#endif + + @objc func eventHandler(_ sender: Control!) { + if let callback = self.callback, let control = self.control { + callback(control) + } + } + + override func dispose() { + super.dispose() +#if os(iOS) || os(tvOS) + self.control?.removeTarget(self, action: self.selector, for: self.controlEvents) +#elseif os(macOS) + self.control?.target = nil + self.control?.action = nil +#endif + self.callback = nil + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift new file mode 100644 index 00000000..d103448e --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift @@ -0,0 +1,294 @@ +// +// DelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + + import RxSwift + #if SWIFT_PACKAGE && !os(Linux) + import RxCocoaRuntime + #endif + + /// Base class for `DelegateProxyType` protocol. + /// + /// This implementation is not thread safe and can be used only from one thread (Main thread). + open class DelegateProxy: _RXDelegateProxy { + public typealias ParentObject = P + public typealias Delegate = D + + private var _sentMessageForSelector = [Selector: MessageDispatcher]() + private var _methodInvokedForSelector = [Selector: MessageDispatcher]() + + /// Parent object associated with delegate proxy. + private weak var _parentObject: ParentObject? + + private let _currentDelegateFor: (ParentObject) -> AnyObject? + private let _setCurrentDelegateTo: (AnyObject?, ParentObject) -> Void + + /// Initializes new instance. + /// + /// - parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object. + public init(parentObject: ParentObject, delegateProxy: Proxy.Type) + where Proxy: DelegateProxy, Proxy.ParentObject == ParentObject, Proxy.Delegate == Delegate { + self._parentObject = parentObject + self._currentDelegateFor = delegateProxy._currentDelegate + self._setCurrentDelegateTo = delegateProxy._setCurrentDelegate + + MainScheduler.ensureRunningOnMainThread() + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + super.init() + } + + /** + Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*. + + Only methods that have `void` return value can be observed using this method because + those methods are used as a notification mechanism. It doesn't matter if they are optional + or not. Observing is performed by installing a hidden associated `PublishSubject` that is + used to dispatch messages to observers. + + Delegate methods that have non `void` return value can't be observed directly using this method + because: + * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism + * there is no sensible automatic way to determine a default return value + + In case observing of delegate methods that have return type is required, it can be done by + manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. + + e.g. + + // delegate proxy part (RxScrollViewDelegateProxy) + + let internalSubject = PublishSubject + + public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { + internalSubject.on(.next(arg1)) + return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue + } + + .... + + // reactive property implementation in a real class (`UIScrollView`) + public var property: Observable { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + return proxy.internalSubject.asObservable() + } + + **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, + a more performant way of registering might exist.", that means that manual observing method + is required analog to the example above because delegate method has already been implemented.** + + - parameter selector: Selector used to filter observed invocations of delegate methods. + - returns: Observable sequence of arguments passed to `selector` method. + */ + open func sentMessage(_ selector: Selector) -> Observable<[Any]> { + MainScheduler.ensureRunningOnMainThread() + + let subject = self._sentMessageForSelector[selector] + + if let subject = subject { + return subject.asObservable() + } + else { + let subject = MessageDispatcher(selector: selector, delegateProxy: self) + self._sentMessageForSelector[selector] = subject + return subject.asObservable() + } + } + + /** + Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*. + + Only methods that have `void` return value can be observed using this method because + those methods are used as a notification mechanism. It doesn't matter if they are optional + or not. Observing is performed by installing a hidden associated `PublishSubject` that is + used to dispatch messages to observers. + + Delegate methods that have non `void` return value can't be observed directly using this method + because: + * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism + * there is no sensible automatic way to determine a default return value + + In case observing of delegate methods that have return type is required, it can be done by + manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. + + e.g. + + // delegate proxy part (RxScrollViewDelegateProxy) + + let internalSubject = PublishSubject + + public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { + internalSubject.on(.next(arg1)) + return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue + } + + .... + + // reactive property implementation in a real class (`UIScrollView`) + public var property: Observable { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + return proxy.internalSubject.asObservable() + } + + **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, + a more performant way of registering might exist.", that means that manual observing method + is required analog to the example above because delegate method has already been implemented.** + + - parameter selector: Selector used to filter observed invocations of delegate methods. + - returns: Observable sequence of arguments passed to `selector` method. + */ + open func methodInvoked(_ selector: Selector) -> Observable<[Any]> { + MainScheduler.ensureRunningOnMainThread() + + let subject = self._methodInvokedForSelector[selector] + + if let subject = subject { + return subject.asObservable() + } + else { + let subject = MessageDispatcher(selector: selector, delegateProxy: self) + self._methodInvokedForSelector[selector] = subject + return subject.asObservable() + } + } + + fileprivate func checkSelectorIsObservable(_ selector: Selector) { + MainScheduler.ensureRunningOnMainThread() + + if self.hasWiredImplementation(for: selector) { + print("⚠️ Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.") + return + } + + if self.voidDelegateMethodsContain(selector) { + return + } + + // In case `_forwardToDelegate` is `nil`, it is assumed the check is being done prematurely. + if !(self._forwardToDelegate?.responds(to: selector) ?? true) { + print("⚠️ Using delegate proxy dynamic interception method but the target delegate object doesn't respond to the requested selector. " + + "In case pure Swift delegate proxy is being used please use manual observing method by using`PublishSubject`s. " + + " (selector: `\(selector)`, forwardToDelegate: `\(self._forwardToDelegate ?? self)`)") + } + } + + // proxy + + open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) { + self._sentMessageForSelector[selector]?.on(.next(arguments)) + } + + open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) { + self._methodInvokedForSelector[selector]?.on(.next(arguments)) + } + + /// Returns reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - returns: Value of reference if set or nil. + open func forwardToDelegate() -> Delegate? { + return castOptionalOrFatalError(self._forwardToDelegate) + } + + /// Sets reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - parameter delegate: Reference of delegate that receives all messages through `self`. + /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. + open func setForwardToDelegate(_ delegate: Delegate?, retainDelegate: Bool) { + #if DEBUG // 4.0 all configurations + MainScheduler.ensureRunningOnMainThread() + #endif + self._setForwardToDelegate(delegate, retainDelegate: retainDelegate) + + let sentSelectors: [Selector] = self._sentMessageForSelector.values.filter { $0.hasObservers }.map { $0.selector } + let invokedSelectors: [Selector] = self._methodInvokedForSelector.values.filter { $0.hasObservers }.map { $0.selector } + let allUsedSelectors = sentSelectors + invokedSelectors + + for selector in Set(allUsedSelectors) { + self.checkSelectorIsObservable(selector) + } + + self.reset() + } + + private func hasObservers(selector: Selector) -> Bool { + return (self._sentMessageForSelector[selector]?.hasObservers ?? false) + || (self._methodInvokedForSelector[selector]?.hasObservers ?? false) + } + + override open func responds(to aSelector: Selector!) -> Bool { + guard let aSelector = aSelector else { return false } + return super.responds(to: aSelector) + || (self._forwardToDelegate?.responds(to: aSelector) ?? false) + || (self.voidDelegateMethodsContain(aSelector) && self.hasObservers(selector: aSelector)) + } + + fileprivate func reset() { + guard let parentObject = self._parentObject else { return } + + let maybeCurrentDelegate = self._currentDelegateFor(parentObject) + + if maybeCurrentDelegate === self { + self._setCurrentDelegateTo(nil, parentObject) + self._setCurrentDelegateTo(castOrFatalError(self), parentObject) + } + } + + deinit { + for v in self._sentMessageForSelector.values { + v.on(.completed) + } + for v in self._methodInvokedForSelector.values { + v.on(.completed) + } + #if TRACE_RESOURCES + _ = Resources.decrementTotal() + #endif + } + + + } + + private let mainScheduler = MainScheduler() + + private final class MessageDispatcher { + private let dispatcher: PublishSubject<[Any]> + private let result: Observable<[Any]> + + fileprivate let selector: Selector + + init(selector: Selector, delegateProxy _delegateProxy: DelegateProxy) { + weak var weakDelegateProxy = _delegateProxy + + let dispatcher = PublishSubject<[Any]>() + self.dispatcher = dispatcher + self.selector = selector + + self.result = dispatcher + .do(onSubscribed: { weakDelegateProxy?.checkSelectorIsObservable(selector); weakDelegateProxy?.reset() }, onDispose: { weakDelegateProxy?.reset() }) + .share() + .subscribe(on: mainScheduler) + } + + var on: (Event<[Any]>) -> Void { + return self.dispatcher.on + } + + var hasObservers: Bool { + return self.dispatcher.hasObservers + } + + func asObservable() -> Observable<[Any]> { + return self.result + } + } + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift new file mode 100644 index 00000000..7ca9c97a --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift @@ -0,0 +1,435 @@ +// +// DelegateProxyType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + + import Foundation + import RxSwift + +/** +`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with +views that can have only one delegate/datasource registered. + +`Proxies` store information about observers, subscriptions and delegates +for specific views. + +Type implementing `DelegateProxyType` should never be initialized directly. + +To fetch initialized instance of type implementing `DelegateProxyType`, `proxy` method +should be used. + +This is more or less how it works. + + + + +-------------------------------------------+ + | | + | UIView subclass (UIScrollView) | + | | + +-----------+-------------------------------+ + | + | Delegate + | + | + +-----------v-------------------------------+ + | | + | Delegate proxy : DelegateProxyType +-----+----> Observable + | , UIScrollViewDelegate | | + +-----------+-------------------------------+ +----> Observable + | | + | +----> Observable + | | + | forwards events | + | to custom delegate | + | v + +-----------v-------------------------------+ + | | + | Custom delegate (UIScrollViewDelegate) | + | | + +-------------------------------------------+ + + +Since RxCocoa needs to automagically create those Proxies and because views that have delegates can be hierarchical + + UITableView : UIScrollView : UIView + +.. and corresponding delegates are also hierarchical + + UITableViewDelegate : UIScrollViewDelegate : NSObject + +... this mechanism can be extended by using the following snippet in `registerKnownImplementations` or in some other + part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). + + RxScrollViewDelegateProxy.register { RxTableViewDelegateProxy(parentObject: $0) } + +*/ +public protocol DelegateProxyType: AnyObject { + associatedtype ParentObject: AnyObject + associatedtype Delegate + + /// It is require that enumerate call `register` of the extended DelegateProxy subclasses here. + static func registerKnownImplementations() + + /// Unique identifier for delegate + static var identifier: UnsafeRawPointer { get } + + /// Returns designated delegate property for object. + /// + /// Objects can have multiple delegate properties. + /// + /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. + /// + /// It's abstract method. + /// + /// - parameter object: Object that has delegate property. + /// - returns: Value of delegate property. + static func currentDelegate(for object: ParentObject) -> Delegate? + + /// Sets designated delegate property for object. + /// + /// Objects can have multiple delegate properties. + /// + /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. + /// + /// It's abstract method. + /// + /// - parameter delegate: Delegate value. + /// - parameter object: Object that has delegate property. + static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) + + /// Returns reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - returns: Value of reference if set or nil. + func forwardToDelegate() -> Delegate? + + /// Sets reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. + /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. + func setForwardToDelegate(_ forwardToDelegate: Delegate?, retainDelegate: Bool) +} + +// default implementations +extension DelegateProxyType { + /// Unique identifier for delegate + public static var identifier: UnsafeRawPointer { + let delegateIdentifier = ObjectIdentifier(Delegate.self) + let integerIdentifier = Int(bitPattern: delegateIdentifier) + return UnsafeRawPointer(bitPattern: integerIdentifier)! + } +} + +// workaround of Delegate: class +extension DelegateProxyType { + static func _currentDelegate(for object: ParentObject) -> AnyObject? { + currentDelegate(for: object).map { $0 as AnyObject } + } + + static func _setCurrentDelegate(_ delegate: AnyObject?, to object: ParentObject) { + setCurrentDelegate(castOptionalOrFatalError(delegate), to: object) + } + + func _forwardToDelegate() -> AnyObject? { + self.forwardToDelegate().map { $0 as AnyObject } + } + + func _setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) { + self.setForwardToDelegate(castOptionalOrFatalError(forwardToDelegate), retainDelegate: retainDelegate) + } +} + +extension DelegateProxyType { + + /// Store DelegateProxy subclass to factory. + /// When make 'Rx*DelegateProxy' subclass, call 'Rx*DelegateProxySubclass.register(for:_)' 1 time, or use it in DelegateProxyFactory + /// 'Rx*DelegateProxy' can have one subclass implementation per concrete ParentObject type. + /// Should call it from concrete DelegateProxy type, not generic. + public static func register(make: @escaping (Parent) -> Self) { + self.factory.extend(make: make) + } + + /// Creates new proxy for target object. + /// Should not call this function directory, use 'DelegateProxy.proxy(for:)' + public static func createProxy(for object: AnyObject) -> Self { + castOrFatalError(factory.createProxy(for: object)) + } + + /// Returns existing proxy for object or installs new instance of delegate proxy. + /// + /// - parameter object: Target object on which to install delegate proxy. + /// - returns: Installed instance of delegate proxy. + /// + /// + /// extension Reactive where Base: UISearchBar { + /// + /// public var delegate: DelegateProxy { + /// return RxSearchBarDelegateProxy.proxy(for: base) + /// } + /// + /// public var text: ControlProperty { + /// let source: Observable = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) + /// ... + /// } + /// } + public static func proxy(for object: ParentObject) -> Self { + MainScheduler.ensureRunningOnMainThread() + + let maybeProxy = self.assignedProxy(for: object) + + let proxy: AnyObject + if let existingProxy = maybeProxy { + proxy = existingProxy + } + else { + proxy = castOrFatalError(self.createProxy(for: object)) + self.assignProxy(proxy, toObject: object) + assert(self.assignedProxy(for: object) === proxy) + } + let currentDelegate = self._currentDelegate(for: object) + let delegateProxy: Self = castOrFatalError(proxy) + + if currentDelegate !== delegateProxy { + delegateProxy._setForwardToDelegate(currentDelegate, retainDelegate: false) + assert(delegateProxy._forwardToDelegate() === currentDelegate) + self._setCurrentDelegate(proxy, to: object) + assert(self._currentDelegate(for: object) === proxy) + assert(delegateProxy._forwardToDelegate() === currentDelegate) + } + + return delegateProxy + } + + /// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate. + /// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations. + /// + /// - parameter forwardDelegate: Delegate object to set. + /// - parameter retainDelegate: Retain `forwardDelegate` while it's being set. + /// - parameter onProxyForObject: Object that has `delegate` property. + /// - returns: Disposable object that can be used to clear forward delegate. + public static func installForwardDelegate(_ forwardDelegate: Delegate, retainDelegate: Bool, onProxyForObject object: ParentObject) -> Disposable { + weak var weakForwardDelegate: AnyObject? = forwardDelegate as AnyObject + let proxy = self.proxy(for: object) + + assert(proxy._forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" + + "If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" + + " This is the source object value: \(object)\n" + + " This is the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" + + "Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n") + + proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate) + + return Disposables.create { + MainScheduler.ensureRunningOnMainThread() + + let delegate: AnyObject? = weakForwardDelegate + + assert(delegate == nil || proxy._forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)") + + proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate) + } + } +} + + +// private extensions +extension DelegateProxyType { + private static var factory: DelegateProxyFactory { + DelegateProxyFactory.sharedFactory(for: self) + } + + private static func assignedProxy(for object: ParentObject) -> AnyObject? { + let maybeDelegate = objc_getAssociatedObject(object, self.identifier) + return castOptionalOrFatalError(maybeDelegate) + } + + private static func assignProxy(_ proxy: AnyObject, toObject object: ParentObject) { + objc_setAssociatedObject(object, self.identifier, proxy, .OBJC_ASSOCIATION_RETAIN) + } +} + +/// Describes an object that has a delegate. +public protocol HasDelegate: AnyObject { + /// Delegate type + associatedtype Delegate + + /// Delegate + var delegate: Delegate? { get set } +} + +extension DelegateProxyType where ParentObject: HasDelegate, Self.Delegate == ParentObject.Delegate { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.delegate + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.delegate = delegate + } +} + +/// Describes an object that has a data source. +public protocol HasDataSource: AnyObject { + /// Data source type + associatedtype DataSource + + /// Data source + var dataSource: DataSource? { get set } +} + +extension DelegateProxyType where ParentObject: HasDataSource, Self.Delegate == ParentObject.DataSource { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.dataSource + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.dataSource = delegate + } +} + +/// Describes an object that has a prefetch data source. +@available(iOS 10.0, tvOS 10.0, *) +public protocol HasPrefetchDataSource: AnyObject { + /// Prefetch data source type + associatedtype PrefetchDataSource + + /// Prefetch data source + var prefetchDataSource: PrefetchDataSource? { get set } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension DelegateProxyType where ParentObject: HasPrefetchDataSource, Self.Delegate == ParentObject.PrefetchDataSource { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.prefetchDataSource + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.prefetchDataSource = delegate + } +} + + #if os(iOS) || os(tvOS) + import UIKit + + extension ObservableType { + func subscribeProxyDataSource(ofObject object: DelegateProxy.ParentObject, dataSource: DelegateProxy.Delegate, retainDataSource: Bool, binding: @escaping (DelegateProxy, Event) -> Void) + -> Disposable + where DelegateProxy.ParentObject: UIView + , DelegateProxy.Delegate: AnyObject { + let proxy = DelegateProxy.proxy(for: object) + let unregisterDelegate = DelegateProxy.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object) + + // Do not perform layoutIfNeeded if the object is still not in the view hierarchy + if object.window != nil { + // this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75) + object.layoutIfNeeded() + } + + let subscription = self.asObservable() + .observe(on:MainScheduler()) + .catch { error in + bindingError(error) + return Observable.empty() + } + // source can never end, otherwise it would release the subscriber, and deallocate the data source + .concat(Observable.never()) + .take(until: object.rx.deallocated) + .subscribe { [weak object] (event: Event) in + + if let object = object { + assert(proxy === DelegateProxy.currentDelegate(for: object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: DelegateProxy.currentDelegate(for: object)))") + } + + binding(proxy, event) + + switch event { + case .error(let error): + bindingError(error) + unregisterDelegate.dispose() + case .completed: + unregisterDelegate.dispose() + default: + break + } + } + + return Disposables.create { [weak object] in + subscription.dispose() + + if object?.window != nil { + object?.layoutIfNeeded() + } + + unregisterDelegate.dispose() + } + } + } + + #endif + + /** + + To add delegate proxy subclasses call `DelegateProxySubclass.register()` in `registerKnownImplementations` or in some other + part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). + + class RxScrollViewDelegateProxy: DelegateProxy { + public static func registerKnownImplementations() { + self.register { RxTableViewDelegateProxy(parentObject: $0) } + } + ... + + + */ + private class DelegateProxyFactory { + private static var _sharedFactories: [UnsafeRawPointer: DelegateProxyFactory] = [:] + + fileprivate static func sharedFactory(for proxyType: DelegateProxy.Type) -> DelegateProxyFactory { + MainScheduler.ensureRunningOnMainThread() + let identifier = DelegateProxy.identifier + if let factory = _sharedFactories[identifier] { + return factory + } + let factory = DelegateProxyFactory(for: proxyType) + _sharedFactories[identifier] = factory + DelegateProxy.registerKnownImplementations() + return factory + } + + private var _factories: [ObjectIdentifier: ((AnyObject) -> AnyObject)] + private var _delegateProxyType: Any.Type + private var _identifier: UnsafeRawPointer + + private init(for proxyType: DelegateProxy.Type) { + self._factories = [:] + self._delegateProxyType = proxyType + self._identifier = proxyType.identifier + } + + fileprivate func extend(make: @escaping (ParentObject) -> DelegateProxy) { + MainScheduler.ensureRunningOnMainThread() + precondition(self._identifier == DelegateProxy.identifier, "Delegate proxy has inconsistent identifier") + guard self._factories[ObjectIdentifier(ParentObject.self)] == nil else { + rxFatalError("The factory of \(ParentObject.self) is duplicated. DelegateProxy is not allowed of duplicated base object type.") + } + self._factories[ObjectIdentifier(ParentObject.self)] = { make(castOrFatalError($0)) } + } + + fileprivate func createProxy(for object: AnyObject) -> AnyObject { + MainScheduler.ensureRunningOnMainThread() + var maybeMirror: Mirror? = Mirror(reflecting: object) + while let mirror = maybeMirror { + if let factory = self._factories[ObjectIdentifier(mirror.subjectType)] { + return factory(object) + } + maybeMirror = mirror.superclassMirror + } + rxFatalError("DelegateProxy has no factory of \(object). Implement DelegateProxy subclass for \(object) first.") + } + } + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift new file mode 100644 index 00000000..9622c98d --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift @@ -0,0 +1,148 @@ +// +// Infallible+Bind.swift +// RxCocoa +// +// Created by Shai Mishali on 27/08/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension InfallibleType { + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element { + self.subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element? { + self.map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Subscribes to observable sequence using custom binder function. + + - parameter binder: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> Result) -> Result { + binder(self) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func bind(to binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return binder(self)(curriedArgument) + } + + - parameter binder: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { + binder(self)(curriedArgument) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind(onNext: @escaping (Element) -> Void) -> Disposable { + self.subscribe(onNext: onNext) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift new file mode 100644 index 00000000..500154aa --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift @@ -0,0 +1,103 @@ +// +// Observable+Bind.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableType { + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element { + self.subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter observers: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element? { + self.map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Subscribes to observable sequence using custom binder function. + + - parameter binder: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> Result) -> Result { + binder(self) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func bind(to binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return binder(self)(curriedArgument) + } + + - parameter binder: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { + binder(self)(curriedArgument) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind( + with object: Object, + onNext: @escaping (Object, Element) -> Void + ) -> Disposable { + self.subscribe(onNext: { [weak object] in + guard let object = object else { return } + onNext(object, $0) + }, + onError: { error in + rxFatalErrorInDebug("Binding error: \(error)") + }) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind(onNext: @escaping (Element) -> Void) -> Disposable { + self.subscribe(onNext: onNext, + onError: { error in + rxFatalErrorInDebug("Binding error: \(error)") + }) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift new file mode 100644 index 00000000..4abf8808 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift @@ -0,0 +1,161 @@ +// +// RxCocoaObjCRuntimeError+Extensions.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/9/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) + import RxCocoaRuntime +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) + /// RxCocoa ObjC runtime interception mechanism. + public enum RxCocoaInterceptionMechanism { + /// Unknown message interception mechanism. + case unknown + /// Key value observing interception mechanism. + case kvo + } + + /// RxCocoa ObjC runtime modification errors. + public enum RxCocoaObjCRuntimeError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error has occurred. + case unknown(target: AnyObject) + + /** + If the object is reporting a different class then it's real class, that means that there is probably + already some interception mechanism in place or something weird is happening. + + The most common case when this would happen is when using a combination of KVO (`observe`) and `sentMessage`. + + This error is easily resolved by just using `sentMessage` observing before `observe`. + + The reason why the other way around could create issues is because KVO will unregister it's interceptor + class and restore original class. Unfortunately that will happen no matter was there another interceptor + subclass registered in hierarchy or not. + + Failure scenario: + * KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`) + * `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`) + * then unobserving with KVO will restore class to be `OriginalClass` -> failure point (possibly a bug in KVO) + + The reason why changing order of observing works is because any interception method on unregistration + should return object's original real class (if that doesn't happen then it's really easy to argue that's a bug + in that interception mechanism). + + This library won't remove registered interceptor even if there aren't any observers left because + it's highly unlikely it would have any benefit in real world use cases, and it's even more + dangerous. + */ + case objectMessagesAlreadyBeingIntercepted(target: AnyObject, interceptionMechanism: RxCocoaInterceptionMechanism) + + /// Trying to observe messages for selector that isn't implemented. + case selectorNotImplemented(target: AnyObject) + + /// Core Foundation classes are usually toll free bridged. Those classes crash the program in case + /// `object_setClass` is performed on them. + /// + /// There is a possibility to just swizzle methods on original object, but since those won't be usual use + /// cases for this library, then an error will just be reported for now. + case cantInterceptCoreFoundationTollFreeBridgedObjects(target: AnyObject) + + /// Two libraries have simultaneously tried to modify ObjC runtime and that was detected. This can only + /// happen in scenarios where multiple interception libraries are used. + /// + /// To synchronize other libraries intercepting messages for an object, use `synchronized` on target object and + /// it's meta-class. + case threadingCollisionWithOtherInterceptionMechanism(target: AnyObject) + + /// For some reason saving original method implementation under RX namespace failed. + case savingOriginalForwardingMethodFailed(target: AnyObject) + + /// Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason. + case replacingMethodWithForwardingImplementation(target: AnyObject) + + /// Attempt to intercept one of the performance sensitive methods: + /// * class + /// * respondsToSelector: + /// * methodSignatureForSelector: + /// * forwardingTargetForSelector: + case observingPerformanceSensitiveMessages(target: AnyObject) + + /// Message implementation has unsupported return type (for example large struct). The reason why this is a error + /// is because in some cases intercepting sent messages requires replacing implementation with `_objc_msgForward_stret` + /// instead of `_objc_msgForward`. + /// + /// The unsupported cases should be fairly uncommon. + case observingMessagesWithUnsupportedReturnType(target: AnyObject) + } + + extension RxCocoaObjCRuntimeError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case let .unknown(target): + return "Unknown error occurred.\nTarget: `\(target)`" + case let .objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism): + let interceptionMechanismDescription = interceptionMechanism == .kvo ? "KVO" : "other interception mechanism" + return "Collision between RxCocoa interception mechanism and \(interceptionMechanismDescription)." + + " To resolve this conflict please use this interception mechanism first.\nTarget: \(target)" + case let .selectorNotImplemented(target): + return "Trying to observe messages for selector that isn't implemented.\nTarget: \(target)" + case let .cantInterceptCoreFoundationTollFreeBridgedObjects(target): + return "Interception of messages sent to Core Foundation isn't supported.\nTarget: \(target)" + case let .threadingCollisionWithOtherInterceptionMechanism(target): + return "Detected a conflict while modifying ObjC runtime.\nTarget: \(target)" + case let .savingOriginalForwardingMethodFailed(target): + return "Saving original method implementation failed.\nTarget: \(target)" + case let .replacingMethodWithForwardingImplementation(target): + return "Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.\nTarget: \(target)" + case let .observingPerformanceSensitiveMessages(target): + return "Attempt to intercept one of the performance sensitive methods. \nTarget: \(target)" + case let .observingMessagesWithUnsupportedReturnType(target): + return "Attempt to intercept a method with unsupported return type. \nTarget: \(target)" + } + } + } + + // MARK: Conversions `NSError` > `RxCocoaObjCRuntimeError` + + extension Error { + func rxCocoaErrorForTarget(_ target: AnyObject) -> RxCocoaObjCRuntimeError { + let error = self as NSError + + if error.domain == RXObjCRuntimeErrorDomain { + let errorCode = RXObjCRuntimeError(rawValue: error.code) ?? .unknown + + switch errorCode { + case .unknown: + return .unknown(target: target) + case .objectMessagesAlreadyBeingIntercepted: + let isKVO = (error.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false + return .objectMessagesAlreadyBeingIntercepted(target: target, interceptionMechanism: isKVO ? .kvo : .unknown) + case .selectorNotImplemented: + return .selectorNotImplemented(target: target) + case .cantInterceptCoreFoundationTollFreeBridgedObjects: + return .cantInterceptCoreFoundationTollFreeBridgedObjects(target: target) + case .threadingCollisionWithOtherInterceptionMechanism: + return .threadingCollisionWithOtherInterceptionMechanism(target: target) + case .savingOriginalForwardingMethodFailed: + return .savingOriginalForwardingMethodFailed(target: target) + case .replacingMethodWithForwardingImplementation: + return .replacingMethodWithForwardingImplementation(target: target) + case .observingPerformanceSensitiveMessages: + return .observingPerformanceSensitiveMessages(target: target) + case .observingMessagesWithUnsupportedReturnType: + return .observingMessagesWithUnsupportedReturnType(target: target) + @unknown default: + fatalError("Unhandled Objective C Runtime Error") + } + } + + return RxCocoaObjCRuntimeError.unknown(target: target) + } + } + +#endif + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift new file mode 100644 index 00000000..5a2c464b --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift @@ -0,0 +1,43 @@ +// +// RxTarget.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +import RxSwift + +class RxTarget : NSObject + , Disposable { + + private var retainSelf: RxTarget? + + override init() { + super.init() + self.retainSelf = self + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + } + + func dispose() { +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + self.retainSelf = nil + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift new file mode 100644 index 00000000..5c3cf3ca --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift @@ -0,0 +1,20 @@ +// +// SectionedViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 1/10/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Data source with access to underlying sectioned model. +public protocol SectionedViewDataSourceType { + /// Returns model at index path. + /// + /// In case data source doesn't contain any sections when this method is being called, `RxCocoaError.ItemsNotYetBound(object: self)` is thrown. + + /// - parameter indexPath: Model index path + /// - returns: Model at index path. + func model(at indexPath: IndexPath) throws -> Any +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Common/TextInput.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Common/TextInput.swift new file mode 100644 index 00000000..2268882f --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Common/TextInput.swift @@ -0,0 +1,78 @@ +// +// TextInput.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +#if os(iOS) || os(tvOS) + import UIKit + + /// Represents text input with reactive extensions. + public struct TextInput { + /// Base text input to extend. + public let base: Base + + /// Reactive wrapper for `text` property. + public let text: ControlProperty + + /// Initializes new text input. + /// + /// - parameter base: Base object. + /// - parameter text: Textual control property. + public init(base: Base, text: ControlProperty) { + self.base = base + self.text = text + } + } + + extension Reactive where Base: UITextField { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: base, text: self.text) + } + } + + extension Reactive where Base: UITextView { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: base, text: self.text) + } + } + +#endif + +#if os(macOS) + import Cocoa + + /// Represents text input with reactive extensions. + public struct TextInput { + /// Base text input to extend. + public let base: Base + + /// Reactive wrapper for `text` property. + public let text: ControlProperty + + /// Initializes new text input. + /// + /// - parameter base: Base object. + /// - parameter text: Textual control property. + public init(base: Base, text: ControlProperty) { + self.base = base + self.text = text + } + } + + extension Reactive where Base: NSTextField, Base: NSTextInputClient { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: self.base, text: self.text) + } + } + +#endif + + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift new file mode 100644 index 00000000..30026bf9 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift @@ -0,0 +1,68 @@ +// +// KVORepresentable+CoreGraphics.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import RxSwift +import CoreGraphics + +import Foundation + +#if arch(x86_64) || arch(arm64) + let CGRectType = "{CGRect={CGPoint=dd}{CGSize=dd}}" + let CGSizeType = "{CGSize=dd}" + let CGPointType = "{CGPoint=dd}" +#elseif arch(i386) || arch(arm) || os(watchOS) + let CGRectType = "{CGRect={CGPoint=ff}{CGSize=ff}}" + let CGSizeType = "{CGSize=ff}" + let CGPointType = "{CGPoint=ff}" +#endif + +extension CGRect : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGRectType) != 0 { + return nil + } + var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +extension CGPoint : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGPointType) != 0 { + return nil + } + var typedValue = CGPoint(x: 0, y: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +extension CGSize : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGSizeType) != 0 { + return nil + } + var typedValue = CGSize(width: 0, height: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift new file mode 100644 index 00000000..00d53dd0 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift @@ -0,0 +1,88 @@ +// +// KVORepresentable+Swift.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension Int : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int32Value) + } +} + +extension Int32 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int32Value) + } +} + +extension Int64 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int64Value) + } +} + +extension UInt : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uintValue) + } +} + +extension UInt32 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uint32Value) + } +} + +extension UInt64 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uint64Value) + } +} + +extension Bool : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.boolValue) + } +} + + +extension RawRepresentable where RawValue: KVORepresentable { + /// Constructs `Self` using optional KVO value. + init?(KVOValue: RawValue.KVOType?) { + guard let KVOValue = KVOValue else { + return nil + } + + guard let rawValue = RawValue(KVOValue: KVOValue) else { + return nil + } + + self.init(rawValue: rawValue) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift new file mode 100644 index 00000000..be12b332 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift @@ -0,0 +1,28 @@ +// +// KVORepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that is KVO representable (KVO mechanism can be used to observe it). +public protocol KVORepresentable { + /// Associated KVO type. + associatedtype KVOType + + /// Constructs `Self` using KVO value. + init?(KVOValue: KVOType) +} + +extension KVORepresentable { + /// Initializes `KVORepresentable` with optional value. + init?(KVOValue: KVOType?) { + guard let KVOValue = KVOValue else { + return nil + } + + self.init(KVOValue: KVOValue) + } +} + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift new file mode 100644 index 00000000..1be5a212 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift @@ -0,0 +1,60 @@ +// +// NSObject+Rx+KVORepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import Foundation +import RxSwift + +/// Key value observing options +public struct KeyValueObservingOptions: OptionSet { + /// Raw value + public let rawValue: UInt + + public init(rawValue: UInt) { + self.rawValue = rawValue + } + + /// Whether a sequence element should be sent to the observer immediately, before the subscribe method even returns. + public static let initial = KeyValueObservingOptions(rawValue: 1 << 0) + /// Whether to send updated values. + public static let new = KeyValueObservingOptions(rawValue: 1 << 1) +} + +extension Reactive where Base: NSObject { + + /** + Specialization of generic `observe` method. + + This is a special overload because to observe values of some type (for example `Int`), first values of KVO type + need to be observed (`NSNumber`), and then converted to result type. + + For more information take a look at `observe` method. + */ + public func observe(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable { + return self.observe(Element.KVOType.self, keyPath, options: options, retainSelf: retainSelf) + .map(Element.init) + } +} + +#if !DISABLE_SWIZZLING && !os(Linux) + // KVO + extension Reactive where Base: NSObject { + /** + Specialization of generic `observeWeakly` method. + + For more information take a look at `observeWeakly` method. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable { + return self.observeWeakly(Element.KVOType.self, keyPath, options: options) + .map(Element.init) + } + } +#endif + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift new file mode 100644 index 00000000..6e47cb24 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift @@ -0,0 +1,52 @@ +// +// NSObject+Rx+RawRepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import RxSwift + +import Foundation + +extension Reactive where Base: NSObject { + /** + Specialization of generic `observe` method. + + This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. + + It is useful for observing bridged ObjC enum values. + + For more information take a look at `observe` method. + */ + public func observe(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable where Element.RawValue: KVORepresentable { + return self.observe(Element.RawValue.KVOType.self, keyPath, options: options, retainSelf: retainSelf) + .map(Element.init) + } +} + +#if !DISABLE_SWIZZLING + + // observeWeakly + RawRepresentable + extension Reactive where Base: NSObject { + + /** + Specialization of generic `observeWeakly` method. + + This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. + + It is useful for observing bridged ObjC enum values. + + For more information take a look at `observeWeakly` method. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable where Element.RawValue: KVORepresentable { + return self.observeWeakly(Element.RawValue.KVOType.self, keyPath, options: options) + .map(Element.init) + } + } +#endif + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift new file mode 100644 index 00000000..2f157241 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift @@ -0,0 +1,569 @@ +// +// NSObject+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import Foundation +import RxSwift +#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) + import RxCocoaRuntime +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) +private var deallocatingSubjectTriggerContext: UInt8 = 0 +private var deallocatingSubjectContext: UInt8 = 0 +#endif +private var deallocatedSubjectTriggerContext: UInt8 = 0 +private var deallocatedSubjectContext: UInt8 = 0 + +#if !os(Linux) + +/** +KVO is a tricky mechanism. + +When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior. +When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior. + +KVO with weak references is especially tricky. For it to work, some kind of swizzling is required. +That can be done by + * replacing object class dynamically (like KVO does) + * by swizzling `dealloc` method on all instances for a class. + * some third method ... + +Both approaches can fail in certain scenarios: + * problems arise when swizzlers return original object class (like KVO does when nobody is observing) + * Problems can arise because replacing dealloc method isn't atomic operation (get implementation, + set implementation). + +Second approach is chosen. It can fail in case there are multiple libraries dynamically trying +to replace dealloc method. In case that isn't the case, it should be ok. +*/ +extension Reactive where Base: NSObject { + + + /** + Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set. + + `observe` is just a simple and performant wrapper around KVO mechanism. + + * it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`) + * it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`) + * the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc. + + If support for weak properties is needed or observing arbitrary or unknown relationships in the + ownership tree, `observeWeakly` is the preferred option. + - parameter type: Optional type hint of the observed sequence elements. + - parameter keyPath: Key path of property names to observe. + - parameter options: KVO mechanism notification options. + - parameter retainSelf: Retains self during observation if set `true`. + - returns: Observable sequence of objects on `keyPath`. + */ + public func observe(_ type: Element.Type, + _ keyPath: String, + options: KeyValueObservingOptions = [.new, .initial], + retainSelf: Bool = true) -> Observable { + KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable() + } + + /** + Observes values at the provided key path using the provided options. + + - parameter keyPath: A key path between the object and one of its properties. + - parameter options: Key-value observation options, defaults to `.new` and `.initial`. + + - note: When the object is deallocated, a completion event is emitted. + + - returns: An observable emitting value changes at the provided key path. + */ + public func observe(_ keyPath: KeyPath, + options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable { + Observable.create { [weak base] observer in + let observation = base?.observe(keyPath, options: options) { obj, _ in + observer.on(.next(obj[keyPath: keyPath])) + } + + return Disposables.create { observation?.invalidate() } + } + .take(until: base.rx.deallocated) + } +} + +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) +// KVO +extension Reactive where Base: NSObject { + /** + Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`. + + It can be used in all cases where `observe` can be used and additionally + + * because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown + * it can be used to observe `weak` properties + + **Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.** + - parameter type: Optional type hint of the observed sequence elements. + - parameter keyPath: Key path of property names to observe. + - parameter options: KVO mechanism notification options. + - returns: Observable sequence of objects on `keyPath`. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable { + return observeWeaklyKeyPathFor(self.base, keyPath: keyPath, options: options) + .map { n in + return n as? Element + } + } +} +#endif + +// Dealloc +extension Reactive where Base: AnyObject { + + /** + Observable sequence of object deallocated events. + + After object is deallocated one `()` element will be produced and sequence will immediately complete. + + - returns: Observable sequence of object deallocated events. + */ + public var deallocated: Observable { + return self.synchronized { + if let deallocObservable = objc_getAssociatedObject(self.base, &deallocatedSubjectContext) as? DeallocObservable { + return deallocObservable.subject + } + + let deallocObservable = DeallocObservable() + + objc_setAssociatedObject(self.base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return deallocObservable.subject + } + } + +#if !DISABLE_SWIZZLING && !os(Linux) + + /** + Observable sequence of message arguments that completes when object is deallocated. + + Each element is produced before message is invoked on target object. `methodInvoked` + exists in case observing of invoked messages is needed. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + In case some argument is `nil`, instance of `NSNull()` will be sent. + + - returns: Observable sequence of arguments passed to `selector` method. + */ + public func sentMessage(_ selector: Selector) -> Observable<[Any]> { + return self.synchronized { + // in case of dealloc selector replay subject behavior needs to be used + if selector == deallocSelector { + return self.deallocating.map { _ in [] } + } + + do { + let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) + return proxy.messageSent.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + /** + Observable sequence of message arguments that completes when object is deallocated. + + Each element is produced after message is invoked on target object. `sentMessage` + exists in case interception of sent messages before they were invoked is needed. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + In case some argument is `nil`, instance of `NSNull()` will be sent. + + - returns: Observable sequence of arguments passed to `selector` method. + */ + public func methodInvoked(_ selector: Selector) -> Observable<[Any]> { + return self.synchronized { + // in case of dealloc selector replay subject behavior needs to be used + if selector == deallocSelector { + return self.deallocated.map { _ in [] } + } + + + do { + let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) + return proxy.methodInvoked.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + /** + Observable sequence of object deallocating events. + + When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence + will immediately complete. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + - returns: Observable sequence of object deallocating events. + */ + public var deallocating: Observable<()> { + return self.synchronized { + do { + let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector) + return proxy.messageSent.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + private func registerMessageInterceptor(_ selector: Selector) throws -> T { + let rxSelector = RX_selector(selector) + let selectorReference = RX_reference_from_selector(rxSelector) + + let subject: T + if let existingSubject = objc_getAssociatedObject(self.base, selectorReference) as? T { + subject = existingSubject + } + else { + subject = T() + objc_setAssociatedObject( + self.base, + selectorReference, + subject, + .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + + if subject.isActive { + return subject + } + + var error: NSError? + let targetImplementation = RX_ensure_observing(self.base, selector, &error) + if targetImplementation == nil { + throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown + } + + subject.targetImplementation = targetImplementation! + + return subject + } +#endif +} + +// MARK: Message interceptors + +#if !DISABLE_SWIZZLING && !os(Linux) + + private protocol MessageInterceptorSubject: AnyObject { + init() + + var isActive: Bool { + get + } + + var targetImplementation: IMP { get set } + } + + private final class DeallocatingProxy + : MessageInterceptorSubject + , RXDeallocatingObserver { + typealias Element = () + + let messageSent = ReplaySubject<()>.create(bufferSize: 1) + + @objc var targetImplementation: IMP = RX_default_target_implementation() + + var isActive: Bool { + return self.targetImplementation != RX_default_target_implementation() + } + + init() { + } + + @objc func deallocating() { + self.messageSent.on(.next(())) + } + + deinit { + self.messageSent.on(.completed) + } + } + + private final class MessageSentProxy + : MessageInterceptorSubject + , RXMessageSentObserver { + typealias Element = [AnyObject] + + let messageSent = PublishSubject<[Any]>() + let methodInvoked = PublishSubject<[Any]>() + + @objc var targetImplementation: IMP = RX_default_target_implementation() + + var isActive: Bool { + return self.targetImplementation != RX_default_target_implementation() + } + + init() { + } + + @objc func messageSent(withArguments arguments: [Any]) { + self.messageSent.on(.next(arguments)) + } + + @objc func methodInvoked(withArguments arguments: [Any]) { + self.methodInvoked.on(.next(arguments)) + } + + deinit { + self.messageSent.on(.completed) + self.methodInvoked.on(.completed) + } + } + +#endif + + +private final class DeallocObservable { + let subject = ReplaySubject.create(bufferSize:1) + + init() { + } + + deinit { + self.subject.on(.next(())) + self.subject.on(.completed) + } +} + +// MARK: KVO + +#if !os(Linux) + +private protocol KVOObservableProtocol { + var target: AnyObject { get } + var keyPath: String { get } + var retainTarget: Bool { get } + var options: KeyValueObservingOptions { get } +} + +private final class KVOObserver + : _RXKVOObserver + , Disposable { + typealias Callback = (Any?) -> Void + + var retainSelf: KVOObserver? + + init(parent: KVOObservableProtocol, callback: @escaping Callback) { + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + + super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options.nsOptions, callback: callback) + self.retainSelf = self + } + + override func dispose() { + super.dispose() + self.retainSelf = nil + } + + deinit { + #if TRACE_RESOURCES + _ = Resources.decrementTotal() + #endif + } +} + +private final class KVOObservable + : ObservableType + , KVOObservableProtocol { + typealias Element = Element? + + unowned var target: AnyObject + var strongTarget: AnyObject? + + var keyPath: String + var options: KeyValueObservingOptions + var retainTarget: Bool + + init(object: AnyObject, keyPath: String, options: KeyValueObservingOptions, retainTarget: Bool) { + self.target = object + self.keyPath = keyPath + self.options = options + self.retainTarget = retainTarget + if retainTarget { + self.strongTarget = object + } + } + + func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element? { + let observer = KVOObserver(parent: self) { value in + if value as? NSNull != nil { + observer.on(.next(nil)) + return + } + observer.on(.next(value as? Element)) + } + + return Disposables.create(with: observer.dispose) + } + +} + +private extension KeyValueObservingOptions { + var nsOptions: NSKeyValueObservingOptions { + var result: UInt = 0 + if self.contains(.new) { + result |= NSKeyValueObservingOptions.new.rawValue + } + if self.contains(.initial) { + result |= NSKeyValueObservingOptions.initial.rawValue + } + + return NSKeyValueObservingOptions(rawValue: result) + } +} + +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) + + private func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: KeyValueObservingOptions) -> Observable { + let components = keyPath.components(separatedBy: ".").filter { $0 != "self" } + + let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options) + .finishWithNilWhenDealloc(target) + + if !options.isDisjoint(with: .initial) { + return observable + } + else { + return observable + .skip(1) + } + } + + // This should work correctly + // Identifiers can't contain `,`, so the only place where `,` can appear + // is as a delimiter. + // This means there is `W` as element in an array of property attributes. + private func isWeakProperty(_ properyRuntimeInfo: String) -> Bool { + properyRuntimeInfo.range(of: ",W,") != nil + } + + private extension ObservableType where Element == AnyObject? { + func finishWithNilWhenDealloc(_ target: NSObject) + -> Observable { + let deallocating = target.rx.deallocating + + return deallocating + .map { _ in + return Observable.just(nil) + } + .startWith(self.asObservable()) + .switchLatest() + } + } + + private func observeWeaklyKeyPathFor( + _ target: NSObject, + keyPathSections: [String], + options: KeyValueObservingOptions + ) -> Observable { + + weak var weakTarget: AnyObject? = target + + let propertyName = keyPathSections[0] + let remainingPaths = Array(keyPathSections[1.. + + // KVO recursion for value changes + return propertyObservable + .flatMapLatest { (nextTarget: AnyObject?) -> Observable in + if nextTarget == nil { + return Observable.just(nil) + } + let nextObject = nextTarget! as? NSObject + + let strongTarget: AnyObject? = weakTarget + + if nextObject == nil { + return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName)) + } + + // if target is alive, then send change + // if it's deallocated, don't send anything + if strongTarget == nil { + return Observable.empty() + } + + let nextElementsObservable = keyPathSections.count == 1 + ? Observable.just(nextTarget) + : observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options) + + if isWeak { + return nextElementsObservable + .finishWithNilWhenDealloc(nextObject!) + } + else { + return nextElementsObservable + } + } + } +#endif + +// MARK: Constants + +private let deallocSelector = NSSelectorFromString("dealloc") + +// MARK: AnyObject + Reactive + +extension Reactive where Base: AnyObject { + func synchronized( _ action: () -> T) -> T { + objc_sync_enter(self.base) + let result = action() + objc_sync_exit(self.base) + return result + } +} + +extension Reactive where Base: AnyObject { + /** + Helper to make sure that `Observable` returned from `createCachedObservable` is only created once. + This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`. + */ + func lazyInstanceObservable(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T { + if let value = objc_getAssociatedObject(self.base, key) { + return value as! T + } + + let observable = createCachedObservable() + + objc_setAssociatedObject(self.base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + + return observable + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift new file mode 100644 index 00000000..30ffa2bf --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift @@ -0,0 +1,31 @@ +// +// NotificationCenter+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import RxSwift + +extension Reactive where Base: NotificationCenter { + /** + Transforms notifications posted to notification center to observable sequence of notifications. + + - parameter name: Optional name used to filter notifications. + - parameter object: Optional object used to filter notifications. + - returns: Observable sequence of posted notifications. + */ + public func notification(_ name: Notification.Name?, object: AnyObject? = nil) -> Observable { + return Observable.create { [weak object] observer in + let nsObserver = self.base.addObserver(forName: name, object: object, queue: nil) { notification in + observer.on(.next(notification)) + } + + return Disposables.create { + self.base.removeObserver(nsObserver) + } + } + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift new file mode 100644 index 00000000..93e65ccf --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift @@ -0,0 +1,240 @@ +// +// URLSession+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import RxSwift + +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +/// RxCocoa URL errors. +public enum RxCocoaURLError + : Swift.Error { + /// Unknown error occurred. + case unknown + /// Response is not NSHTTPURLResponse + case nonHTTPResponse(response: URLResponse) + /// Response is not successful. (not in `200 ..< 300` range) + case httpRequestFailed(response: HTTPURLResponse, data: Data?) + /// Deserialization error. + case deserializationError(error: Swift.Error) +} + +extension RxCocoaURLError + : CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error has occurred." + case let .nonHTTPResponse(response): + return "Response is not NSHTTPURLResponse `\(response)`." + case let .httpRequestFailed(response, _): + return "HTTP request failed with `\(response.statusCode)`." + case let .deserializationError(error): + return "Error during deserialization of the response: \(error)" + } + } +} + +private func escapeTerminalString(_ value: String) -> String { + return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil) +} + +private func convertURLRequestToCurlCommand(_ request: URLRequest) -> String { + let method = request.httpMethod ?? "GET" + var returnValue = "curl -X \(method) " + + if let httpBody = request.httpBody { + let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8) + if let body = maybeBody { + returnValue += "-d \"\(escapeTerminalString(body))\" " + } + } + + for (key, value) in request.allHTTPHeaderFields ?? [:] { + let escapedKey = escapeTerminalString(key as String) + let escapedValue = escapeTerminalString(value as String) + returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" " + } + + let URLString = request.url?.absoluteString ?? "" + + returnValue += "\n\"\(escapeTerminalString(URLString))\"" + + returnValue += " -i -v" + + return returnValue +} + +private func convertResponseToString(_ response: URLResponse?, _ error: NSError?, _ interval: TimeInterval) -> String { + let ms = Int(interval * 1000) + + if let response = response as? HTTPURLResponse { + if 200 ..< 300 ~= response.statusCode { + return "Success (\(ms)ms): Status \(response.statusCode)" + } + else { + return "Failure (\(ms)ms): Status \(response.statusCode)" + } + } + + if let error = error { + if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { + return "Canceled (\(ms)ms)" + } + return "Failure (\(ms)ms): NSError > \(error)" + } + + return "" +} + +extension Reactive where Base: URLSession { + /** + Observable sequence of responses for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + - parameter request: URL request. + - returns: Observable sequence of URL responses. + */ + public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> { + return Observable.create { observer in + + // smart compiler should be able to optimize this out + let d: Date? + + if URLSession.rx.shouldLogRequest(request) { + d = Date() + } + else { + d = nil + } + + let task = self.base.dataTask(with: request) { data, response, error in + + if URLSession.rx.shouldLogRequest(request) { + let interval = Date().timeIntervalSince(d ?? Date()) + print(convertURLRequestToCurlCommand(request)) + #if os(Linux) + print(convertResponseToString(response, error.flatMap { $0 as NSError }, interval)) + #else + print(convertResponseToString(response, error.map { $0 as NSError }, interval)) + #endif + } + + guard let response = response, let data = data else { + observer.on(.error(error ?? RxCocoaURLError.unknown)) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response))) + return + } + + observer.on(.next((httpResponse, data))) + observer.on(.completed) + } + + task.resume() + + return Disposables.create(with: task.cancel) + } + } + + /** + Observable sequence of response data for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + - parameter request: URL request. + - returns: Observable sequence of response data. + */ + public func data(request: URLRequest) -> Observable { + return self.response(request: request).map { pair -> Data in + if 200 ..< 300 ~= pair.0.statusCode { + return pair.1 + } + else { + throw RxCocoaURLError.httpRequestFailed(response: pair.0, data: pair.1) + } + } + } + + /** + Observable sequence of response JSON for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + If there is an error during JSON deserialization observable sequence will fail with that error. + + - parameter request: URL request. + - returns: Observable sequence of response JSON. + */ + public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable { + return self.data(request: request).map { data -> Any in + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch let error { + throw RxCocoaURLError.deserializationError(error: error) + } + } + } + + /** + Observable sequence of response JSON for GET request with `URL`. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + If there is an error during JSON deserialization observable sequence will fail with that error. + + - parameter url: URL of `NSURLRequest` request. + - returns: Observable sequence of response JSON. + */ + public func json(url: Foundation.URL) -> Observable { + self.json(request: URLRequest(url: url)) + } +} + +extension Reactive where Base == URLSession { + /// Log URL requests to standard output in curl format. + public static var shouldLogRequest: (URLRequest) -> Bool = { _ in + #if DEBUG + return true + #else + return false + #endif + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RX.m b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RX.m new file mode 100644 index 00000000..cffbfbcc --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RX.m @@ -0,0 +1,10 @@ +// +// _RX.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RX.h" + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m new file mode 100644 index 00000000..36338a57 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m @@ -0,0 +1,147 @@ +// +// _RXDelegateProxy.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RXDelegateProxy.h" +#import "include/_RX.h" +#import "include/_RXObjCRuntime.h" + +@interface _RXDelegateProxy () { + id __weak __forwardToDelegate; +} + +@property (nonatomic, strong) id strongForwardDelegate; + +@end + +static NSMutableDictionary *voidSelectorsPerClass = nil; + +@implementation _RXDelegateProxy + ++(NSSet*)collectVoidSelectorsForProtocol:(Protocol *)protocol { + NSMutableSet *selectors = [NSMutableSet set]; + + unsigned int protocolMethodCount = 0; + struct objc_method_description *pMethods = protocol_copyMethodDescriptionList(protocol, NO, YES, &protocolMethodCount); + + for (unsigned int i = 0; i < protocolMethodCount; ++i) { + struct objc_method_description method = pMethods[i]; + if (RX_is_method_with_description_void(method)) { + [selectors addObject:SEL_VALUE(method.name)]; + } + } + + free(pMethods); + + unsigned int numberOfBaseProtocols = 0; + Protocol * __unsafe_unretained * pSubprotocols = protocol_copyProtocolList(protocol, &numberOfBaseProtocols); + + for (unsigned int i = 0; i < numberOfBaseProtocols; ++i) { + [selectors unionSet:[self collectVoidSelectorsForProtocol:pSubprotocols[i]]]; + } + + free(pSubprotocols); + + return selectors; +} + ++(void)initialize { + @synchronized (_RXDelegateProxy.class) { + if (voidSelectorsPerClass == nil) { + voidSelectorsPerClass = [[NSMutableDictionary alloc] init]; + } + + NSMutableSet *voidSelectors = [NSMutableSet set]; + +#define CLASS_HIERARCHY_MAX_DEPTH 100 + + NSInteger classHierarchyDepth = 0; + Class targetClass = NULL; + + for (classHierarchyDepth = 0, targetClass = self; + classHierarchyDepth < CLASS_HIERARCHY_MAX_DEPTH && targetClass != nil; + ++classHierarchyDepth, targetClass = class_getSuperclass(targetClass) + ) { + unsigned int count; + Protocol *__unsafe_unretained *pProtocols = class_copyProtocolList(targetClass, &count); + + for (unsigned int i = 0; i < count; i++) { + NSSet *selectorsForProtocol = [self collectVoidSelectorsForProtocol:pProtocols[i]]; + [voidSelectors unionSet:selectorsForProtocol]; + } + + free(pProtocols); + } + + if (classHierarchyDepth == CLASS_HIERARCHY_MAX_DEPTH) { + NSLog(@"Detected weird class hierarchy with depth over %d. Starting with this class -> %@", CLASS_HIERARCHY_MAX_DEPTH, self); +#if DEBUG + abort(); +#endif + } + + voidSelectorsPerClass[CLASS_VALUE(self)] = voidSelectors; + } +} + +-(id)_forwardToDelegate { + return __forwardToDelegate; +} + +-(void)_setForwardToDelegate:(id __nullable)forwardToDelegate retainDelegate:(BOOL)retainDelegate { + __forwardToDelegate = forwardToDelegate; + if (retainDelegate) { + self.strongForwardDelegate = forwardToDelegate; + } + else { + self.strongForwardDelegate = nil; + } +} + +-(BOOL)hasWiredImplementationForSelector:(SEL)selector { + return [super respondsToSelector:selector]; +} + +-(BOOL)voidDelegateMethodsContain:(SEL)selector { + @synchronized(_RXDelegateProxy.class) { + NSSet *voidSelectors = voidSelectorsPerClass[CLASS_VALUE(self.class)]; + NSAssert(voidSelectors != nil, @"Set of allowed methods not initialized"); + return [voidSelectors containsObject:SEL_VALUE(selector)]; + } +} + +-(void)forwardInvocation:(NSInvocation *)anInvocation { + BOOL isVoid = RX_is_method_signature_void(anInvocation.methodSignature); + NSArray *arguments = nil; + if (isVoid) { + arguments = RX_extract_arguments(anInvocation); + [self _sentMessage:anInvocation.selector withArguments:arguments]; + } + + if (self._forwardToDelegate && [self._forwardToDelegate respondsToSelector:anInvocation.selector]) { + [anInvocation invokeWithTarget:self._forwardToDelegate]; + } + + if (isVoid) { + [self _methodInvoked:anInvocation.selector withArguments:arguments]; + } +} + +// abstract method +-(void)_sentMessage:(SEL)selector withArguments:(NSArray *)arguments { + +} + +// abstract method +-(void)_methodInvoked:(SEL)selector withArguments:(NSArray *)arguments { + +} + +-(void)dealloc { +} + +@end diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m new file mode 100644 index 00000000..fc8fb75c --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m @@ -0,0 +1,54 @@ +// +// _RXKVOObserver.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RXKVOObserver.h" + +@interface _RXKVOObserver () + +@property (nonatomic, unsafe_unretained) id target; +@property (nonatomic, strong ) id retainedTarget; +@property (nonatomic, copy ) NSString *keyPath; +@property (nonatomic, copy ) void (^callback)(id); + +@end + +@implementation _RXKVOObserver + +-(instancetype)initWithTarget:(id)target + retainTarget:(BOOL)retainTarget + keyPath:(NSString*)keyPath + options:(NSKeyValueObservingOptions)options + callback:(void (^)(id))callback { + self = [super init]; + if (!self) return nil; + + self.target = target; + if (retainTarget) { + self.retainedTarget = target; + } + self.keyPath = keyPath; + self.callback = callback; + + [self.target addObserver:self forKeyPath:self.keyPath options:options context:nil]; + + return self; +} + +-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + @synchronized(self) { + self.callback(change[NSKeyValueChangeNewKey]); + } +} + +-(void)dispose { + [self.target removeObserver:self forKeyPath:self.keyPath context:nil]; + self.target = nil; + self.retainedTarget = nil; +} + +@end diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m new file mode 100644 index 00000000..2e685aaa --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m @@ -0,0 +1,1062 @@ +// +// _RXObjCRuntime.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import +#import +#import +#import +#import + +#import "include/_RX.h" +#import "include/_RXObjCRuntime.h" + +// self + cmd +#define HIDDEN_ARGUMENT_COUNT 2 + +#if !DISABLE_SWIZZLING + +#define NSErrorParam NSError *__autoreleasing __nullable * __nullable + +@class RXObjCRuntime; + +BOOL RXAbortOnThreadingHazard = NO; + +typedef NSInvocation *NSInvocationRef; +typedef NSMethodSignature *NSMethodSignatureRef; +typedef unsigned char rx_uchar; +typedef unsigned short rx_ushort; +typedef unsigned int rx_uint; +typedef unsigned long rx_ulong; +typedef id (^rx_block)(id); +typedef BOOL (^RXInterceptWithOptimizedObserver)(RXObjCRuntime * __nonnull self, Class __nonnull class, SEL __nonnull selector, NSErrorParam error); + +static CFTypeID defaultTypeID; +static SEL deallocSelector; + +static int RxSwizzlingTargetClassKey = 0; + +#if TRACE_RESOURCES +_Atomic static int32_t numberOInterceptedMethods = 0; +_Atomic static int32_t numberOfForwardedMethods = 0; +#endif + +#define THREADING_HAZARD(class) \ + NSLog(@"There was a problem swizzling on `%@`.\nYou have probably two libraries performing swizzling in runtime.\nWe didn't want to crash your program, but this is not good ...\nYou an solve this problem by either not using swizzling in this library, removing one of those other libraries, or making sure that swizzling parts are synchronized (only perform them on main thread).\nAnd yes, this message will self destruct when you clear the console, and since it's non deterministic, the problem could still exist and it will be hard for you to reproduce it.", NSStringFromClass(class)); ABORT_IN_DEBUG if (RXAbortOnThreadingHazard) { abort(); } + +#define ALWAYS(condition, message) if (!(condition)) { [NSException raise:@"RX Invalid Operator" format:@"%@", message]; } +#define ALWAYS_WITH_INFO(condition, message) NSAssert((condition), @"%@ [%@] > %@", NSStringFromClass(class), NSStringFromSelector(selector), (message)) +#define C_ALWAYS(condition, message) NSCAssert((condition), @"%@ [%@] > %@", NSStringFromClass(class), NSStringFromSelector(selector), (message)) + +#define RX_PREFIX @"_RX_namespace_" + +#define RX_ARG_id(value) ((value) ?: [NSNull null]) +#define RX_ARG_char(value) [NSNumber numberWithChar:value] +#define RX_ARG_short(value) [NSNumber numberWithShort:value] +#define RX_ARG_int(value) [NSNumber numberWithInt:value] +#define RX_ARG_long(value) [NSNumber numberWithLong:value] +#define RX_ARG_BOOL(value) [NSNumber numberWithBool:value] +#define RX_ARG_SEL(value) [NSNumber valueWithPointer:value] +#define RX_ARG_rx_uchar(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_ushort(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_uint(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_ulong(value) [NSNumber numberWithUnsignedLong:value] +#define RX_ARG_rx_block(value) ((id)(value) ?: [NSNull null]) +#define RX_ARG_float(value) [NSNumber numberWithFloat:value] +#define RX_ARG_double(value) [NSNumber numberWithDouble:value] + +typedef struct supported_type { + const char *encoding; +} supported_type_t; + +static supported_type_t supported_types[] = { + { .encoding = @encode(void)}, + { .encoding = @encode(id)}, + { .encoding = @encode(Class)}, + { .encoding = @encode(void (^)(void))}, + { .encoding = @encode(char)}, + { .encoding = @encode(short)}, + { .encoding = @encode(int)}, + { .encoding = @encode(long)}, + { .encoding = @encode(long long)}, + { .encoding = @encode(unsigned char)}, + { .encoding = @encode(unsigned short)}, + { .encoding = @encode(unsigned int)}, + { .encoding = @encode(unsigned long)}, + { .encoding = @encode(unsigned long long)}, + { .encoding = @encode(float)}, + { .encoding = @encode(double)}, + { .encoding = @encode(BOOL)}, + { .encoding = @encode(const char*)}, +}; + +NSString * __nonnull const RXObjCRuntimeErrorDomain = @"RXObjCRuntimeErrorDomain"; +NSString * __nonnull const RXObjCRuntimeErrorIsKVOKey = @"RXObjCRuntimeErrorIsKVOKey"; + +BOOL RX_return_type_is_supported(const char *type) { + if (type == nil) { + return NO; + } + + for (int i = 0; i < sizeof(supported_types) / sizeof(supported_type_t); ++i) { + if (supported_types[i].encoding[0] != type[0]) { + continue; + } + if (strcmp(supported_types[i].encoding, type) == 0) { + return YES; + } + } + + return NO; +} + +static BOOL RX_method_has_supported_return_type(Method method) { + const char *rawEncoding = method_getTypeEncoding(method); + ALWAYS(rawEncoding != nil, @"Example encoding method is nil."); + + NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:rawEncoding]; + ALWAYS(methodSignature != nil, @"Method signature method is nil."); + + return RX_return_type_is_supported(methodSignature.methodReturnType); +} + +SEL __nonnull RX_selector(SEL __nonnull selector) { + NSString *selectorString = NSStringFromSelector(selector); + return NSSelectorFromString([RX_PREFIX stringByAppendingString:selectorString]); +} + +#endif + +BOOL RX_is_method_signature_void(NSMethodSignature * __nonnull methodSignature) { + const char *methodReturnType = methodSignature.methodReturnType; + return strcmp(methodReturnType, @encode(void)) == 0; +} + +BOOL RX_is_method_with_description_void(struct objc_method_description method) { + return strncmp(method.types, @encode(void), 1) == 0; +} + +id __nonnull RX_extract_argument_at_index(NSInvocation * __nonnull invocation, NSUInteger index) { + const char *argumentType = [invocation.methodSignature getArgumentTypeAtIndex:index]; + +#define RETURN_VALUE(type) \ + else if (strcmp(argumentType, @encode(type)) == 0) {\ + type val = 0; \ + [invocation getArgument:&val atIndex:index]; \ + return @(val); \ + } + + // Skip const type qualifier. + if (argumentType[0] == 'r') { + argumentType++; + } + + if (strcmp(argumentType, @encode(id)) == 0 + || strcmp(argumentType, @encode(Class)) == 0 + || strcmp(argumentType, @encode(void (^)(void))) == 0 + ) { + __unsafe_unretained id argument = nil; + [invocation getArgument:&argument atIndex:index]; + return argument; + } + RETURN_VALUE(char) + RETURN_VALUE(short) + RETURN_VALUE(int) + RETURN_VALUE(long) + RETURN_VALUE(long long) + RETURN_VALUE(unsigned char) + RETURN_VALUE(unsigned short) + RETURN_VALUE(unsigned int) + RETURN_VALUE(unsigned long) + RETURN_VALUE(unsigned long long) + RETURN_VALUE(float) + RETURN_VALUE(double) + RETURN_VALUE(BOOL) + RETURN_VALUE(const char *) + else { + NSUInteger size = 0; + NSGetSizeAndAlignment(argumentType, &size, NULL); + NSCParameterAssert(size > 0); + uint8_t data[size]; + [invocation getArgument:&data atIndex:index]; + + return [NSValue valueWithBytes:&data objCType:argumentType]; + } +} + +NSArray *RX_extract_arguments(NSInvocation *invocation) { + NSUInteger numberOfArguments = invocation.methodSignature.numberOfArguments; + NSUInteger numberOfVisibleArguments = numberOfArguments - HIDDEN_ARGUMENT_COUNT; + + NSCParameterAssert(numberOfVisibleArguments >= 0); + + NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:numberOfVisibleArguments]; + + for (NSUInteger index = HIDDEN_ARGUMENT_COUNT; index < numberOfArguments; ++index) { + [arguments addObject:RX_extract_argument_at_index(invocation, index) ?: [NSNull null]]; + } + + return arguments; +} + +IMP __nonnull RX_default_target_implementation(void) { + return _objc_msgForward; +} + +#if !DISABLE_SWIZZLING + +void * __nonnull RX_reference_from_selector(SEL __nonnull selector) { + return selector; +} + +static BOOL RX_forward_invocation(id __nonnull __unsafe_unretained self, NSInvocation *invocation) { + SEL originalSelector = RX_selector(invocation.selector); + + id messageSentObserver = objc_getAssociatedObject(self, originalSelector); + + if (messageSentObserver != nil) { + NSArray *arguments = RX_extract_arguments(invocation); + [messageSentObserver messageSentWithArguments:arguments]; + } + + if ([self respondsToSelector:originalSelector]) { + invocation.selector = originalSelector; + [invocation invokeWithTarget:self]; + + if (messageSentObserver != nil) { + NSArray *arguments = RX_extract_arguments(invocation); + [messageSentObserver methodInvokedWithArguments:arguments]; + } + + return YES; + } + + return NO; +} + +static BOOL RX_responds_to_selector(id __nonnull __unsafe_unretained self, SEL selector) { + Class class = object_getClass(self); + if (class == nil) { return NO; } + + Method m = class_getInstanceMethod(class, selector); + return m != nil; + +} + +static NSMethodSignatureRef RX_method_signature(id __nonnull __unsafe_unretained self, SEL selector) { + Class class = object_getClass(self); + if (class == nil) { return nil; } + + Method method = class_getInstanceMethod(class, selector); + if (method == nil) { return nil; } + + const char *encoding = method_getTypeEncoding(method); + if (encoding == nil) { return nil; } + + return [NSMethodSignature signatureWithObjCTypes:encoding]; +} + +static NSString * __nonnull RX_method_encoding(Method __nonnull method) { + const char *typeEncoding = method_getTypeEncoding(method); + ALWAYS(typeEncoding != nil, @"Method encoding is nil."); + + NSString *encoding = [NSString stringWithCString:typeEncoding encoding:NSASCIIStringEncoding]; + ALWAYS(encoding != nil, @"Can't convert encoding to NSString."); + return encoding; +} + +@interface RXObjCRuntime: NSObject + +@property (nonatomic, assign) pthread_mutex_t lock; + +@property (nonatomic, strong) NSMutableSet *classesThatSupportObservingByForwarding; +@property (nonatomic, strong) NSMutableDictionary *> *forwardedSelectorsByClass; + +@property (nonatomic, strong) NSMutableDictionary *dynamicSubclassByRealClass; +@property (nonatomic, strong) NSMutableDictionary*> *interceptorIMPbySelectorsByClass; + ++(RXObjCRuntime*)instance; + +-(void)performLocked:(void (^)(RXObjCRuntime* __nonnull))action; +-(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error; +-(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector + ofClass:(Class __nonnull)class + newImplementationGenerator:(IMP(^)(void))newImplementationGenerator +replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator + error:(NSErrorParam)error; + + ++(void)registerOptimizedObserver:(RXInterceptWithOptimizedObserver)registration encodedAs:(SEL)selector; + +@end + +/** + All API methods perform work on locked instance of `RXObjCRuntime`. In that way it's easy to prove + that every action is properly locked. + */ +IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSErrorParam error) { + __block IMP targetImplementation = nil; + // Target is the second object that needs to be synchronized to TRY to make sure other swizzling framework + // won't do something in parallel. + // Even though this is too fine grained locking and more coarse grained locks should exist, this is just in case + // someone calls this method directly without any external lock. + @synchronized(target) { + // The only other resource that all other swizzling libraries have in common without introducing external + // dependencies is class object. + // + // It is polite to try to synchronize it in hope other unknown entities will also attempt to do so. + // It's like trying to figure out how to communicate with aliens without actually communicating, + // save for the fact that aliens are people, programmers, authors of swizzling libraries. + @synchronized([target class]) { + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + targetImplementation = [self ensurePrepared:target + forObserving:selector + error:error]; + }]; + } + } + + return targetImplementation; +} + +// bodies + +#define FORWARD_BODY(invocation) if (RX_forward_invocation(self, NAME_CAT(_, 0, invocation))) { return; } + +#define RESPONDS_TO_SELECTOR_BODY(selector) if (RX_responds_to_selector(self, NAME_CAT(_, 0, selector))) return YES; + +#define CLASS_BODY(...) return actAsClass; + +#define METHOD_SIGNATURE_FOR_SELECTOR_BODY(selector) \ + NSMethodSignatureRef methodSignature = RX_method_signature(self, NAME_CAT(_, 0, selector)); \ + if (methodSignature != nil) { \ + return methodSignature; \ + } + +#define DEALLOCATING_BODY(...) \ + id observer = objc_getAssociatedObject(self, rxSelector); \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer deallocating]; \ + } + +#define OBSERVE_BODY(...) \ + id observer = objc_getAssociatedObject(self, rxSelector); \ + \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer messageSentWithArguments:@[COMMA_DELIMITED_ARGUMENTS(__VA_ARGS__)]]; \ + } \ + + +#define OBSERVE_INVOKED_BODY(...) \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer methodInvokedWithArguments:@[COMMA_DELIMITED_ARGUMENTS(__VA_ARGS__)]]; \ + } \ + + +#define BUILD_ARG_WRAPPER(type) RX_ARG_ ## type //RX_ARG_ ## type + +#define CAT(_1, _2, head, tail) RX_CAT2(head, tail) +#define SEPARATE_BY_COMMA(_1, _2, head, tail) head, tail +#define SEPARATE_BY_SPACE(_1, _2, head, tail) head tail +#define SEPARATE_BY_UNDERSCORE(head, tail) RX_CAT2(RX_CAT2(head, _), tail) + +#define UNDERSCORE_TYPE_CAT(_1, index, type) RX_CAT2(_, type) // generates -> _type +#define NAME_CAT(_1, index, type) SEPARATE_BY_UNDERSCORE(type, index) // generates -> type_0 +#define TYPE_AND_NAME_CAT(_1, index, type) type SEPARATE_BY_UNDERSCORE(type, index) // generates -> type type_0 +#define NOT_NULL_ARGUMENT_CAT(_1, index, type) BUILD_ARG_WRAPPER(type)(NAME_CAT(_1, index, type)) // generates -> ((id)(type_0) ?: [NSNull null]) +#define EXAMPLE_PARAMETER(_1, index, type) RX_CAT2(_, type):(type)SEPARATE_BY_UNDERSCORE(type, index) // generates -> _type:(type)type_0 +#define SELECTOR_PART(_1, index, type) RX_CAT2(_, type:) // generates -> _type: + +#define COMMA_DELIMITED_ARGUMENTS(...) RX_FOREACH(_, SEPARATE_BY_COMMA, NOT_NULL_ARGUMENT_CAT, ## __VA_ARGS__) +#define ARGUMENTS(...) RX_FOREACH_COMMA(_, NAME_CAT, ## __VA_ARGS__) +#define DECLARE_ARGUMENTS(...) RX_FOREACH_COMMA(_, TYPE_AND_NAME_CAT, ## __VA_ARGS__) + +// optimized observe methods + +#define GENERATE_SELECTOR_IDENTIFIER(...) RX_CAT2(exampleSelector, RX_FOREACH(_, CAT, UNDERSCORE_TYPE_CAT, ## __VA_ARGS__)) + +#define GENERATE_METHOD_IDENTIFIER(...) RX_CAT2(swizzle, RX_FOREACH(_, CAT, UNDERSCORE_TYPE_CAT, ## __VA_ARGS__)) + +#define GENERATE_OBSERVE_METHOD_DECLARATION(...) \ + -(BOOL)GENERATE_METHOD_IDENTIFIER(__VA_ARGS__):(Class __nonnull)class \ + selector:(SEL)selector \ + error:(NSErrorParam)error { \ + + +#define BUILD_EXAMPLE_METHOD(return_value, ...) \ + +(return_value)RX_CAT2(RX_CAT2(example_, return_value), RX_FOREACH(_, SEPARATE_BY_SPACE, EXAMPLE_PARAMETER, ## __VA_ARGS__)) {} + +#define BUILD_EXAMPLE_METHOD_SELECTOR(return_value, ...) \ + RX_CAT2(RX_CAT2(example_, return_value), RX_FOREACH(_, SEPARATE_BY_SPACE, SELECTOR_PART, ## __VA_ARGS__)) + +#define SWIZZLE_OBSERVE_METHOD_DEFINITIONS(return_value, ...) \ + BUILD_EXAMPLE_METHOD(return_value, ## __VA_ARGS__) \ + SWIZZLE_METHOD(return_value, GENERATE_OBSERVE_METHOD_DECLARATION(return_value, ## __VA_ARGS__), OBSERVE_BODY, OBSERVE_INVOKED_BODY, ## __VA_ARGS__) \ + +#define SWIZZLE_OBSERVE_METHOD_BODY(return_value, ...) \ + __unused SEL GENERATE_SELECTOR_IDENTIFIER(return_value, ## __VA_ARGS__) = @selector(BUILD_EXAMPLE_METHOD_SELECTOR(return_value, ## __VA_ARGS__)); \ + [self registerOptimizedObserver:^BOOL(RXObjCRuntime * __nonnull self, Class __nonnull class, \ + SEL __nonnull selector, NSErrorParam error) { \ + return [self GENERATE_METHOD_IDENTIFIER(return_value, ## __VA_ARGS__):class selector:selector error:error]; \ + } encodedAs:GENERATE_SELECTOR_IDENTIFIER(return_value, ## __VA_ARGS__)]; \ + +// infrastructure method + +#define NO_BODY(...) + +#define SWIZZLE_INFRASTRUCTURE_METHOD(return_value, method_name, parameters, method_selector, body, ...) \ + SWIZZLE_METHOD(return_value, -(BOOL)method_name:(Class __nonnull)class parameters error:(NSErrorParam)error \ + { \ + SEL selector = method_selector; , body, NO_BODY, __VA_ARGS__) \ + + +// common base + +#define SWIZZLE_METHOD(return_value, method_prototype, body, invoked_body, ...) \ +method_prototype \ + __unused SEL rxSelector = RX_selector(selector); \ + IMP (^newImplementationGenerator)(void) = ^() { \ + __block IMP thisIMP = nil; \ + id newImplementation = ^return_value(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__)) { \ + body(__VA_ARGS__) \ + \ + struct objc_super superInfo = { \ + .receiver = self, \ + .super_class = class_getSuperclass(class) \ + }; \ + \ + return_value (*msgSend)(struct objc_super *, SEL DECLARE_ARGUMENTS(__VA_ARGS__)) \ + = (__typeof__(msgSend))objc_msgSendSuper; \ + @try { \ + return msgSend(&superInfo, selector ARGUMENTS(__VA_ARGS__)); \ + } \ + @finally { invoked_body(__VA_ARGS__) } \ + }; \ + \ + thisIMP = imp_implementationWithBlock(newImplementation); \ + return thisIMP; \ + }; \ + \ + IMP (^replacementImplementationGenerator)(IMP) = ^(IMP originalImplementation) { \ + __block return_value (*originalImplementationTyped)(__unsafe_unretained id, SEL DECLARE_ARGUMENTS(__VA_ARGS__) ) \ + = (__typeof__(originalImplementationTyped))(originalImplementation); \ + \ + __block IMP thisIMP = nil; \ + id implementationReplacement = ^return_value(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__) ) { \ + body(__VA_ARGS__) \ + @try { \ + return originalImplementationTyped(self, selector ARGUMENTS(__VA_ARGS__)); \ + } \ + @finally { invoked_body(__VA_ARGS__) } \ + }; \ + \ + thisIMP = imp_implementationWithBlock(implementationReplacement); \ + return thisIMP; \ + }; \ + \ + return [self ensureSwizzledSelector:selector \ + ofClass:class \ + newImplementationGenerator:newImplementationGenerator \ + replacementImplementationGenerator:replacementImplementationGenerator \ + error:error]; \ + } \ + + +@interface RXObjCRuntime (InfrastructureMethods) +@end + +// MARK: Infrastructure Methods + +@implementation RXObjCRuntime (InfrastructureMethods) + +SWIZZLE_INFRASTRUCTURE_METHOD( + void, + swizzleForwardInvocation, + , + @selector(forwardInvocation:), + FORWARD_BODY, + NSInvocationRef +) +SWIZZLE_INFRASTRUCTURE_METHOD( + BOOL, + swizzleRespondsToSelector, + , + @selector(respondsToSelector:), + RESPONDS_TO_SELECTOR_BODY, + SEL +) +SWIZZLE_INFRASTRUCTURE_METHOD( + Class __nonnull, + swizzleClass, + toActAs:(Class)actAsClass, + @selector(class), + CLASS_BODY +) +SWIZZLE_INFRASTRUCTURE_METHOD( + NSMethodSignatureRef, + swizzleMethodSignatureForSelector, + , + @selector(methodSignatureForSelector:), + METHOD_SIGNATURE_FOR_SELECTOR_BODY, + SEL +) +SWIZZLE_INFRASTRUCTURE_METHOD( + void, + swizzleDeallocating, + , + deallocSelector, + DEALLOCATING_BODY +) + +@end + +// MARK: Optimized intercepting methods for specific combination of parameter types + +@interface RXObjCRuntime (swizzle) + +@end + +@implementation RXObjCRuntime(swizzle) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, char) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, short) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, int) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, long) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_uchar) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_ushort) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_uint) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_ulong) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_block) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, float) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, double) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, SEL) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, id) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, char) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, short) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, int) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, long) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_uchar) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_ushort) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_uint) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_ulong) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_block) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, float) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, double) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, SEL) + ++(void)load { + SWIZZLE_OBSERVE_METHOD_BODY(void) + + SWIZZLE_OBSERVE_METHOD_BODY(void, id) + SWIZZLE_OBSERVE_METHOD_BODY(void, char) + SWIZZLE_OBSERVE_METHOD_BODY(void, short) + SWIZZLE_OBSERVE_METHOD_BODY(void, int) + SWIZZLE_OBSERVE_METHOD_BODY(void, long) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_uchar) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_ushort) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_uint) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_ulong) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_block) + SWIZZLE_OBSERVE_METHOD_BODY(void, float) + SWIZZLE_OBSERVE_METHOD_BODY(void, double) + SWIZZLE_OBSERVE_METHOD_BODY(void, SEL) + + SWIZZLE_OBSERVE_METHOD_BODY(void, id, id) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, char) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, short) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, int) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, long) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_uchar) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_ushort) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_uint) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_ulong) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_block) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, float) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, double) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, SEL) +} + +@end + +// MARK: RXObjCRuntime + +@implementation RXObjCRuntime + +static RXObjCRuntime *_instance = nil; +static NSMutableDictionary *optimizedObserversByMethodEncoding = nil; + ++(RXObjCRuntime*)instance { + return _instance; +} + ++(void)initialize { + _instance = [[RXObjCRuntime alloc] init]; + defaultTypeID = CFGetTypeID((CFTypeRef)RXObjCRuntime.class); // just need a reference of some object not from CF + deallocSelector = NSSelectorFromString(@"dealloc"); + NSAssert(_instance != nil, @"Failed to initialize swizzling"); +} + +-(instancetype)init { + self = [super init]; + if (!self) return nil; + + self.classesThatSupportObservingByForwarding = [NSMutableSet set]; + self.forwardedSelectorsByClass = [NSMutableDictionary dictionary]; + + self.dynamicSubclassByRealClass = [NSMutableDictionary dictionary]; + self.interceptorIMPbySelectorsByClass = [NSMutableDictionary dictionary]; + + pthread_mutexattr_t lock_attr; + pthread_mutexattr_init(&lock_attr); + pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&_lock, &lock_attr); + pthread_mutexattr_destroy(&lock_attr); + + return self; +} + +-(void)performLocked:(void (^)(RXObjCRuntime* __nonnull))action { + pthread_mutex_lock(&_lock); + action(self); + pthread_mutex_unlock(&_lock); +} + ++(void)registerOptimizedObserver:(RXInterceptWithOptimizedObserver)registration encodedAs:(SEL)selector { + Method exampleEncodingMethod = class_getClassMethod(self, selector); + ALWAYS(exampleEncodingMethod != nil, @"Example encoding method is nil."); + + NSString *methodEncoding = RX_method_encoding(exampleEncodingMethod); + + if (optimizedObserversByMethodEncoding == nil) { + optimizedObserversByMethodEncoding = [NSMutableDictionary dictionary]; + } + + DLOG(@"Added optimized method: %@ (%@)", methodEncoding, NSStringFromSelector(selector)); + ALWAYS(optimizedObserversByMethodEncoding[methodEncoding] == nil, @"Optimized observer already registered") + optimizedObserversByMethodEncoding[methodEncoding] = registration; +} + +/** + This is the main entry point for observing messages sent to arbitrary objects. + */ +-(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error { + Method instanceMethod = class_getInstanceMethod([target class], selector); + if (instanceMethod == nil) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSelectorNotImplemented + userInfo:nil], nil); + } + + if (selector == @selector(class) + || selector == @selector(forwardingTargetForSelector:) + || selector == @selector(methodSignatureForSelector:) + || selector == @selector(respondsToSelector:)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObservingPerformanceSensitiveMessages + userInfo:nil], nil); + } + + // For `dealloc` message, original implementation will be swizzled. + // This is a special case because observing `dealloc` message is performed when `observeWeakly` is used. + // + // Some toll free bridged classes don't handle `object_setClass` well and cause crashes. + // + // To make `deallocating` as robust as possible, original implementation will be replaced. + if (selector == deallocSelector) { + Class __nonnull deallocSwizzingTarget = [target class]; + IMP interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + + if (![self swizzleDeallocating:deallocSwizzingTarget error:error]) { + return nil; + } + + interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + } + else { + Class __nullable swizzlingImplementorClass = [self prepareTargetClassForObserving:target error:error]; + if (swizzlingImplementorClass == nil) { + return nil; + } + + NSString *methodEncoding = RX_method_encoding(instanceMethod); + RXInterceptWithOptimizedObserver optimizedIntercept = optimizedObserversByMethodEncoding[methodEncoding]; + + if (!RX_method_has_supported_return_type(instanceMethod)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObservingMessagesWithUnsupportedReturnType + userInfo:nil], nil); + } + + // optimized interception method + if (optimizedIntercept != nil) { + IMP interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:swizzlingImplementorClass]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + + if (!optimizedIntercept(self, swizzlingImplementorClass, selector, error)) { + return nil; + } + + interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:swizzlingImplementorClass]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + } + // default fallback to observing by forwarding messages + else { + if ([self forwardingSelector:selector forClass:swizzlingImplementorClass]) { + return RX_default_target_implementation(); + } + + if (![self observeByForwardingMessages:swizzlingImplementorClass + selector:selector + target:target + error:error]) { + return nil; + } + + if ([self forwardingSelector:selector forClass:swizzlingImplementorClass]) { + return RX_default_target_implementation(); + } + } + } + + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorUnknown + userInfo:nil], nil); +} + +-(Class __nullable)prepareTargetClassForObserving:(id __nonnull)target error:(NSErrorParam)error { + Class swizzlingClass = objc_getAssociatedObject(target, &RxSwizzlingTargetClassKey); + if (swizzlingClass != nil) { + return swizzlingClass; + } + + Class __nonnull wannaBeClass = [target class]; + /** + Core Foundation classes are usually toll free bridged. Those classes crash the program in case + `object_setClass` is performed on them. + + There is a possibility to just swizzle methods on original object, but since those won't be usual use + cases for this library, then an error will just be reported for now. + */ + BOOL isThisTollFreeFoundationClass = CFGetTypeID((CFTypeRef)target) != defaultTypeID; + + if (isThisTollFreeFoundationClass) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorCantInterceptCoreFoundationTollFreeBridgedObjects + userInfo:nil], nil); + } + + /** + If the object is reporting a different class then what it's real class, that means that there is probably + already some interception mechanism in place or something weird is happening. + + Most common case when this would happen is when using KVO (`observe`) and `sentMessage`. + + This error is easily resolved by just using `sentMessage` observing before `observe`. + + The reason why other way around could create issues is because KVO will unregister it's interceptor + class and restore original class. Unfortunately that will happen no matter was there another interceptor + subclass registered in hierarchy or not. + + Failure scenario: + * KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`) + * `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`) + * then unobserving with KVO will restore class to be `OriginalClass` -> failure point + + The reason why changing order of observing works is because any interception method should return + object's original real class (if that doesn't happen then it's really easy to argue that's a bug + in that other library). + + This library won't remove registered interceptor even if there aren't any observers left because + it's highly unlikely it would have any benefit in real world use cases, and it's even more + dangerous. + */ + if ([target class] != object_getClass(target)) { + BOOL isKVO = [target respondsToSelector:NSSelectorFromString(@"_isKVOA")]; + + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObjectMessagesAlreadyBeingIntercepted + userInfo:@{ + RXObjCRuntimeErrorIsKVOKey : @(isKVO) + }], nil); + } + + Class __nullable dynamicFakeSubclass = [self ensureHasDynamicFakeSubclass:wannaBeClass error:error]; + + if (dynamicFakeSubclass == nil) { + return nil; + } + + Class previousClass = object_setClass(target, dynamicFakeSubclass); + if (previousClass != wannaBeClass) { + THREADING_HAZARD(wannaBeClass); + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorThreadingCollisionWithOtherInterceptionMechanism + userInfo:nil], nil); + } + + objc_setAssociatedObject(target, &RxSwizzlingTargetClassKey, dynamicFakeSubclass, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return dynamicFakeSubclass; +} + + +-(BOOL)forwardingSelector:(SEL)selector forClass:(Class __nonnull)class { + return [self.forwardedSelectorsByClass[CLASS_VALUE(class)] containsObject:SEL_VALUE(selector)]; +} + +-(void)registerForwardedSelector:(SEL)selector forClass:(Class __nonnull)class { + NSValue *classValue = CLASS_VALUE(class); + + NSMutableSet *forwardedSelectors = self.forwardedSelectorsByClass[classValue]; + + if (forwardedSelectors == nil) { + forwardedSelectors = [NSMutableSet set]; + self.forwardedSelectorsByClass[classValue] = forwardedSelectors; + } + + [forwardedSelectors addObject:SEL_VALUE(selector)]; +} + +-(BOOL)observeByForwardingMessages:(Class __nonnull)swizzlingImplementorClass + selector:(SEL)selector + target:(id __nonnull)target + error:(NSErrorParam)error { + if (![self ensureForwardingMethodsAreSwizzled:swizzlingImplementorClass error:error]) { + return NO; + } + + ALWAYS(![self forwardingSelector:selector forClass:swizzlingImplementorClass], @"Already observing selector for class"); + +#if TRACE_RESOURCES + atomic_fetch_add(&numberOfForwardedMethods, 1); +#endif + SEL rxSelector = RX_selector(selector); + + Method instanceMethod = class_getInstanceMethod(swizzlingImplementorClass, selector); + ALWAYS(instanceMethod != nil, @"Instance method is nil"); + + const char* methodEncoding = method_getTypeEncoding(instanceMethod); + ALWAYS(methodEncoding != nil, @"Method encoding is nil."); + NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:methodEncoding]; + ALWAYS(methodSignature != nil, @"Method signature is invalid."); + + IMP implementation = method_getImplementation(instanceMethod); + + if (implementation == nil) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSelectorNotImplemented + userInfo:nil], NO); + } + + if (!class_addMethod(swizzlingImplementorClass, rxSelector, implementation, methodEncoding)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSavingOriginalForwardingMethodFailed + userInfo:nil], NO); + } + + if (!class_addMethod(swizzlingImplementorClass, selector, _objc_msgForward, methodEncoding)) { + if (implementation != method_setImplementation(instanceMethod, _objc_msgForward)) { + THREADING_HAZARD(swizzlingImplementorClass); + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorReplacingMethodWithForwardingImplementation + userInfo:nil], NO); + } + } + + DLOG(@"Rx uses forwarding to observe `%@` for `%@`.", NSStringFromSelector(selector), swizzlingImplementorClass); + [self registerForwardedSelector:selector forClass:swizzlingImplementorClass]; + + return YES; +} + +/** + If object don't have some weird behavior, claims it's the same class that runtime shows, + then dynamic subclass is created (only this instance will have performance hit). + + In case something weird is detected, then original base class is being swizzled and all instances + will have somewhat reduced performance. + + This is especially handy optimization for weak KVO. Nobody will swizzle for example `NSString`, + but to know when instance of a `NSString` was deallocated, performance hit will be only felt on a + single instance of `NSString`, not all instances of `NSString`s. + */ +-(Class __nullable)ensureHasDynamicFakeSubclass:(Class __nonnull)class error:(NSErrorParam)error { + Class dynamicFakeSubclass = self.dynamicSubclassByRealClass[CLASS_VALUE(class)]; + if (dynamicFakeSubclass != nil) { + return dynamicFakeSubclass; + } + + NSString *dynamicFakeSubclassName = [RX_PREFIX stringByAppendingString:NSStringFromClass(class)]; + const char *dynamicFakeSubclassNameRaw = dynamicFakeSubclassName.UTF8String; + dynamicFakeSubclass = objc_allocateClassPair(class, dynamicFakeSubclassNameRaw, 0); + ALWAYS(dynamicFakeSubclass != nil, @"Class not generated"); + + if (![self swizzleClass:dynamicFakeSubclass toActAs:class error:error]) { + return nil; + } + + objc_registerClassPair(dynamicFakeSubclass); + + [self.dynamicSubclassByRealClass setObject:dynamicFakeSubclass forKey:CLASS_VALUE(class)]; + ALWAYS(self.dynamicSubclassByRealClass[CLASS_VALUE(class)] != nil, @"Class not registered"); + + return dynamicFakeSubclass; +} + +-(BOOL)ensureForwardingMethodsAreSwizzled:(Class __nonnull)class error:(NSErrorParam)error { + NSValue *classValue = CLASS_VALUE(class); + if ([self.classesThatSupportObservingByForwarding containsObject:classValue]) { + return YES; + } + + if (![self swizzleForwardInvocation:class error:error]) { return NO; } + if (![self swizzleMethodSignatureForSelector:class error:error]) { return NO; } + if (![self swizzleRespondsToSelector:class error:error]) { return NO; } + + [self.classesThatSupportObservingByForwarding addObject:classValue]; + + return YES; +} + +-(void)registerInterceptedSelector:(SEL)selector implementation:(IMP)implementation forClass:(Class)class { + NSValue * __nonnull classValue = CLASS_VALUE(class); + NSValue * __nonnull selectorValue = SEL_VALUE(selector); + + NSMutableDictionary *swizzledIMPBySelectorsForClass = self.interceptorIMPbySelectorsByClass[classValue]; + + if (swizzledIMPBySelectorsForClass == nil) { + swizzledIMPBySelectorsForClass = [NSMutableDictionary dictionary]; + self.interceptorIMPbySelectorsByClass[classValue] = swizzledIMPBySelectorsForClass; + } + + swizzledIMPBySelectorsForClass[selectorValue] = IMP_VALUE(implementation); + + ALWAYS([self interceptorImplementationForSelector:selector forClass:class] != nil, @"Class should have been swizzled"); +} + +-(IMP)interceptorImplementationForSelector:(SEL)selector forClass:(Class)class { + NSValue * __nonnull classValue = CLASS_VALUE(class); + NSValue * __nonnull selectorValue = SEL_VALUE(selector); + + NSMutableDictionary *swizzledIMPBySelectorForClass = self.interceptorIMPbySelectorsByClass[classValue]; + + NSValue *impValue = swizzledIMPBySelectorForClass[selectorValue]; + return impValue.pointerValue; +} + +-(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector + ofClass:(Class __nonnull)class + newImplementationGenerator:(IMP(^)(void))newImplementationGenerator +replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator + error:(NSErrorParam)error { + if ([self interceptorImplementationForSelector:selector forClass:class] != nil) { + DLOG(@"Trying to register same intercept at least once, this sounds like a possible bug"); + return YES; + } + +#if TRACE_RESOURCES + atomic_fetch_add(&numberOInterceptedMethods, 1); +#endif + + DLOG(@"Rx is swizzling `%@` for `%@`", NSStringFromSelector(selector), class); + + Method existingMethod = class_getInstanceMethod(class, selector); + ALWAYS(existingMethod != nil, @"Method doesn't exist"); + + const char *encoding = method_getTypeEncoding(existingMethod); + ALWAYS(encoding != nil, @"Encoding is nil"); + + IMP newImplementation = newImplementationGenerator(); + + if (class_addMethod(class, selector, newImplementation, encoding)) { + // new method added, job done + [self registerInterceptedSelector:selector implementation:newImplementation forClass:class]; + + return YES; + } + + imp_removeBlock(newImplementation); + + // if add fails, that means that method already exists on targetClass + Method existingMethodOnTargetClass = existingMethod; + + IMP originalImplementation = method_getImplementation(existingMethodOnTargetClass); + ALWAYS(originalImplementation != nil, @"Method must exist."); + IMP implementationReplacementIMP = replacementImplementationGenerator(originalImplementation); + ALWAYS(implementationReplacementIMP != nil, @"Method must exist."); + IMP originalImplementationAfterChange = method_setImplementation(existingMethodOnTargetClass, implementationReplacementIMP); + ALWAYS(originalImplementation != nil, @"Method must exist."); + + // If method replacing failed, who knows what happened, better not trying again, otherwise program can get + // corrupted. + [self registerInterceptedSelector:selector implementation:implementationReplacementIMP forClass:class]; + + // ¯\_(ツ)_/¯ + if (originalImplementationAfterChange != originalImplementation) { + THREADING_HAZARD(class); + return NO; + } + + return YES; +} + +@end + +#if TRACE_RESOURCES + +NSInteger RX_number_of_dynamic_subclasses(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.dynamicSubclassByRealClass.count; + }]; + + return count; +} + +NSInteger RX_number_of_forwarding_enabled_classes(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.classesThatSupportObservingByForwarding.count; + }]; + + return count; +} + +NSInteger RX_number_of_intercepting_classes(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.interceptorIMPbySelectorsByClass.count; + }]; + + return count; +} + +NSInteger RX_number_of_forwarded_methods(void) { + return numberOfForwardedMethods; +} + +NSInteger RX_number_of_swizzled_methods(void) { + return numberOInterceptedMethods; +} + +#endif + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h new file mode 100644 index 00000000..8cf762ec --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h @@ -0,0 +1,19 @@ +// +// RxCocoaRuntime.h +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import "_RX.h" +#import "_RXDelegateProxy.h" +#import "_RXKVOObserver.h" +#import "_RXObjCRuntime.h" + +//! Project version number for RxCocoa. +FOUNDATION_EXPORT double RxCocoaVersionNumber; + +//! Project version string for RxCocoa. +FOUNDATION_EXPORT const unsigned char RxCocoaVersionString[]; diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h new file mode 100644 index 00000000..b868ac97 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h @@ -0,0 +1,93 @@ +// +// _RX.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +#if TRACE_RESOURCES >= 2 +# define DLOG(...) NSLog(__VA_ARGS__) +#else +# define DLOG(...) +#endif + +#if DEBUG +# define ABORT_IN_DEBUG abort(); +#else +# define ABORT_IN_DEBUG +#endif + + +#define SEL_VALUE(x) [NSValue valueWithPointer:(x)] +#define CLASS_VALUE(x) [NSValue valueWithNonretainedObject:(x)] +#define IMP_VALUE(x) [NSValue valueWithPointer:(x)] + +/** + Checks that the local `error` instance exists before assigning it's value by reference. + This macro exists to work around static analysis warnings — `NSError` is always assumed to be `nullable`, even though we explicitly define the method parameter as `nonnull`. See http://www.openradar.me/21766176 for more details. + */ +#define RX_THROW_ERROR(errorValue, returnValue) if (error != nil) { *error = (errorValue); } return (returnValue); + +#define RX_CAT2(_1, _2) _RX_CAT2(_1, _2) +#define _RX_CAT2(_1, _2) _1 ## _2 + +#define RX_ELEMENT_AT(n, ...) RX_CAT2(_RX_ELEMENT_AT_, n)(__VA_ARGS__) +#define _RX_ELEMENT_AT_0(x, ...) x +#define _RX_ELEMENT_AT_1(_0, x, ...) x +#define _RX_ELEMENT_AT_2(_0, _1, x, ...) x +#define _RX_ELEMENT_AT_3(_0, _1, _2, x, ...) x +#define _RX_ELEMENT_AT_4(_0, _1, _2, _3, x, ...) x +#define _RX_ELEMENT_AT_5(_0, _1, _2, _3, _4, x, ...) x +#define _RX_ELEMENT_AT_6(_0, _1, _2, _3, _4, _5, x, ...) x + +#define RX_COUNT(...) RX_ELEMENT_AT(6, ## __VA_ARGS__, 6, 5, 4, 3, 2, 1, 0) +#define RX_EMPTY(...) RX_ELEMENT_AT(6, ## __VA_ARGS__, 0, 0, 0, 0, 0, 0, 1) + +/** + #define SUM(context, index, head, tail) head + tail + #define MAP(context, index, element) (context)[index] * (element) + + RX_FOR(numbers, SUM, MAP, b0, b1, b2); + + (numbers)[0] * (b0) + (numbers)[1] * (b1) + (numbers[2]) * (b2) + */ + +#define RX_FOREACH(context, concat, map, ...) RX_FOR_MAX(RX_COUNT(__VA_ARGS__), _RX_FOREACH_CONCAT, _RX_FOREACH_MAP, context, concat, map, __VA_ARGS__) +#define _RX_FOREACH_CONCAT(index, head, tail, context, concat, map, ...) concat(context, index, head, tail) +#define _RX_FOREACH_MAP(index, context, concat, map, ...) map(context, index, RX_ELEMENT_AT(index, __VA_ARGS__)) + +/** + #define MAP(context, index, item) (context)[index] * (item) + + RX_FOR_COMMA(numbers, MAP, b0, b1); + + ,(numbers)[0] * b0, (numbers)[1] * b1 + */ +#define RX_FOREACH_COMMA(context, map, ...) RX_CAT2(_RX_FOREACH_COMMA_EMPTY_, RX_EMPTY(__VA_ARGS__))(context, map, ## __VA_ARGS__) +#define _RX_FOREACH_COMMA_EMPTY_1(context, map, ...) +#define _RX_FOREACH_COMMA_EMPTY_0(context, map, ...) , RX_FOR_MAX(RX_COUNT(__VA_ARGS__), _RX_FOREACH_COMMA_CONCAT, _RX_FOREACH_COMMA_MAP, context, map, __VA_ARGS__) +#define _RX_FOREACH_COMMA_CONCAT(index, head, tail, context, map, ...) head, tail +#define _RX_FOREACH_COMMA_MAP(index, context, map, ...) map(context, index, RX_ELEMENT_AT(index, __VA_ARGS__)) + +// rx for + +#define RX_FOR_MAX(max, concat, map, ...) RX_CAT2(RX_FOR_, max)(concat, map, ## __VA_ARGS__) + +#define RX_FOR_0(concat, map, ...) +#define RX_FOR_1(concat, map, ...) map(0, __VA_ARGS__) +#define RX_FOR_2(concat, map, ...) concat(1, RX_FOR_1(concat, map, ## __VA_ARGS__), map(1, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_3(concat, map, ...) concat(2, RX_FOR_2(concat, map, ## __VA_ARGS__), map(2, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_4(concat, map, ...) concat(3, RX_FOR_3(concat, map, ## __VA_ARGS__), map(3, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_5(concat, map, ...) concat(4, RX_FOR_4(concat, map, ## __VA_ARGS__), map(4, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_6(concat, map, ...) concat(5, RX_FOR_5(concat, map, ## __VA_ARGS__), map(5, __VA_ARGS__), __VA_ARGS__) + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h new file mode 100644 index 00000000..e1cc207d --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h @@ -0,0 +1,27 @@ +// +// _RXDelegateProxy.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface _RXDelegateProxy : NSObject + +@property (nonatomic, weak, readonly) id _forwardToDelegate; + +-(void)_setForwardToDelegate:(id __nullable)forwardToDelegate retainDelegate:(BOOL)retainDelegate NS_SWIFT_NAME(_setForwardToDelegate(_:retainDelegate:)) ; + +-(BOOL)hasWiredImplementationForSelector:(SEL)selector; +-(BOOL)voidDelegateMethodsContain:(SEL)selector; + +-(void)_sentMessage:(SEL)selector withArguments:(NSArray*)arguments; +-(void)_methodInvoked:(SEL)selector withArguments:(NSArray*)arguments; + +@end + +NS_ASSUME_NONNULL_END diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h new file mode 100644 index 00000000..adcfd0a3 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h @@ -0,0 +1,28 @@ +// +// _RXKVOObserver.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +// Exists because if written in Swift, reading unowned is disabled during dealloc process +@interface _RXKVOObserver : NSObject + +-(instancetype)initWithTarget:(id)target + retainTarget:(BOOL)retainTarget + keyPath:(NSString*)keyPath + options:(NSKeyValueObservingOptions)options + callback:(void (^)(id))callback; + +-(void)dispose; + +@end diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h new file mode 100644 index 00000000..bc6a76af --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h @@ -0,0 +1,102 @@ +// +// _RXObjCRuntime.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +#if !DISABLE_SWIZZLING + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +/** + This flag controls `RELEASE` configuration behavior in case race was detecting while modifying + ObjC runtime. + + In case this value is set to `YES`, after runtime race is detected, `abort()` will be called. + Otherwise, only error will be reported using normal error reporting mechanism. + + In `DEBUG` mode `abort` will be always called in case race is detected. + + Races can't happen in case this is the only library modifying ObjC runtime, but in case there are multiple libraries + changing ObjC runtime, race conditions can occur because there is no way to synchronize multiple libraries unaware of + each other. + + To help remedy this situation this library will use `synchronized` on target object and it's meta-class, but + there aren't any guarantees of how other libraries will behave. + + Default value is `NO`. + + */ +extern BOOL RXAbortOnThreadingHazard; + +/// Error domain for RXObjCRuntime. +extern NSString * __nonnull const RXObjCRuntimeErrorDomain; + +/// `userInfo` key with additional information is interceptor probably KVO. +extern NSString * __nonnull const RXObjCRuntimeErrorIsKVOKey; + +typedef NS_ENUM(NSInteger, RXObjCRuntimeError) { + RXObjCRuntimeErrorUnknown = 1, + RXObjCRuntimeErrorObjectMessagesAlreadyBeingIntercepted = 2, + RXObjCRuntimeErrorSelectorNotImplemented = 3, + RXObjCRuntimeErrorCantInterceptCoreFoundationTollFreeBridgedObjects = 4, + RXObjCRuntimeErrorThreadingCollisionWithOtherInterceptionMechanism = 5, + RXObjCRuntimeErrorSavingOriginalForwardingMethodFailed = 6, + RXObjCRuntimeErrorReplacingMethodWithForwardingImplementation = 7, + RXObjCRuntimeErrorObservingPerformanceSensitiveMessages = 8, + RXObjCRuntimeErrorObservingMessagesWithUnsupportedReturnType = 9, +}; + +/// Transforms normal selector into a selector with RX prefix. +SEL _Nonnull RX_selector(SEL _Nonnull selector); + +/// Transforms selector into a unique pointer (because of Swift conversion rules) +void * __nonnull RX_reference_from_selector(SEL __nonnull selector); + +/// Protocol that interception observers must implement. +@protocol RXMessageSentObserver + +/// In case the same selector is being intercepted for a pair of base/sub classes, +/// this property will differentiate between interceptors that need to fire. +@property (nonatomic, assign, readonly) IMP __nonnull targetImplementation; + +-(void)messageSentWithArguments:(NSArray* __nonnull)arguments; +-(void)methodInvokedWithArguments:(NSArray* __nonnull)arguments; + +@end + +/// Protocol that deallocating observer must implement. +@protocol RXDeallocatingObserver + +/// In case the same selector is being intercepted for a pair of base/sub classes, +/// this property will differentiate between interceptors that need to fire. +@property (nonatomic, assign, readonly) IMP __nonnull targetImplementation; + +-(void)deallocating; + +@end + +/// Ensures interceptor is installed on target object. +IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSError *__autoreleasing __nullable * __nullable error); + +#endif + +/// Extracts arguments for `invocation`. +NSArray * __nonnull RX_extract_arguments(NSInvocation * __nonnull invocation); + +/// Returns `YES` in case method has `void` return type. +BOOL RX_is_method_with_description_void(struct objc_method_description method); + +/// Returns `YES` in case methodSignature has `void` return type. +BOOL RX_is_method_signature_void(NSMethodSignature * __nonnull methodSignature); + +/// Default value for `RXInterceptionObserver.targetImplementation`. +IMP __nonnull RX_default_target_implementation(void); diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/RxCocoa.h b/ChatBot/Pods/RxCocoa/RxCocoa/RxCocoa.h new file mode 100644 index 00000000..0bca1bc7 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/RxCocoa.h @@ -0,0 +1,19 @@ +// +// RxCocoa.h +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import +#import +#import +#import + +//! Project version number for RxCocoa. +FOUNDATION_EXPORT double RxCocoaVersionNumber; + +//! Project version string for RxCocoa. +FOUNDATION_EXPORT const unsigned char RxCocoaVersionString[]; diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/RxCocoa.swift b/ChatBot/Pods/RxCocoa/RxCocoa/RxCocoa.swift new file mode 100644 index 00000000..5e569fc2 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/RxCocoa.swift @@ -0,0 +1,155 @@ +// +// RxCocoa.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// Importing RxCocoa also imports RxRelay +@_exported import RxRelay + +import RxSwift +#if os(iOS) + import UIKit +#endif + +/// RxCocoa errors. +public enum RxCocoaError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error has occurred. + case unknown + /// Invalid operation was attempted. + case invalidOperation(object: Any) + /// Items are not yet bound to user interface but have been requested. + case itemsNotYetBound(object: Any) + /// Invalid KVO Path. + case invalidPropertyName(object: Any, propertyName: String) + /// Invalid object on key path. + case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String) + /// Error during swizzling. + case errorDuringSwizzling + /// Casting error. + case castingError(object: Any, targetType: Any.Type) +} + + +// MARK: Debug descriptions + +extension RxCocoaError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case let .invalidOperation(object): + return "Invalid operation was attempted on `\(object)`." + case let .itemsNotYetBound(object): + return "Data source is set, but items are not yet bound to user interface for `\(object)`." + case let .invalidPropertyName(object, propertyName): + return "Object `\(object)` doesn't have a property named `\(propertyName)`." + case let .invalidObjectOnKeyPath(object, sourceObject, propertyName): + return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`." + case .errorDuringSwizzling: + return "Error during swizzling." + case let .castingError(object, targetType): + return "Error casting `\(object)` to `\(targetType)`" + } + } +} + + + +// MARK: Error binding policies + +func bindingError(_ error: Swift.Error) { + let error = "Binding error: \(error)" +#if DEBUG + rxFatalError(error) +#else + print(error) +#endif +} + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(message: String = "Abstract method", file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError(message, file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +// MARK: casts or fatal error + +// workaround for Swift compiler bug, cheers compiler team :) +func castOptionalOrFatalError(_ value: Any?) -> T? { + if value == nil { + return nil + } + let v: T = castOrFatalError(value) + return v +} + +func castOrThrow(_ resultType: T.Type, _ object: Any) throws -> T { + guard let returnValue = object as? T else { + throw RxCocoaError.castingError(object: object, targetType: resultType) + } + + return returnValue +} + +func castOptionalOrThrow(_ resultType: T.Type, _ object: AnyObject) throws -> T? { + if NSNull().isEqual(object) { + return nil + } + + guard let returnValue = object as? T else { + throw RxCocoaError.castingError(object: object, targetType: resultType) + } + + return returnValue +} + +func castOrFatalError(_ value: AnyObject!, message: String) -> T { + let maybeResult: T? = value as? T + guard let result = maybeResult else { + rxFatalError(message) + } + + return result +} + +func castOrFatalError(_ value: Any!) -> T { + let maybeResult: T? = value as? T + guard let result = maybeResult else { + rxFatalError("Failure converting from \(String(describing: value)) to \(T.self)") + } + + return result +} + +// MARK: Error messages + +let dataSourceNotSet = "DataSource not set" +let delegateNotSet = "Delegate not set" + +// MARK: Shared with RxSwift + +func rxFatalError(_ lastMessage: String) -> Never { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage) +} + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift new file mode 100644 index 00000000..bea1d83d --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift @@ -0,0 +1,68 @@ +// +// ControlEvent.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// A protocol that extends `ControlEvent`. +public protocol ControlEventType : ObservableType { + + /// - returns: `ControlEvent` interface + func asControlEvent() -> ControlEvent +} + +/** + A trait for `Observable`/`ObservableType` that represents an event on a UI element. + + Properties: + + - it doesn’t send any initial value on subscription, + - it `Complete`s the sequence when the control deallocates, + - it never errors out + - it delivers events on `MainScheduler.instance`. + + **The implementation of `ControlEvent` will ensure that sequence of events is being subscribed on main scheduler + (`subscribe(on: ConcurrentMainScheduler.instance)` behavior).** + + **It is the implementor’s responsibility to make sure that all other properties enumerated above are satisfied.** + + **If they aren’t, using this trait will communicate wrong properties, and could potentially break someone’s code.** + + **If the `events` observable sequence passed into the initializer doesn’t satisfy all enumerated + properties, don’t use this trait.** +*/ +public struct ControlEvent : ControlEventType { + public typealias Element = PropertyType + + let events: Observable + + /// Initializes control event with a observable sequence that represents events. + /// + /// - parameter events: Observable sequence that represents events. + /// - returns: Control event created with a observable sequence of events. + public init(events: Ev) where Ev.Element == Element { + self.events = events.subscribe(on: ConcurrentMainScheduler.instance) + } + + /// Subscribes an observer to control events. + /// + /// - parameter observer: Observer to subscribe to events. + /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control events. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.events.subscribe(observer) + } + + /// - returns: `Observable` interface. + public func asObservable() -> Observable { + self.events + } + + /// - returns: `ControlEvent` interface. + public func asControlEvent() -> ControlEvent { + self + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift new file mode 100644 index 00000000..5ff48ca4 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift @@ -0,0 +1,118 @@ +// +// ControlProperty.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// Protocol that enables extension of `ControlProperty`. +public protocol ControlPropertyType : ObservableType, ObserverType { + + /// - returns: `ControlProperty` interface + func asControlProperty() -> ControlProperty +} + +/** + Trait for `Observable`/`ObservableType` that represents property of UI element. + + Sequence of values only represents initial control value and user initiated value changes. + Programmatic value changes won't be reported. + + It's properties are: + + - `shareReplay(1)` behavior + - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced + - it will `Complete` sequence on control being deallocated + - it never errors out + - it delivers events on `MainScheduler.instance` + + **The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler + (`subscribe(on: ConcurrentMainScheduler.instance)` behavior).** + + **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** + + **If they aren't, then using this trait communicates wrong properties and could potentially break someone's code.** + + **In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated + properties, please don't use this trait.** +*/ +public struct ControlProperty : ControlPropertyType { + public typealias Element = PropertyType + + let values: Observable + let valueSink: AnyObserver + + /// Initializes control property with a observable sequence that represents property values and observer that enables + /// binding values to property. + /// + /// - parameter values: Observable sequence that represents property values. + /// - parameter valueSink: Observer that enables binding values to control property. + /// - returns: Control property created with a observable sequence of values and an observer that enables binding values + /// to property. + public init(values: Values, valueSink: Sink) where Element == Values.Element, Element == Sink.Element { + self.values = values.subscribe(on: ConcurrentMainScheduler.instance) + self.valueSink = valueSink.asObserver() + } + + /// Subscribes an observer to control property values. + /// + /// - parameter observer: Observer to subscribe to property values. + /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.values.subscribe(observer) + } + + /// `ControlEvent` of user initiated value changes. Every time user updates control value change event + /// will be emitted from `changed` event. + /// + /// Programmatic changes to control value won't be reported. + /// + /// It contains all control property values except for first one. + /// + /// The name only implies that sequence element will be generated once user changes a value and not that + /// adjacent sequence values need to be different (e.g. because of interaction between programmatic and user updates, + /// or for any other reason). + public var changed: ControlEvent { + ControlEvent(events: self.values.skip(1)) + } + + /// - returns: `Observable` interface. + public func asObservable() -> Observable { + self.values + } + + /// - returns: `ControlProperty` interface. + public func asControlProperty() -> ControlProperty { + self + } + + /// Binds event to user interface. + /// + /// - In case next element is received, it is being set to control value. + /// - In case error is received, DEBUG builds raise fatal error, RELEASE builds log event to standard output. + /// - In case sequence completes, nothing happens. + public func on(_ event: Event) { + switch event { + case .error(let error): + bindingError(error) + case .next: + self.valueSink.on(event) + case .completed: + self.valueSink.on(event) + } + } +} + +extension ControlPropertyType where Element == String? { + /// Transforms control property of type `String?` into control property of type `String`. + public var orEmpty: ControlProperty { + let original: ControlProperty = self.asControlProperty() + + let values: Observable = original.values.map { $0 ?? "" } + let valueSink: AnyObserver = original.valueSink.mapObserver { $0 } + return ControlProperty(values: values, valueSink: valueSink) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift new file mode 100644 index 00000000..76d960f0 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift @@ -0,0 +1,21 @@ +// +// BehaviorRelay+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/7/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension BehaviorRelay { + /// Converts `BehaviorRelay` to `Driver`. + /// + /// - returns: Observable sequence. + public func asDriver() -> Driver { + let source = self.asObservable() + .observe(on:DriverSharingStrategy.scheduler) + return SharedSequence(source) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift new file mode 100644 index 00000000..b59c7533 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift @@ -0,0 +1,24 @@ +// +// ControlEvent+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlEvent { + /// Converts `ControlEvent` to `Driver` trait. + /// + /// `ControlEvent` already can't fail, so no special case needs to be handled. + public func asDriver() -> Driver { + return self.asDriver { _ -> Driver in + #if DEBUG + rxFatalError("Somehow driver received error from a source that shouldn't fail.") + #else + return Driver.empty() + #endif + } + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift new file mode 100644 index 00000000..79045297 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift @@ -0,0 +1,24 @@ +// +// ControlProperty+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlProperty { + /// Converts `ControlProperty` to `Driver` trait. + /// + /// `ControlProperty` already can't fail, so no special case needs to be handled. + public func asDriver() -> Driver { + return self.asDriver { _ -> Driver in + #if DEBUG + rxFatalError("Somehow driver received error from a source that shouldn't fail.") + #else + return Driver.empty() + #endif + } + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift new file mode 100644 index 00000000..0b9024c7 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift @@ -0,0 +1,203 @@ +// +// Driver+Subscription.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +private let errorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" + +"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n" + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + /** + Creates new subscription and sends elements to observer. + This method can be only called from `MainThread`. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func drive(_ observers: Observer...) -> Disposable where Observer.Element == Element { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asSharedSequence() + .asObservable() + .subscribe { e in + observers.forEach { $0.on(e) } + } + } + + /** + Creates new subscription and sends elements to observer. + This method can be only called from `MainThread`. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func drive(_ observers: Observer...) -> Disposable where Observer.Element == Element? { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asSharedSequence() + .asObservable() + .map { $0 as Element? } + .subscribe { e in + observers.forEach { $0.on(e) } + } + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: BehaviorRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: BehaviorRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: ReplayRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: ReplayRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Subscribes to observable sequence using custom binder function. + This method can be only called from `MainThread`. + + - parameter transformation: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func drive(_ transformation: (Observable) -> Result) -> Result { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return transformation(self.asObservable()) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func drive(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return with(self)(curriedArgument) + } + + This method can be only called from `MainThread`. + + - parameter with: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func drive(_ with: (Observable) -> (R1) -> R2, curriedArgument: R1) -> R2 { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return with(self.asObservable())(curriedArgument) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + This method can be only called from `MainThread`. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + Error callback is not exposed because `Driver` can't error out. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asObservable().subscribe(with: object, onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + This method can be only called from `MainThread`. + + Error callback is not exposed because `Driver` can't error out. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive( + onNext: ((Element) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes to this `Driver` with a no-op. + This method can be only called from `MainThread`. + + - note: This is an alias of `drive(onNext: nil, onCompleted: nil, onDisposed: nil)` used to fix an ambiguity bug in Swift: https://bugs.swift.org/browse/SR-13657 + + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive() -> Disposable { + drive(onNext: nil, onCompleted: nil, onDisposed: nil) + } +} + + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift new file mode 100644 index 00000000..5de8b3a5 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift @@ -0,0 +1,53 @@ +// +// Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/26/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence with following properties: + + - it never fails + - it delivers events on `MainScheduler.instance` + - `share(replay: 1, scope: .whileConnected)` sharing strategy + + Additional explanation: + - all observers share sequence computation resources + - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced + - computation of elements is reference counted with respect to the number of observers + - if there are no subscribers, it will release sequence computation resources + + In case trait that models event bus is required, please check `Signal`. + + `Driver` can be considered a builder pattern for observable sequences that drive the application. + + If observable sequence has produced at least one element, after new subscription is made last produced element will be + immediately replayed on the same thread on which the subscription was made. + + When using `drive*`, `subscribe*` and `bind*` family of methods, they should always be called from main thread. + + If `drive*`, `subscribe*` and `bind*` are called from background thread, it is possible that initial replay + will happen on background thread, and subsequent events will arrive on main thread. + + To find out more about traits and how to use them, please visit `Documentation/Traits.md`. + */ +public typealias Driver = SharedSequence + +public struct DriverSharingStrategy: SharingStrategyProtocol { + public static var scheduler: SchedulerType { SharingScheduler.make() } + public static func share(_ source: Observable) -> Observable { + source.share(replay: 1, scope: .whileConnected) + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + /// Adds `asDriver` to `SharingSequence` with `DriverSharingStrategy`. + public func asDriver() -> Driver { + self.asSharedSequence() + } +} + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift new file mode 100644 index 00000000..bcac66b6 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Driver trait. + */ + public func asDriver(onErrorJustReturn: Element) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catchAndReturn(onErrorJustReturn) + return Driver(source) + } + + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorDriveWith: Driver that continues to drive the sequence in case of error. + - returns: Driver trait. + */ + public func asDriver(onErrorDriveWith: Driver) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catch { _ in + onErrorDriveWith.asObservable() + } + return Driver(source) + } + + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorRecover: Calculates driver that continues to drive the sequence in case of error. + - returns: Driver trait. + */ + public func asDriver(onErrorRecover: @escaping (_ error: Swift.Error) -> Driver) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return Driver(source) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift new file mode 100644 index 00000000..20ddf868 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/1/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorJustReturn: Element) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catchAndReturn(onErrorJustReturn) + return SharedSequence(source) + } + + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorDriveWith: SharedSequence that provides elements of the sequence in case of error. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorDriveWith: SharedSequence) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catch { _ in + onErrorDriveWith.asObservable() + } + return SharedSequence(source) + } + + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorRecover: Calculates driver that continues to drive the sequence in case of error. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorRecover: @escaping (_ error: Swift.Error) -> SharedSequence) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return SharedSequence(source) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift new file mode 100644 index 00000000..5111e06d --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift @@ -0,0 +1,62 @@ +// +// SchedulerType+SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/27/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +public enum SharingScheduler { + /// Default scheduler used in SharedSequence based traits. + public private(set) static var make: () -> SchedulerType = { MainScheduler() } + + /** + This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead + of main schedulers. + + **This shouldn't be used in normal release builds.** + */ + static public func mock(scheduler: SchedulerType, action: () throws -> Void) rethrows { + return try mock(makeScheduler: { scheduler }, action: action) + } + + /** + This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead + of main schedulers. + + **This shouldn't be used in normal release builds.** + */ + static public func mock(makeScheduler: @escaping () -> SchedulerType, action: () throws -> Void) rethrows { + let originalMake = make + make = makeScheduler + defer { + make = originalMake + } + + try action() + + // If you remove this line , compiler buggy optimizations will change behavior of this code + _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(makeScheduler) + // Scary, I know + } +} + +#if os(Linux) + import Glibc +#else + import Foundation +#endif + +func _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(_ scheduler: () -> SchedulerType) { + let a: Int32 = 1 +#if os(Linux) + let b = 314 + Int32(Glibc.random() & 1) +#else + let b = 314 + Int32(arc4random() & 1) +#endif + if a == b { + print(scheduler()) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift new file mode 100644 index 00000000..c36b575f --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Concurrency.swift @@ -0,0 +1,42 @@ +// +// SharedSequence+Concurrency.swift +// RxCocoa +// +// Created by Shai Mishali on 22/09/2021. +// Copyright © 2021 Krunoslav Zaher. All rights reserved. +// + +#if swift(>=5.5.2) && canImport(_Concurrency) && !os(Linux) +import Foundation + +// MARK: - Shared Sequence +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension SharedSequence { + /// Allows iterating over the values of this Shared Sequence + /// asynchronously via Swift's concurrency features (`async/await`) + /// + /// A sample usage would look like so: + /// + /// ```swift + /// for await value in driver.values { + /// // Handle emitted values + /// } + /// ``` + @MainActor var values: AsyncStream { + AsyncStream { continuation in + // It is safe to ignore the `onError` closure here since + // Shared Sequences (`Driver` and `Signal`) cannot fail + let disposable = self.asObservable() + .subscribe( + onNext: { value in continuation.yield(value) }, + onCompleted: { continuation.finish() }, + onDisposed: { continuation.onTermination?(.cancelled) } + ) + + continuation.onTermination = { @Sendable _ in + disposable.dispose() + } + } + } +} +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift new file mode 100644 index 00000000..4cc967cf --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift @@ -0,0 +1,656 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// SharedSequence+Operators+arity.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + + + +// 2 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 3 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 4 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 5 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 6 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 7 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 8 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift new file mode 100644 index 00000000..1d53b03d --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift @@ -0,0 +1,584 @@ +// +// SharedSequence+Operators.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +// MARK: map +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence into a new form. + + - parameter selector: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + public func map(_ selector: @escaping (Element) -> Result) -> SharedSequence { + let source = self + .asObservable() + .map(selector) + return SharedSequence(source) + } +} + +// MARK: compactMap +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence into an optional form and filters all optional results. + + - parameter selector: A transform function to apply to each source element and which returns an element or nil. + - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. + + */ + public func compactMap(_ selector: @escaping (Element) -> Result?) -> SharedSequence { + let source = self + .asObservable() + .compactMap(selector) + return SharedSequence(source) + } +} + +// MARK: filter +extension SharedSequenceConvertibleType { + /** + Filters the elements of an observable sequence based on a predicate. + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (Element) -> Bool) -> SharedSequence { + let source = self + .asObservable() + .filter(predicate) + return SharedSequence(source) + } +} + +// MARK: switchLatest +extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> SharedSequence { + let source: Observable = self + .asObservable() + .map { $0.asSharedSequence() } + .switchLatest() + return SharedSequence(source) + } +} + +// MARK: flatMapLatest +extension SharedSequenceConvertibleType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) -> SharedSequence) + -> SharedSequence { + let source: Observable = self + .asObservable() + .flatMapLatest(selector) + return SharedSequence(source) + } +} + +// MARK: flatMapFirst +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (Element) -> SharedSequence) + -> SharedSequence { + let source: Observable = self + .asObservable() + .flatMapFirst(selector) + return SharedSequence(source) + } +} + +// MARK: do +extension SharedSequenceConvertibleType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((Element) -> Void)? = nil, afterNext: ((Element) -> Void)? = nil, onCompleted: (() -> Void)? = nil, afterCompleted: (() -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> SharedSequence { + let source = self.asObservable() + .do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + + return SharedSequence(source) + } +} + +// MARK: debug +extension SharedSequenceConvertibleType { + + /** + Prints received events for all observers on standard output. + + - parameter identifier: Identifier that is printed together with event description to standard output. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) -> SharedSequence { + let source = self.asObservable() + .debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function) + return SharedSequence(source) + } +} + +// MARK: distinctUntilChanged +extension SharedSequenceConvertibleType where Element: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) -> Key) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + return SharedSequence(source) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (Element, Element) -> Bool) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged({ $0 }, comparer: comparer) + return SharedSequence(source) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) -> K, comparer: @escaping (K, K) -> Bool) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged(keySelector, comparer: comparer) + return SharedSequence(source) + } +} + + +// MARK: flatMap +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (Element) -> SharedSequence) -> SharedSequence { + let source = self.asObservable() + .flatMap(selector) + + return SharedSequence(source) + } +} + +// MARK: merge +extension SharedSequenceConvertibleType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [SharedSequence]) -> SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: SharedSequence...) -> SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + +} + +// MARK: merge +extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType { + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> SharedSequence { + let source = self.asObservable() + .map { $0.asSharedSequence() } + .merge() + return SharedSequence(source) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> SharedSequence { + let source = self.asObservable() + .map { $0.asSharedSequence() } + .merge(maxConcurrent: maxConcurrent) + return SharedSequence(source) + } +} + +// MARK: throttle +extension SharedSequenceConvertibleType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true) + -> SharedSequence { + let source = self.asObservable() + .throttle(dueTime, latest: latest, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - parameter dueTime: Throttling duration for each element. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval) + -> SharedSequence { + let source = self.asObservable() + .debounce(dueTime, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } +} + +// MARK: scan +extension SharedSequenceConvertibleType { + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, Element) -> A) + -> SharedSequence { + let source = self.asObservable() + .scan(seed, accumulator: accumulator) + return SharedSequence(source) + } +} + +// MARK: concat + +extension SharedSequence { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: Sequence) -> SharedSequence + where Sequence.Element == SharedSequence { + let source = Observable.concat(sequence.lazy.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.concat(collection.map { $0.asObservable() }) + return SharedSequence(source) + } +} + +// MARK: zip + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }, resultSelector: resultSelector) + return SharedSequence(source) + } + + /** + Merges the specified observable sequences into one observable sequence all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }) + return SharedSequence(source) + } +} + +// MARK: combineLatest + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.combineLatest(collection.map { $0.asObservable() }, resultSelector: resultSelector) + return SharedSequence(source) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.combineLatest(collection.map { $0.asObservable() }) + return SharedSequence(source) + } +} + +// MARK: - withUnretained +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. + - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) + } + + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained(_ obj: Object) -> SharedSequence { + withUnretained(obj) { ($0, $1) } + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + @available(*, message: "withUnretained has been deprecated for Driver. Consider using `drive(with:onNext:onCompleted:onDisposed:)`, instead", unavailable) + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) + } + + @available(*, message: "withUnretained has been deprecated for Driver. Consider using `drive(with:onNext:onCompleted:onDisposed:)`, instead", unavailable) + public func withUnretained(_ obj: Object) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj) { ($0, $1) }) + } +} + +// MARK: withLatestFrom +extension SharedSequenceConvertibleType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO, resultSelector: @escaping (Element, SecondO.Element) -> ResultType) -> SharedSequence where SecondO.SharingStrategy == SharingStrategy { + let source = self.asObservable() + .withLatestFrom(second.asSharedSequence(), resultSelector: resultSelector) + + return SharedSequence(source) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO) -> SharedSequence { + let source = self.asObservable() + .withLatestFrom(second.asSharedSequence()) + + return SharedSequence(source) + } +} + +// MARK: skip +extension SharedSequenceConvertibleType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> SharedSequence { + let source = self.asObservable() + .skip(count) + return SharedSequence(source) + } +} + +// MARK: startWith +extension SharedSequenceConvertibleType { + + /** + Prepends a value to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter element: Element to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ element: Element) + -> SharedSequence { + let source = self.asObservable() + .startWith(element) + + return SharedSequence(source) + } +} + +// MARK: delay +extension SharedSequenceConvertibleType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval) + -> SharedSequence { + let source = self.asObservable() + .delay(dueTime, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift new file mode 100644 index 00000000..4db2ee49 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift @@ -0,0 +1,226 @@ +// +// SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence that shares computation resources with following properties: + + - it never fails + - it delivers events on `SharingStrategy.scheduler` + - sharing strategy is customizable using `SharingStrategy.share` behavior + + `SharedSequence` can be considered a builder pattern for observable sequences that share computation resources. + + To find out more about units and how to use them, please visit `Documentation/Traits.md`. +*/ +public struct SharedSequence : SharedSequenceConvertibleType, ObservableConvertibleType { + let source: Observable + + init(_ source: Observable) { + self.source = SharingStrategy.share(source) + } + + init(raw: Observable) { + self.source = raw + } + + #if EXPANDABLE_SHARED_SEQUENCE + /** + This method is extension hook in case this unit needs to extended from outside the library. + + By defining `EXPANDABLE_SHARED_SEQUENCE` one agrees that it's up to them to ensure shared sequence + properties are preserved after extension. + */ + public static func createUnsafe(source: Source) -> SharedSequence { + SharedSequence(raw: source.asObservable()) + } + #endif + + /** + - returns: Built observable sequence. + */ + public func asObservable() -> Observable { + self.source + } + + /** + - returns: `self` + */ + public func asSharedSequence() -> SharedSequence { + self + } +} + +/** + Different `SharedSequence` sharing strategies must conform to this protocol. + */ +public protocol SharingStrategyProtocol { + /** + Scheduled on which all sequence events will be delivered. + */ + static var scheduler: SchedulerType { get } + + /** + Computation resources sharing strategy for multiple sequence observers. + + E.g. One can choose `share(replay:scope:)` + as sequence event sharing strategies, but also do something more exotic, like + implementing promises or lazy loading chains. + */ + static func share(_ source: Observable) -> Observable +} + +/** +A type that can be converted to `SharedSequence`. +*/ +public protocol SharedSequenceConvertibleType : ObservableConvertibleType { + associatedtype SharingStrategy: SharingStrategyProtocol + + /** + Converts self to `SharedSequence`. + */ + func asSharedSequence() -> SharedSequence +} + +extension SharedSequenceConvertibleType { + public func asObservable() -> Observable { + self.asSharedSequence().asObservable() + } +} + + +extension SharedSequence { + + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - returns: An observable sequence with no elements. + */ + public static func empty() -> SharedSequence { + SharedSequence(raw: Observable.empty().subscribe(on: SharingStrategy.scheduler)) + } + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> SharedSequence { + SharedSequence(raw: Observable.never()) + } + + /** + Returns an observable sequence that contains a single element. + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element) -> SharedSequence { + SharedSequence(raw: Observable.just(element).subscribe(on: SharingStrategy.scheduler)) + } + + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () -> SharedSequence) + -> SharedSequence { + SharedSequence(Observable.deferred { observableFactory().asObservable() }) + } + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: Element ...) -> SharedSequence { + let source = Observable.from(elements, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } +} + +extension SharedSequence { + + /** + This method converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [Element]) -> SharedSequence { + let source = Observable.from(array, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } + + /** + This method converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: Sequence) -> SharedSequence where Sequence.Element == Element { + let source = Observable.from(sequence, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } + + /** + This method converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?) -> SharedSequence { + let source = Observable.from(optional: optional, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } +} + +extension SharedSequence where Element: RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval) + -> SharedSequence { + SharedSequence(Observable.interval(period, scheduler: SharingStrategy.scheduler)) + } +} + +// MARK: timer + +extension SharedSequence where Element: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval) + -> SharedSequence { + SharedSequence(Observable.timer(dueTime, period: period, scheduler: SharingStrategy.scheduler)) + } +} + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift new file mode 100644 index 00000000..bec4723d --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift @@ -0,0 +1,25 @@ +// +// ControlEvent+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/1/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlEvent { + /// Converts `ControlEvent` to `Signal` trait. + /// + /// `ControlEvent` already can't fail, so no special case needs to be handled. + public func asSignal() -> Signal { + return self.asSignal { _ -> Signal in + #if DEBUG + rxFatalError("Somehow signal received error from a source that shouldn't fail.") + #else + return Signal.empty() + #endif + } + } +} + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift new file mode 100644 index 00000000..b962d4ed --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Signal trait. + */ + public func asSignal(onErrorJustReturn: Element) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catchAndReturn(onErrorJustReturn) + return Signal(source) + } + + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorSignalWith: Signal that continues to emit the sequence in case of error. + - returns: Signal trait. + */ + public func asSignal(onErrorSignalWith: Signal) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catch { _ in + onErrorSignalWith.asObservable() + } + return Signal(source) + } + + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorRecover: Calculates signal that continues to emit the sequence in case of error. + - returns: Signal trait. + */ + public func asSignal(onErrorRecover: @escaping (_ error: Swift.Error) -> Signal) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return Signal(source) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift new file mode 100644 index 00000000..79b975db --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift @@ -0,0 +1,21 @@ +// +// PublishRelay+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 12/28/15. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension PublishRelay { + /// Converts `PublishRelay` to `Signal`. + /// + /// - returns: Observable sequence. + public func asSignal() -> Signal { + let source = self.asObservable() + .observe(on:SignalSharingStrategy.scheduler) + return SharedSequence(source) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift new file mode 100644 index 00000000..4a6add33 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift @@ -0,0 +1,178 @@ +// +// Signal+Subscription.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /** + Creates new subscription and sends elements to observer. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func emit(to observers: Observer...) -> Disposable where Observer.Element == Element { + return self.asSharedSequence() + .asObservable() + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func emit(to observers: Observer...) -> Disposable where Observer.Element == Element? { + return self.asSharedSequence() + .asObservable() + .map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: BehaviorRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: BehaviorRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: PublishRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: PublishRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: ReplayRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relays: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: ReplayRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + Error callback is not exposed because `Signal` can't error out. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + self.asObservable().subscribe( + with: object, + onNext: onNext, + onCompleted: onCompleted, + onDisposed: onDisposed + ) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + + Error callback is not exposed because `Signal` can't error out. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit( + onNext: ((Element) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes to this `Signal` with a no-op. + This method can be only called from `MainThread`. + + - note: This is an alias of `emit(onNext: nil, onCompleted: nil, onDisposed: nil)` used to fix an ambiguity bug in Swift: https://bugs.swift.org/browse/SR-13657 + + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit() -> Disposable { + emit(onNext: nil, onCompleted: nil, onDisposed: nil) + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift new file mode 100644 index 00000000..e066b7ec --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift @@ -0,0 +1,45 @@ +// +// Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/26/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence with following properties: + + - it never fails + - it delivers events on `MainScheduler.instance` + - `share(scope: .whileConnected)` sharing strategy + + Additional explanation: + - all observers share sequence computation resources + - there is no replaying of sequence elements on new observer subscription + - computation of elements is reference counted with respect to the number of observers + - if there are no subscribers, it will release sequence computation resources + + In case trait that models state propagation is required, please check `Driver`. + + `Signal` can be considered a builder pattern for observable sequences that model imperative events part of the application. + + To find out more about units and how to use them, please visit `Documentation/Traits.md`. + */ +public typealias Signal = SharedSequence + +public struct SignalSharingStrategy: SharingStrategyProtocol { + public static var scheduler: SchedulerType { SharingScheduler.make() } + + public static func share(_ source: Observable) -> Observable { + source.share(scope: .whileConnected) + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /// Adds `asPublisher` to `SharingSequence` with `PublishSharingStrategy`. + public func asSignal() -> Signal { + self.asSharedSequence() + } +} diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift new file mode 100644 index 00000000..1acc998a --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift @@ -0,0 +1,108 @@ +// +// RxCollectionViewReactiveArrayDataSource.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// objc monkey business +class _RxCollectionViewReactiveArrayDataSource + : NSObject + , UICollectionViewDataSource { + + @objc(numberOfSectionsInCollectionView:) + func numberOfSections(in: UICollectionView) -> Int { + 1 + } + + func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + 0 + } + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + _collectionView(collectionView, numberOfItemsInSection: section) + } + + fileprivate func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + rxAbstractMethod() + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + _collectionView(collectionView, cellForItemAt: indexPath) + } +} + +class RxCollectionViewReactiveArrayDataSourceSequenceWrapper + : RxCollectionViewReactiveArrayDataSource + , RxCollectionViewDataSourceType { + typealias Element = Sequence + + override init(cellFactory: @escaping CellFactory) { + super.init(cellFactory: cellFactory) + } + + func collectionView(_ collectionView: UICollectionView, observedEvent: Event) { + Binder(self) { collectionViewDataSource, sectionModels in + let sections = Array(sectionModels) + collectionViewDataSource.collectionView(collectionView, observedElements: sections) + }.on(observedEvent) + } +} + + +// Please take a look at `DelegateProxyType.swift` +class RxCollectionViewReactiveArrayDataSource + : _RxCollectionViewReactiveArrayDataSource + , SectionedViewDataSourceType { + + typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell + + var itemModels: [Element]? + + func modelAtIndex(_ index: Int) -> Element? { + itemModels?[index] + } + + func model(at indexPath: IndexPath) throws -> Any { + precondition(indexPath.section == 0) + guard let item = itemModels?[indexPath.item] else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return item + } + + var cellFactory: CellFactory + + init(cellFactory: @escaping CellFactory) { + self.cellFactory = cellFactory + } + + // data source + + override func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + itemModels?.count ?? 0 + } + + override func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + cellFactory(collectionView, indexPath.item, itemModels![indexPath.item]) + } + + // reactive + + func collectionView(_ collectionView: UICollectionView, observedElements: [Element]) { + self.itemModels = observedElements + + collectionView.reloadData() + + // workaround for http://stackoverflow.com/questions/39867325/ios-10-bug-uicollectionview-received-layout-attributes-for-a-cell-with-an-index + collectionView.collectionViewLayout.invalidateLayout() + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift new file mode 100644 index 00000000..53b84754 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift @@ -0,0 +1,92 @@ +// +// RxPickerViewAdapter.swift +// RxCocoa +// +// Created by Sergey Shulga on 12/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +class RxPickerViewArrayDataSource: NSObject, UIPickerViewDataSource, SectionedViewDataSourceType { + fileprivate var items: [T] = [] + + func model(at indexPath: IndexPath) throws -> Any { + guard items.indices ~= indexPath.row else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return items[indexPath.row] + } + + func numberOfComponents(in pickerView: UIPickerView) -> Int { + 1 + } + + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + items.count + } +} + +class RxPickerViewSequenceDataSource + : RxPickerViewArrayDataSource + , RxPickerViewDataSourceType { + typealias Element = Sequence + + func pickerView(_ pickerView: UIPickerView, observedEvent: Event) { + Binder(self) { dataSource, items in + dataSource.items = items + pickerView.reloadAllComponents() + } + .on(observedEvent.map(Array.init)) + } +} + +final class RxStringPickerViewAdapter + : RxPickerViewSequenceDataSource + , UIPickerViewDelegate { + + typealias TitleForRow = (Int, Sequence.Element) -> String? + private let titleForRow: TitleForRow + + init(titleForRow: @escaping TitleForRow) { + self.titleForRow = titleForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { + titleForRow(row, items[row]) + } +} + +final class RxAttributedStringPickerViewAdapter: RxPickerViewSequenceDataSource, UIPickerViewDelegate { + typealias AttributedTitleForRow = (Int, Sequence.Element) -> NSAttributedString? + private let attributedTitleForRow: AttributedTitleForRow + + init(attributedTitleForRow: @escaping AttributedTitleForRow) { + self.attributedTitleForRow = attributedTitleForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { + attributedTitleForRow(row, items[row]) + } +} + +final class RxPickerViewAdapter: RxPickerViewSequenceDataSource, UIPickerViewDelegate { + typealias ViewForRow = (Int, Sequence.Element, UIView?) -> UIView + private let viewForRow: ViewForRow + + init(viewForRow: @escaping ViewForRow) { + self.viewForRow = viewForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { + viewForRow(row, items[row], view) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift new file mode 100644 index 00000000..6d612f32 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift @@ -0,0 +1,101 @@ +// +// RxTableViewReactiveArrayDataSource.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/26/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// objc monkey business +class _RxTableViewReactiveArrayDataSource + : NSObject + , UITableViewDataSource { + + func numberOfSections(in tableView: UITableView) -> Int { + 1 + } + + func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + 0 + } + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + _tableView(tableView, numberOfRowsInSection: section) + } + + fileprivate func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + rxAbstractMethod() + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + _tableView(tableView, cellForRowAt: indexPath) + } +} + + +class RxTableViewReactiveArrayDataSourceSequenceWrapper + : RxTableViewReactiveArrayDataSource + , RxTableViewDataSourceType { + typealias Element = Sequence + + override init(cellFactory: @escaping CellFactory) { + super.init(cellFactory: cellFactory) + } + + func tableView(_ tableView: UITableView, observedEvent: Event) { + Binder(self) { tableViewDataSource, sectionModels in + let sections = Array(sectionModels) + tableViewDataSource.tableView(tableView, observedElements: sections) + }.on(observedEvent) + } +} + +// Please take a look at `DelegateProxyType.swift` +class RxTableViewReactiveArrayDataSource + : _RxTableViewReactiveArrayDataSource + , SectionedViewDataSourceType { + typealias CellFactory = (UITableView, Int, Element) -> UITableViewCell + + var itemModels: [Element]? + + func modelAtIndex(_ index: Int) -> Element? { + itemModels?[index] + } + + func model(at indexPath: IndexPath) throws -> Any { + precondition(indexPath.section == 0) + guard let item = itemModels?[indexPath.item] else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return item + } + + let cellFactory: CellFactory + + init(cellFactory: @escaping CellFactory) { + self.cellFactory = cellFactory + } + + override func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + itemModels?.count ?? 0 + } + + override func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + cellFactory(tableView, indexPath.item, itemModels![indexPath.row]) + } + + // reactive + + func tableView(_ tableView: UITableView, observedElements: [Element]) { + self.itemModels = observedElements + + tableView.reloadData() + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift new file mode 100644 index 00000000..aadf7498 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift @@ -0,0 +1,15 @@ +// +// ItemEvents.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) +import UIKit + +public typealias ItemMovedEvent = (sourceIndex: IndexPath, destinationIndex: IndexPath) +public typealias WillDisplayCellEvent = (cell: UITableViewCell, indexPath: IndexPath) +public typealias DidEndDisplayingCellEvent = (cell: UITableViewCell, indexPath: IndexPath) +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift new file mode 100644 index 00000000..ba305476 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift @@ -0,0 +1,35 @@ +// +// NSTextStorage+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + import RxSwift + import UIKit + + extension Reactive where Base: NSTextStorage { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxTextStorageDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message. + public var didProcessEditingRangeChangeInLength: Observable<(editedMask: NSTextStorage.EditActions, editedRange: NSRange, delta: Int)> { + return delegate + .methodInvoked(#selector(NSTextStorageDelegate.textStorage(_:didProcessEditing:range:changeInLength:))) + .map { a in + let editedMask = NSTextStorage.EditActions(rawValue: try castOrThrow(UInt.self, a[1]) ) + let editedRange = try castOrThrow(NSValue.self, a[2]).rangeValue + let delta = try castOrThrow(Int.self, a[3]) + + return (editedMask, editedRange, delta) + } + } + } +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift new file mode 100644 index 00000000..b098a9ed --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift @@ -0,0 +1,27 @@ +// +// RxCollectionViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// Marks data source as `UICollectionView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxCollectionViewDataSourceType /*: UICollectionViewDataSource*/ { + + /// Type of elements that can be bound to collection view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter collectionView: Bound collection view. + /// - parameter observedEvent: Event + func collectionView(_ collectionView: UICollectionView, observedEvent: Event) +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift new file mode 100644 index 00000000..1f390bff --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift @@ -0,0 +1,26 @@ +// +// RxPickerViewDataSourceType.swift +// RxCocoa +// +// Created by Sergey Shulga on 05/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +/// Marks data source as `UIPickerView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxPickerViewDataSourceType { + /// Type of elements that can be bound to picker view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter pickerView: Bound picker view. + /// - parameter observedEvent: Event + func pickerView(_ pickerView: UIPickerView, observedEvent: Event) +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift new file mode 100644 index 00000000..d59af9e4 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift @@ -0,0 +1,27 @@ +// +// RxTableViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/26/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// Marks data source as `UITableView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxTableViewDataSourceType /*: UITableViewDataSource*/ { + + /// Type of elements that can be bound to table view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter tableView: Bound table view. + /// - parameter observedEvent: Event + func tableView(_ tableView: UITableView, observedEvent: Event) +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift new file mode 100644 index 00000000..5ddfda78 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift @@ -0,0 +1,92 @@ +// +// RxCollectionViewDataSourcePrefetchingProxy.swift +// RxCocoa +// +// Created by Rowan Livingstone on 2/15/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +@available(iOS 10.0, tvOS 10.0, *) +extension UICollectionView: HasPrefetchDataSource { + public typealias PrefetchDataSource = UICollectionViewDataSourcePrefetching +} + +@available(iOS 10.0, tvOS 10.0, *) +private let collectionViewPrefetchDataSourceNotSet = CollectionViewPrefetchDataSourceNotSet() + +@available(iOS 10.0, tvOS 10.0, *) +private final class CollectionViewPrefetchDataSourceNotSet + : NSObject + , UICollectionViewDataSourcePrefetching { + + func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {} + +} + +@available(iOS 10.0, tvOS 10.0, *) +open class RxCollectionViewDataSourcePrefetchingProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: ParentObject) { + self.collectionView = collectionView + super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourcePrefetchingProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxCollectionViewDataSourcePrefetchingProxy(collectionView: $0) } + } + + private var _prefetchItemsPublishSubject: PublishSubject<[IndexPath]>? + + /// Optimized version used for observing prefetch items callbacks. + internal var prefetchItemsPublishSubject: PublishSubject<[IndexPath]> { + if let subject = _prefetchItemsPublishSubject { + return subject + } + + let subject = PublishSubject<[IndexPath]>() + _prefetchItemsPublishSubject = subject + + return subject + } + + private weak var _requiredMethodsPrefetchDataSource: UICollectionViewDataSourcePrefetching? = collectionViewPrefetchDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSourcePrefetching?, retainDelegate: Bool) { + _requiredMethodsPrefetchDataSource = forwardToDelegate ?? collectionViewPrefetchDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + + deinit { + if let subject = _prefetchItemsPublishSubject { + subject.on(.completed) + } + } + +} + +@available(iOS 10.0, tvOS 10.0, *) +extension RxCollectionViewDataSourcePrefetchingProxy: UICollectionViewDataSourcePrefetching { + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { + if let subject = _prefetchItemsPublishSubject { + subject.on(.next(indexPaths)) + } + + (_requiredMethodsPrefetchDataSource ?? collectionViewPrefetchDataSourceNotSet).collectionView(collectionView, prefetchItemsAt: indexPaths) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift new file mode 100644 index 00000000..534b6fa4 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift @@ -0,0 +1,75 @@ +// +// RxCollectionViewDataSourceProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UICollectionView: HasDataSource { + public typealias DataSource = UICollectionViewDataSource +} + +private let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() + +private final class CollectionViewDataSourceNotSet + : NSObject + , UICollectionViewDataSource { + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + 0 + } + + // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + rxAbstractMethod(message: dataSourceNotSet) + } + +} + +/// For more information take a look at `DelegateProxyType`. +open class RxCollectionViewDataSourceProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: ParentObject) { + self.collectionView = collectionView + super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxCollectionViewDataSourceProxy(collectionView: $0) } + } + + private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? collectionViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +extension RxCollectionViewDataSourceProxy: UICollectionViewDataSource { + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) + } + + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift new file mode 100644 index 00000000..da04caa6 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift @@ -0,0 +1,32 @@ +// +// RxCollectionViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxCollectionViewDelegateProxy + : RxScrollViewDelegateProxy { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// Initializes `RxCollectionViewDelegateProxy` + /// + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: UICollectionView) { + self.collectionView = collectionView + super.init(scrollView: collectionView) + } +} + +extension RxCollectionViewDelegateProxy: UICollectionViewDelegateFlowLayout {} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift new file mode 100644 index 00000000..b4a827ed --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// RxNavigationControllerDelegateProxy.swift +// RxCocoa +// +// Created by Diogo on 13/04/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import UIKit + import RxSwift + + extension UINavigationController: HasDelegate { + public typealias Delegate = UINavigationControllerDelegate + } + + /// For more information take a look at `DelegateProxyType`. + open class RxNavigationControllerDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var navigationController: UINavigationController? + + /// - parameter navigationController: Parent object for delegate proxy. + public init(navigationController: ParentObject) { + self.navigationController = navigationController + super.init(parentObject: navigationController, delegateProxy: RxNavigationControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxNavigationControllerDelegateProxy(navigationController: $0) } + } + } + + extension RxNavigationControllerDelegateProxy: UINavigationControllerDelegate {} +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift new file mode 100644 index 00000000..ecd0288d --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift @@ -0,0 +1,72 @@ +// +// RxPickerViewDataSourceProxy.swift +// RxCocoa +// +// Created by Sergey Shulga on 05/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension UIPickerView: HasDataSource { + public typealias DataSource = UIPickerViewDataSource +} + +private let pickerViewDataSourceNotSet = PickerViewDataSourceNotSet() + +final private class PickerViewDataSourceNotSet: NSObject, UIPickerViewDataSource { + func numberOfComponents(in pickerView: UIPickerView) -> Int { + 0 + } + + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + 0 + } +} + +/// For more information take a look at `DelegateProxyType`. +public class RxPickerViewDataSourceProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var pickerView: UIPickerView? + + /// - parameter pickerView: Parent object for delegate proxy. + public init(pickerView: ParentObject) { + self.pickerView = pickerView + super.init(parentObject: pickerView, delegateProxy: RxPickerViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxPickerViewDataSourceProxy(pickerView: $0) } + } + + private weak var _requiredMethodsDataSource: UIPickerViewDataSource? = pickerViewDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + public override func setForwardToDelegate(_ forwardToDelegate: UIPickerViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? pickerViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +// MARK: UIPickerViewDataSource + +extension RxPickerViewDataSourceProxy: UIPickerViewDataSource { + /// Required delegate method implementation. + public func numberOfComponents(in pickerView: UIPickerView) -> Int { + (_requiredMethodsDataSource ?? pickerViewDataSourceNotSet).numberOfComponents(in: pickerView) + } + + /// Required delegate method implementation. + public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + (_requiredMethodsDataSource ?? pickerViewDataSourceNotSet).pickerView(pickerView, numberOfRowsInComponent: component) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift new file mode 100644 index 00000000..9e64f01f --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift @@ -0,0 +1,38 @@ +// +// RxPickerViewDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension UIPickerView: HasDelegate { + public typealias Delegate = UIPickerViewDelegate + } + + open class RxPickerViewDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var pickerView: UIPickerView? + + /// - parameter pickerView: Parent object for delegate proxy. + public init(pickerView: ParentObject) { + self.pickerView = pickerView + super.init(parentObject: pickerView, delegateProxy: RxPickerViewDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxPickerViewDelegateProxy(pickerView: $0) } + } + } + + extension RxPickerViewDelegateProxy: UIPickerViewDelegate {} +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift new file mode 100644 index 00000000..02e75920 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift @@ -0,0 +1,91 @@ +// +// RxScrollViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension UIScrollView: HasDelegate { + public typealias Delegate = UIScrollViewDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxScrollViewDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var scrollView: UIScrollView? + + /// - parameter scrollView: Parent object for delegate proxy. + public init(scrollView: ParentObject) { + self.scrollView = scrollView + super.init(parentObject: scrollView, delegateProxy: RxScrollViewDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxScrollViewDelegateProxy(scrollView: $0) } + self.register { RxTableViewDelegateProxy(tableView: $0) } + self.register { RxCollectionViewDelegateProxy(collectionView: $0) } + self.register { RxTextViewDelegateProxy(textView: $0) } + } + + private var _contentOffsetBehaviorSubject: BehaviorSubject? + private var _contentOffsetPublishSubject: PublishSubject<()>? + + /// Optimized version used for observing content offset changes. + internal var contentOffsetBehaviorSubject: BehaviorSubject { + if let subject = _contentOffsetBehaviorSubject { + return subject + } + + let subject = BehaviorSubject(value: self.scrollView?.contentOffset ?? CGPoint.zero) + _contentOffsetBehaviorSubject = subject + + return subject + } + + /// Optimized version used for observing content offset changes. + internal var contentOffsetPublishSubject: PublishSubject<()> { + if let subject = _contentOffsetPublishSubject { + return subject + } + + let subject = PublishSubject<()>() + _contentOffsetPublishSubject = subject + + return subject + } + + deinit { + if let subject = _contentOffsetBehaviorSubject { + subject.on(.completed) + } + + if let subject = _contentOffsetPublishSubject { + subject.on(.completed) + } + } +} + +extension RxScrollViewDelegateProxy: UIScrollViewDelegate { + /// For more information take a look at `DelegateProxyType`. + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + if let subject = _contentOffsetBehaviorSubject { + subject.on(.next(scrollView.contentOffset)) + } + if let subject = _contentOffsetPublishSubject { + subject.on(.next(())) + } + self._forwardToDelegate?.scrollViewDidScroll?(scrollView) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift new file mode 100644 index 00000000..94bd30bd --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift @@ -0,0 +1,40 @@ +// +// RxSearchBarDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UISearchBar: HasDelegate { + public typealias Delegate = UISearchBarDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxSearchBarDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var searchBar: UISearchBar? + + /// - parameter searchBar: Parent object for delegate proxy. + public init(searchBar: ParentObject) { + self.searchBar = searchBar + super.init(parentObject: searchBar, delegateProxy: RxSearchBarDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxSearchBarDelegateProxy(searchBar: $0) } + } +} + +extension RxSearchBarDelegateProxy: UISearchBarDelegate {} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift new file mode 100644 index 00000000..64e36a21 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift @@ -0,0 +1,40 @@ +// +// RxSearchControllerDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 3/17/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension UISearchController: HasDelegate { + public typealias Delegate = UISearchControllerDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxSearchControllerDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var searchController: UISearchController? + + /// - parameter searchController: Parent object for delegate proxy. + public init(searchController: UISearchController) { + self.searchController = searchController + super.init(parentObject: searchController, delegateProxy: RxSearchControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxSearchControllerDelegateProxy(searchController: $0) } + } +} + +extension RxSearchControllerDelegateProxy: UISearchControllerDelegate {} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift new file mode 100644 index 00000000..62d42ac0 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift @@ -0,0 +1,40 @@ +// +// RxTabBarControllerDelegateProxy.swift +// RxCocoa +// +// Created by Yusuke Kita on 2016/12/07. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITabBarController: HasDelegate { + public typealias Delegate = UITabBarControllerDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTabBarControllerDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tabBar: UITabBarController? + + /// - parameter tabBar: Parent object for delegate proxy. + public init(tabBar: ParentObject) { + self.tabBar = tabBar + super.init(parentObject: tabBar, delegateProxy: RxTabBarControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTabBarControllerDelegateProxy(tabBar: $0) } + } +} + +extension RxTabBarControllerDelegateProxy: UITabBarControllerDelegate {} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift new file mode 100644 index 00000000..49c5cf7f --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift @@ -0,0 +1,50 @@ +// +// RxTabBarDelegateProxy.swift +// RxCocoa +// +// Created by Jesse Farless on 5/14/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITabBar: HasDelegate { + public typealias Delegate = UITabBarDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTabBarDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tabBar: UITabBar? + + /// - parameter tabBar: Parent object for delegate proxy. + public init(tabBar: ParentObject) { + self.tabBar = tabBar + super.init(parentObject: tabBar, delegateProxy: RxTabBarDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTabBarDelegateProxy(tabBar: $0) } + } + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> UITabBarDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: UITabBarDelegate?, to object: ParentObject) { + object.delegate = delegate + } +} + +extension RxTabBarDelegateProxy: UITabBarDelegate {} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift new file mode 100644 index 00000000..d0831f2e --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift @@ -0,0 +1,93 @@ +// +// RxTableViewDataSourcePrefetchingProxy.swift +// RxCocoa +// +// Created by Rowan Livingstone on 2/15/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +@available(iOS 10.0, tvOS 10.0, *) +extension UITableView: HasPrefetchDataSource { + public typealias PrefetchDataSource = UITableViewDataSourcePrefetching +} + +@available(iOS 10.0, tvOS 10.0, *) +private let tableViewPrefetchDataSourceNotSet = TableViewPrefetchDataSourceNotSet() + +@available(iOS 10.0, tvOS 10.0, *) +private final class TableViewPrefetchDataSourceNotSet + : NSObject + , UITableViewDataSourcePrefetching { + + func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {} + +} + +@available(iOS 10.0, tvOS 10.0, *) +open class RxTableViewDataSourcePrefetchingProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: ParentObject) { + self.tableView = tableView + super.init(parentObject: tableView, delegateProxy: RxTableViewDataSourcePrefetchingProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTableViewDataSourcePrefetchingProxy(tableView: $0) } + } + + private var _prefetchRowsPublishSubject: PublishSubject<[IndexPath]>? + + /// Optimized version used for observing prefetch rows callbacks. + internal var prefetchRowsPublishSubject: PublishSubject<[IndexPath]> { + if let subject = _prefetchRowsPublishSubject { + return subject + } + + let subject = PublishSubject<[IndexPath]>() + _prefetchRowsPublishSubject = subject + + return subject + } + + private weak var _requiredMethodsPrefetchDataSource: UITableViewDataSourcePrefetching? = tableViewPrefetchDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UITableViewDataSourcePrefetching?, retainDelegate: Bool) { + _requiredMethodsPrefetchDataSource = forwardToDelegate ?? tableViewPrefetchDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + + deinit { + if let subject = _prefetchRowsPublishSubject { + subject.on(.completed) + } + } + +} + +@available(iOS 10.0, tvOS 10.0, *) +extension RxTableViewDataSourcePrefetchingProxy: UITableViewDataSourcePrefetching { + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { + if let subject = _prefetchRowsPublishSubject { + subject.on(.next(indexPaths)) + } + + (_requiredMethodsPrefetchDataSource ?? tableViewPrefetchDataSourceNotSet).tableView(tableView, prefetchRowsAt: indexPaths) + } +} + +#endif + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift new file mode 100644 index 00000000..4c5e8638 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift @@ -0,0 +1,73 @@ +// +// RxTableViewDataSourceProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITableView: HasDataSource { + public typealias DataSource = UITableViewDataSource +} + +private let tableViewDataSourceNotSet = TableViewDataSourceNotSet() + +private final class TableViewDataSourceNotSet + : NSObject + , UITableViewDataSource { + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + 0 + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + rxAbstractMethod(message: dataSourceNotSet) + } +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTableViewDataSourceProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: UITableView) { + self.tableView = tableView + super.init(parentObject: tableView, delegateProxy: RxTableViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTableViewDataSourceProxy(tableView: $0) } + } + + private weak var _requiredMethodsDataSource: UITableViewDataSource? = tableViewDataSourceNotSet + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UITableViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? tableViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +extension RxTableViewDataSourceProxy: UITableViewDataSource { + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, numberOfRowsInSection: section) + } + + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, cellForRowAt: indexPath) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift new file mode 100644 index 00000000..901fe665 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift @@ -0,0 +1,31 @@ +// +// RxTableViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxTableViewDelegateProxy + : RxScrollViewDelegateProxy { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: UITableView) { + self.tableView = tableView + super.init(scrollView: tableView) + } + +} + +extension RxTableViewDelegateProxy: UITableViewDelegate {} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift new file mode 100644 index 00000000..e8ff33f0 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift @@ -0,0 +1,38 @@ +// +// RxTextStorageDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import RxSwift + import UIKit + + extension NSTextStorage: HasDelegate { + public typealias Delegate = NSTextStorageDelegate + } + + open class RxTextStorageDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var textStorage: NSTextStorage? + + /// - parameter textStorage: Parent object for delegate proxy. + public init(textStorage: NSTextStorage) { + self.textStorage = textStorage + super.init(parentObject: textStorage, delegateProxy: RxTextStorageDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTextStorageDelegateProxy(textStorage: $0) } + } + } + + extension RxTextStorageDelegateProxy: NSTextStorageDelegate {} +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift new file mode 100644 index 00000000..9d934247 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift @@ -0,0 +1,42 @@ +// +// RxTextViewDelegateProxy.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 7/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxTextViewDelegateProxy + : RxScrollViewDelegateProxy { + + /// Typed parent object. + public weak private(set) var textView: UITextView? + + /// - parameter textview: Parent object for delegate proxy. + public init(textView: UITextView) { + self.textView = textView + super.init(scrollView: textView) + } +} + +extension RxTextViewDelegateProxy: UITextViewDelegate { + /// For more information take a look at `DelegateProxyType`. + @objc open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { + /** + We've had some issues with observing text changes. This is here just in case we need the same hack in future and that + we wouldn't need to change the public interface. + */ + let forwardToDelegate = self.forwardToDelegate() as? UITextViewDelegate + return forwardToDelegate?.textView?(textView, + shouldChangeTextIn: range, + replacementText: text) ?? true + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift new file mode 100644 index 00000000..0fa16b49 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift @@ -0,0 +1,45 @@ +// +// RxWKNavigationDelegateProxy.swift +// RxCocoa +// +// Created by Giuseppe Lanza on 14/02/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(macOS) + +import RxSwift +import WebKit + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +open class RxWKNavigationDelegateProxy + : DelegateProxy + , DelegateProxyType { + + /// Typed parent object. + public weak private(set) var webView: WKWebView? + + /// - parameter webView: Parent object for delegate proxy. + public init(webView: ParentObject) { + self.webView = webView + super.init(parentObject: webView, delegateProxy: RxWKNavigationDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxWKNavigationDelegateProxy(webView: $0) } + } + + public static func currentDelegate(for object: WKWebView) -> WKNavigationDelegate? { + object.navigationDelegate + } + + public static func setCurrentDelegate(_ delegate: WKNavigationDelegate?, to object: WKWebView) { + object.navigationDelegate = delegate + } +} + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +extension RxWKNavigationDelegateProxy: WKNavigationDelegate {} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift new file mode 100644 index 00000000..ca2d4f1b --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift @@ -0,0 +1,27 @@ +// +// UIActivityIndicatorView+Rx.swift +// RxCocoa +// +// Created by Ivan Persidskiy on 02/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIActivityIndicatorView { + /// Bindable sink for `startAnimating()`, `stopAnimating()` methods. + public var isAnimating: Binder { + Binder(self.base) { activityIndicator, active in + if active { + activityIndicator.startAnimating() + } else { + activityIndicator.stopAnimating() + } + } + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift new file mode 100644 index 00000000..d7761058 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift @@ -0,0 +1,106 @@ +// +// UIApplication+Rx.swift +// RxCocoa +// +// Created by Mads Bøgeskov on 18/01/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIApplication { + /// Bindable sink for `isNetworkActivityIndicatorVisible`. + public var isNetworkActivityIndicatorVisible: Binder { + return Binder(self.base) { application, active in + application.isNetworkActivityIndicatorVisible = active + } + } + + /// Reactive wrapper for `UIApplication.didEnterBackgroundNotification` + public static var didEnterBackground: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didEnterBackgroundNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willEnterForegroundNotification` + public static var willEnterForeground: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didFinishLaunchingNotification` + public static var didFinishLaunching: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didFinishLaunchingNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didBecomeActiveNotification` + public static var didBecomeActive: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willResignActiveNotification` + public static var willResignActive: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willResignActiveNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didReceiveMemoryWarningNotification` + public static var didReceiveMemoryWarning: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didReceiveMemoryWarningNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willTerminateNotification` + public static var willTerminate: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willTerminateNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.significantTimeChangeNotification` + public static var significantTimeChange: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.significantTimeChangeNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.backgroundRefreshStatusDidChangeNotification` + public static var backgroundRefreshStatusDidChange: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.backgroundRefreshStatusDidChangeNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.protectedDataWillBecomeUnavailableNotification` + public static var protectedDataWillBecomeUnavailable: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.protectedDataWillBecomeUnavailableNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.protectedDataDidBecomeAvailableNotification` + public static var protectedDataDidBecomeAvailable: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.protectedDataDidBecomeAvailableNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.userDidTakeScreenshotNotification` + public static var userDidTakeScreenshot: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.userDidTakeScreenshotNotification).map { _ in } + + return ControlEvent(events: source) + } +} +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift new file mode 100644 index 00000000..0bcaa994 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift @@ -0,0 +1,72 @@ +// +// UIBarButtonItem+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +private var rx_tap_key: UInt8 = 0 + +extension Reactive where Base: UIBarButtonItem { + /// Reactive wrapper for target action pattern on `self`. + public var tap: ControlEvent<()> { + let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in + Observable.create { [weak control = self.base] observer in + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + let target = BarButtonItemTarget(barButtonItem: control) { + observer.on(.next(())) + } + return target + } + .take(until: self.deallocated) + .share() + } + + return ControlEvent(events: source) + } +} + + +@objc +final class BarButtonItemTarget: RxTarget { + typealias Callback = () -> Void + + weak var barButtonItem: UIBarButtonItem? + var callback: Callback! + + init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { + self.barButtonItem = barButtonItem + self.callback = callback + super.init() + barButtonItem.target = self + barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) + } + + override func dispose() { + super.dispose() +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + + barButtonItem?.target = nil + barButtonItem?.action = nil + + callback = nil + } + + @objc func action(_ sender: AnyObject) { + callback() + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift new file mode 100644 index 00000000..4d0f4c32 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift @@ -0,0 +1,82 @@ +// +// UIButton+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + + /// Reactive wrapper for `TouchUpInside` control event. + public var tap: ControlEvent { + controlEvent(.touchUpInside) + } +} + +#endif + +#if os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + + /// Reactive wrapper for `PrimaryActionTriggered` control event. + public var primaryAction: ControlEvent { + controlEvent(.primaryActionTriggered) + } + +} + +#endif + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + /// Reactive wrapper for `setTitle(_:for:)` + public func title(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, title in + button.setTitle(title, for: controlState) + } + } + + /// Reactive wrapper for `setImage(_:for:)` + public func image(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, image in + button.setImage(image, for: controlState) + } + } + + /// Reactive wrapper for `setBackgroundImage(_:for:)` + public func backgroundImage(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, image in + button.setBackgroundImage(image, for: controlState) + } + } + +} +#endif + +#if os(iOS) || os(tvOS) + import RxSwift + import UIKit + + extension Reactive where Base: UIButton { + /// Reactive wrapper for `setAttributedTitle(_:controlState:)` + public func attributedTitle(for controlState: UIControl.State = []) -> Binder { + return Binder(self.base) { button, attributedTitle -> Void in + button.setAttributedTitle(attributedTitle, for: controlState) + } + } + } +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift new file mode 100644 index 00000000..8f4bdb3a --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift @@ -0,0 +1,380 @@ +// +// UICollectionView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +// Items + +extension Reactive where Base: UICollectionView { + + /** + Binds sequences of elements to collection view items. + + - parameter source: Observable sequence of items. + - parameter cellFactory: Transform between sequence elements and view cells. + - returns: Disposable object that can be used to unbind. + + Example + + let items = Observable.just([ + 1, + 2, + 3 + ]) + + items + .bind(to: collectionView.rx.items) { (collectionView, row, element) in + let indexPath = IndexPath(row: row, section: 0) + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell + cell.value?.text = "\(element) @ \(row)" + return cell + } + .disposed(by: disposeBag) + */ + public func items + (_ source: Source) + -> (_ cellFactory: @escaping (UICollectionView, Int, Sequence.Element) -> UICollectionViewCell) + -> Disposable where Source.Element == Sequence { + return { cellFactory in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + return self.items(dataSource: dataSource)(source) + } + + } + + /** + Binds sequences of elements to collection view items. + + - parameter cellIdentifier: Identifier used to dequeue cells. + - parameter source: Observable sequence of items. + - parameter configureCell: Transform between sequence elements and view cells. + - parameter cellType: Type of collection view cell. + - returns: Disposable object that can be used to unbind. + + Example + + let items = Observable.just([ + 1, + 2, + 3 + ]) + + items + .bind(to: collectionView.rx.items(cellIdentifier: "Cell", cellType: NumberCell.self)) { (row, element, cell) in + cell.value?.text = "\(element) @ \(row)" + } + .disposed(by: disposeBag) + */ + public func items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (_ source: Source) + -> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void) + -> Disposable where Source.Element == Sequence { + return { source in + return { configureCell in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper { cv, i, item in + let indexPath = IndexPath(item: i, section: 0) + let cell = cv.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! Cell + configureCell(i, item, cell) + return cell + } + + return self.items(dataSource: dataSource)(source) + } + } + } + + + /** + Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. + + - parameter dataSource: Data source used to transform elements to view cells. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + + Example + + let dataSource = RxCollectionViewSectionedReloadDataSource>() + + let items = Observable.just([ + SectionModel(model: "First section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Second section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Third section", items: [ + 1.0, + 2.0, + 3.0 + ]) + ]) + + dataSource.configureCell = { (dataSource, cv, indexPath, element) in + let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell + cell.value?.text = "\(element) @ row \(indexPath.row)" + return cell + } + + items + .bind(to: collectionView.rx.items(dataSource: dataSource)) + .disposed(by: disposeBag) + */ + public func items< + DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, + Source: ObservableType> + (dataSource: DataSource) + -> (_ source: Source) + -> Disposable where DataSource.Element == Source.Element + { + return { source in + // This is called for side effects only, and to make sure delegate proxy is in place when + // data source is being bound. + // This is needed because theoretically the data source subscription itself might + // call `self.rx.delegate`. If that happens, it might cause weird side effects since + // setting data source will set delegate, and UICollectionView might get into a weird state. + // Therefore it's better to set delegate proxy first, just to be sure. + _ = self.delegate + // Strong reference is needed because data source is in use until result subscription is disposed + return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak collectionView = self.base] (_: RxCollectionViewDataSourceProxy, event) -> Void in + guard let collectionView = collectionView else { + return + } + dataSource.collectionView(collectionView, observedEvent: event) + } + } + } +} + +extension Reactive where Base: UICollectionView { + public typealias DisplayCollectionViewCellEvent = (cell: UICollectionViewCell, at: IndexPath) + public typealias DisplayCollectionViewSupplementaryViewEvent = (supplementaryView: UICollectionReusableView, elementKind: String, at: IndexPath) + + /// Reactive wrapper for `dataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var dataSource: DelegateProxy { + RxCollectionViewDataSourceProxy.proxy(for: base) + } + + /// Installs data source as forwarding delegate on `rx.dataSource`. + /// Data source won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter dataSource: Data source object. + /// - returns: Disposable object that can be used to unbind the data source. + public func setDataSource(_ dataSource: UICollectionViewDataSource) + -> Disposable { + RxCollectionViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + public var itemSelected: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didSelectItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didDeselectItemAtIndexPath:)`. + public var itemDeselected: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didDeselectItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didHighlightItemAt:)`. + public var itemHighlighted: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didHighlightItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didUnhighlightItemAt:)`. + public var itemUnhighlighted: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUnhighlightItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView:willDisplay:forItemAt:`. + public var willDisplayCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplay:forItemAt:))) + .map { a in + return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:willDisplaySupplementaryView:forElementKind:at:)`. + public var willDisplaySupplementaryView: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplaySupplementaryView:forElementKind:at:))) + .map { a in + return (try castOrThrow(UICollectionReusableView.self, a[1]), + try castOrThrow(String.self, a[2]), + try castOrThrow(IndexPath.self, a[3])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView:didEndDisplaying:forItemAt:`. + public var didEndDisplayingCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplaying:forItemAt:))) + .map { a in + return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:)`. + public var didEndDisplayingSupplementaryView: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:))) + .map { a in + return (try castOrThrow(UICollectionReusableView.self, a[1]), + try castOrThrow(String.self, a[2]), + try castOrThrow(IndexPath.self, a[3])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + /// + /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + /// or any other data source conforming to `SectionedViewDataSourceType` protocol. + /// + /// ``` + /// collectionView.rx.modelSelected(MyModel.self) + /// .map { ... + /// ``` + public func modelSelected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = itemSelected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + /// + /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + /// or any other data source conforming to `SectionedViewDataSourceType` protocol. + /// + /// ``` + /// collectionView.rx.modelDeselected(MyModel.self) + /// .map { ... + /// ``` + public func modelDeselected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = itemDeselected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /// Synchronous helper method for retrieving a model at indexPath through a reactive data source + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemsWith*` methods was used.") + + let element = try dataSource.model(at: indexPath) + + return try castOrThrow(T.self, element) + } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension Reactive where Base: UICollectionView { + + /// Reactive wrapper for `prefetchDataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var prefetchDataSource: DelegateProxy { + RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base) + } + + /** + Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. + Prefetch data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter prefetchDataSource: Prefetch data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setPrefetchDataSource(_ prefetchDataSource: UICollectionViewDataSourcePrefetching) + -> Disposable { + return RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:prefetchItemsAt:)`. + public var prefetchItems: ControlEvent<[IndexPath]> { + let source = RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base).prefetchItemsPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:cancelPrefetchingForItemsAt:)`. + public var cancelPrefetchingForItems: ControlEvent<[IndexPath]> { + let source = prefetchDataSource.methodInvoked(#selector(UICollectionViewDataSourcePrefetching.collectionView(_:cancelPrefetchingForItemsAt:))) + .map { a in + return try castOrThrow(Array.self, a[1]) + } + + return ControlEvent(events: source) + } + +} +#endif + +#if os(tvOS) + +extension Reactive where Base: UICollectionView { + + /// Reactive wrapper for `delegate` message `collectionView(_:didUpdateFocusInContext:withAnimationCoordinator:)`. + public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { + + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUpdateFocusIn:with:))) + .map { a -> (context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in + let context = try castOrThrow(UICollectionViewFocusUpdateContext.self, a[1]) + let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) + return (context: context, animationCoordinator: animationCoordinator) + } + + return ControlEvent(events: source) + } +} +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift new file mode 100644 index 00000000..6698cf24 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift @@ -0,0 +1,86 @@ +// +// UIControl+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIControl { + /// Reactive wrapper for target action pattern. + /// + /// - parameter controlEvents: Filter for observed event types. + public func controlEvent(_ controlEvents: UIControl.Event) -> ControlEvent<()> { + let source: Observable = Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) { _ in + observer.on(.next(())) + } + + return Disposables.create(with: controlTarget.dispose) + } + .take(until: deallocated) + + return ControlEvent(events: source) + } + + /// Creates a `ControlProperty` that is triggered by target/action pattern value updates. + /// + /// - parameter controlEvents: Events that trigger value update sequence elements. + /// - parameter getter: Property value getter. + /// - parameter setter: Property value setter. + public func controlProperty( + editingEvents: UIControl.Event, + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + let source: Observable = Observable.create { [weak weakControl = base] observer in + guard let control = weakControl else { + observer.on(.completed) + return Disposables.create() + } + + observer.on(.next(getter(control))) + + let controlTarget = ControlTarget(control: control, controlEvents: editingEvents) { _ in + if let control = weakControl { + observer.on(.next(getter(control))) + } + } + + return Disposables.create(with: controlTarget.dispose) + } + .take(until: deallocated) + + let bindingObserver = Binder(base, binding: setter) + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// This is a separate method to better communicate to public consumers that + /// an `editingEvent` needs to fire for control property to be updated. + internal func controlPropertyWithDefaultEvents( + editingEvents: UIControl.Event = [.allEditingEvents, .valueChanged], + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + return controlProperty( + editingEvents: editingEvents, + getter: getter, + setter: setter + ) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift new file mode 100644 index 00000000..e10c1ec9 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift @@ -0,0 +1,43 @@ +// +// UIDatePicker+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIDatePicker { + /// Reactive wrapper for `date` property. + public var date: ControlProperty { + value + } + + /// Reactive wrapper for `date` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { datePicker in + datePicker.date + }, setter: { datePicker, value in + datePicker.date = value + } + ) + } + + /// Reactive wrapper for `countDownDuration` property. + public var countDownDuration: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { datePicker in + datePicker.countDownDuration + }, setter: { datePicker, value in + datePicker.countDownDuration = value + } + ) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift new file mode 100644 index 00000000..55129008 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift @@ -0,0 +1,75 @@ +// +// UIGestureRecognizer+Rx.swift +// RxCocoa +// +// Created by Carlos García on 10/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// This should be only used from `MainScheduler` +final class GestureTarget: RxTarget { + typealias Callback = (Recognizer) -> Void + + let selector = #selector(ControlTarget.eventHandler(_:)) + + weak var gestureRecognizer: Recognizer? + var callback: Callback? + + init(_ gestureRecognizer: Recognizer, callback: @escaping Callback) { + self.gestureRecognizer = gestureRecognizer + self.callback = callback + + super.init() + + gestureRecognizer.addTarget(self, action: selector) + + let method = self.method(for: selector) + if method == nil { + fatalError("Can't find method") + } + } + + @objc func eventHandler(_ sender: UIGestureRecognizer) { + if let callback = self.callback, let gestureRecognizer = self.gestureRecognizer { + callback(gestureRecognizer) + } + } + + override func dispose() { + super.dispose() + + self.gestureRecognizer?.removeTarget(self, action: self.selector) + self.callback = nil + } +} + +extension Reactive where Base: UIGestureRecognizer { + + /// Reactive wrapper for gesture recognizer events. + public var event: ControlEvent { + let source: Observable = Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let observer = GestureTarget(control) { control in + observer.on(.next(control)) + } + + return observer + }.take(until: deallocated) + + return ControlEvent(events: source) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift new file mode 100644 index 00000000..94796b65 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift @@ -0,0 +1,49 @@ +// +// UINavigationController+Rx.swift +// RxCocoa +// +// Created by Diogo on 13/04/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UINavigationController { + public typealias ShowEvent = (viewController: UIViewController, animated: Bool) + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxNavigationControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for delegate method `navigationController(:willShow:animated:)`. + public var willShow: ControlEvent { + let source: Observable = delegate + .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:willShow:animated:))) + .map { arg in + let viewController = try castOrThrow(UIViewController.self, arg[1]) + let animated = try castOrThrow(Bool.self, arg[2]) + return (viewController, animated) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `navigationController(:didShow:animated:)`. + public var didShow: ControlEvent { + let source: Observable = delegate + .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:))) + .map { arg in + let viewController = try castOrThrow(UIViewController.self, arg[1]) + let animated = try castOrThrow(Bool.self, arg[2]) + return (viewController, animated) + } + return ControlEvent(events: source) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift new file mode 100644 index 00000000..317dc13b --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift @@ -0,0 +1,224 @@ +// +// UIPickerView+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UIPickerView { + + /// Reactive wrapper for `delegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxPickerViewDelegateProxy.proxy(for: base) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UIPickerViewDelegate) + -> Disposable { + return RxPickerViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } + + /** + Reactive wrapper for `dataSource`. + + For more information take a look at `DelegateProxyType` protocol documentation. + */ + public var dataSource: DelegateProxy { + return RxPickerViewDataSourceProxy.proxy(for: base) + } + + /** + Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. + */ + public var itemSelected: ControlEvent<(row: Int, component: Int)> { + let source = delegate + .methodInvoked(#selector(UIPickerViewDelegate.pickerView(_:didSelectRow:inComponent:))) + .map { + return (row: try castOrThrow(Int.self, $0[1]), component: try castOrThrow(Int.self, $0[2])) + } + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. + + It can be only used when one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods is used to bind observable sequence, + or any other data source conforming to a `ViewDataSourceType` protocol. + + ``` + pickerView.rx.modelSelected(MyModel.self) + .map { ... + ``` + - parameter modelType: Type of a Model which bound to the dataSource + */ + public func modelSelected(_ modelType: T.Type) -> ControlEvent<[T]> { + let source = itemSelected.flatMap { [weak view = self.base as UIPickerView] _, component -> Observable<[T]> in + guard let view = view else { + return Observable.empty() + } + + let model: [T] = try (0 ..< view.numberOfComponents).map { component in + let row = view.selectedRow(inComponent: component) + return try view.rx.model(at: IndexPath(row: row, section: component)) + } + + return Observable.just(model) + } + + return ControlEvent(events: source) + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter titleForRow: Transform between sequence elements and row titles. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.itemTitles) { (row, element) in + return element.title + } + .disposed(by: disposeBag) + + */ + + public func itemTitles + (_ source: Source) + -> (_ titleForRow: @escaping (Int, Sequence.Element) -> String?) + -> Disposable where Source.Element == Sequence { + return { titleForRow in + let adapter = RxStringPickerViewAdapter(titleForRow: titleForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter attributedTitleForRow: Transform between sequence elements and row attributed titles. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.itemAttributedTitles) { (row, element) in + return NSAttributedString(string: element.title) + } + .disposed(by: disposeBag) + + */ + + public func itemAttributedTitles + (_ source: Source) + -> (_ attributedTitleForRow: @escaping (Int, Sequence.Element) -> NSAttributedString?) + -> Disposable where Source.Element == Sequence { + return { attributedTitleForRow in + let adapter = RxAttributedStringPickerViewAdapter(attributedTitleForRow: attributedTitleForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter viewForRow: Transform between sequence elements and row views. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.items) { (row, element, view) in + guard let myView = view as? MyView else { + let view = MyView() + view.configure(with: element) + return view + } + myView.configure(with: element) + return myView + } + .disposed(by: disposeBag) + + */ + + public func items + (_ source: Source) + -> (_ viewForRow: @escaping (Int, Sequence.Element, UIView?) -> UIView) + -> Disposable where Source.Element == Sequence { + return { viewForRow in + let adapter = RxPickerViewAdapter(viewForRow: viewForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows using a custom reactive adapter used to perform the transformation. + This method will retain the adapter for as long as the subscription isn't disposed (result `Disposable` + being disposed). + In case `source` observable sequence terminates successfully, the adapter will present latest element + until the subscription isn't disposed. + + - parameter adapter: Adapter used to transform elements to picker components. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + */ + public func items(adapter: Adapter) + -> (_ source: Source) + -> Disposable where Source.Element == Adapter.Element { + return { source in + let delegateSubscription = self.setDelegate(adapter) + let dataSourceSubscription = source.subscribeProxyDataSource(ofObject: self.base, dataSource: adapter, retainDataSource: true, binding: { [weak pickerView = self.base] (_: RxPickerViewDataSourceProxy, event) in + guard let pickerView = pickerView else { return } + adapter.pickerView(pickerView, observedEvent: event) + }) + return Disposables.create(delegateSubscription, dataSourceSubscription) + } + } + + /** + Synchronous helper method for retrieving a model at indexPath through a reactive data source. + */ + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods was used.") + + return castOrFatalError(try dataSource.model(at: indexPath)) + } + } + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift new file mode 100644 index 00000000..cdb10be1 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift @@ -0,0 +1,28 @@ +// +// UIRefreshControl+Rx.swift +// RxCocoa +// +// Created by Yosuke Ishikawa on 1/31/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIRefreshControl { + /// Bindable sink for `beginRefreshing()`, `endRefreshing()` methods. + public var isRefreshing: Binder { + return Binder(self.base) { refreshControl, refresh in + if refresh { + refreshControl.beginRefreshing() + } else { + refreshControl.endRefreshing() + } + } + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift new file mode 100644 index 00000000..f90e1c26 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift @@ -0,0 +1,131 @@ +// +// UIScrollView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UIScrollView { + public typealias EndZoomEvent = (view: UIView?, scale: CGFloat) + public typealias WillEndDraggingEvent = (velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxScrollViewDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `contentOffset`. + public var contentOffset: ControlProperty { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + + let bindingObserver = Binder(self.base) { scrollView, contentOffset in + scrollView.contentOffset = contentOffset + } + + return ControlProperty(values: proxy.contentOffsetBehaviorSubject, valueSink: bindingObserver) + } + + /// Reactive wrapper for delegate method `scrollViewDidScroll` + public var didScroll: ControlEvent { + let source = RxScrollViewDelegateProxy.proxy(for: base).contentOffsetPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginDecelerating` + public var willBeginDecelerating: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDecelerating(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndDecelerating` + public var didEndDecelerating: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDecelerating(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginDragging` + public var willBeginDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)` + public var willEndDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillEndDragging(_:withVelocity:targetContentOffset:))) + .map { value -> WillEndDraggingEvent in + let velocity = try castOrThrow(CGPoint.self, value[1]) + let targetContentOffsetValue = try castOrThrow(NSValue.self, value[2]) + + guard let rawPointer = targetContentOffsetValue.pointerValue else { throw RxCocoaError.unknown } + let typedPointer = rawPointer.bindMemory(to: CGPoint.self, capacity: MemoryLayout.size) + + return (velocity, typedPointer) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndDragging(_:willDecelerate:)` + public var didEndDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDragging(_:willDecelerate:))).map { value -> Bool in + return try castOrThrow(Bool.self, value[1]) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidZoom` + public var didZoom: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidZoom)).map { _ in } + return ControlEvent(events: source) + } + + + /// Reactive wrapper for delegate method `scrollViewDidScrollToTop` + public var didScrollToTop: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidScrollToTop(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndScrollingAnimation` + public var didEndScrollingAnimation: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginZooming(_:with:)` + public var willBeginZooming: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginZooming(_:with:))).map { value -> UIView? in + return try castOptionalOrThrow(UIView.self, value[1] as AnyObject) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndZooming(_:with:atScale:)` + public var didEndZooming: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndZooming(_:with:atScale:))).map { value -> EndZoomEvent in + return (try castOptionalOrThrow(UIView.self, value[1] as AnyObject), try castOrThrow(CGFloat.self, value[2])) + } + return ControlEvent(events: source) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UIScrollViewDelegate) + -> Disposable { + return RxScrollViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } + } + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift new file mode 100644 index 00000000..3892b1ca --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift @@ -0,0 +1,136 @@ +// +// UISearchBar+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UISearchBar { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxSearchBarDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + let source: Observable = Observable.deferred { [weak searchBar = self.base as UISearchBar] () -> Observable in + let text = searchBar?.text + + let textDidChange = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty()) + let didEndEditing = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) ?? Observable.empty()) + + return Observable.merge(textDidChange, didEndEditing) + .map { _ in searchBar?.text ?? "" } + .startWith(text) + } + + let bindingObserver = Binder(self.base) { (searchBar, text: String?) in + searchBar.text = text + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// Reactive wrapper for `selectedScopeButtonIndex` property. + public var selectedScopeButtonIndex: ControlProperty { + let source: Observable = Observable.deferred { [weak source = self.base as UISearchBar] () -> Observable in + let index = source?.selectedScopeButtonIndex ?? 0 + + return (source?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty()) + .map { a in + return try castOrThrow(Int.self, a[1]) + } + .startWith(index) + } + + let bindingObserver = Binder(self.base) { (searchBar, index: Int) in + searchBar.selectedScopeButtonIndex = index + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + +#if os(iOS) + /// Reactive wrapper for delegate method `searchBarCancelButtonClicked`. + public var cancelButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarCancelButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarBookmarkButtonClicked`. + public var bookmarkButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarBookmarkButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarResultsListButtonClicked`. + public var resultsListButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarResultsListButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } +#endif + + /// Reactive wrapper for delegate method `searchBarSearchButtonClicked`. + public var searchButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarSearchButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarTextDidBeginEditing`. + public var textDidBeginEditing: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidBeginEditing(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarTextDidEndEditing`. + public var textDidEndEditing: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UISearchBarDelegate) + -> Disposable { + RxSearchBarDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift new file mode 100644 index 00000000..4f524a51 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift @@ -0,0 +1,58 @@ +// +// UISearchController+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 3/17/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UISearchController { + /// Reactive wrapper for `delegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxSearchControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message. + public var didDismiss: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.didDismissSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var didPresent: Observable { + return delegate + .methodInvoked(#selector(UISearchControllerDelegate.didPresentSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var present: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.presentSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var willDismiss: Observable { + return delegate + .methodInvoked(#selector(UISearchControllerDelegate.willDismissSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var willPresent: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.willPresentSearchController(_:))) + .map { _ in } + } + + } + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift new file mode 100644 index 00000000..1a626626 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift @@ -0,0 +1,54 @@ +// +// UISegmentedControl+Rx.swift +// RxCocoa +// +// Created by Carlos García on 8/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UISegmentedControl { + /// Reactive wrapper for `selectedSegmentIndex` property. + public var selectedSegmentIndex: ControlProperty { + value + } + + /// Reactive wrapper for `selectedSegmentIndex` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { segmentedControl in + segmentedControl.selectedSegmentIndex + }, setter: { segmentedControl, value in + segmentedControl.selectedSegmentIndex = value + } + ) + } + + /// Reactive wrapper for `setEnabled(_:forSegmentAt:)` + public func enabledForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, segmentEnabled -> Void in + segmentedControl.setEnabled(segmentEnabled, forSegmentAt: index) + } + } + + /// Reactive wrapper for `setTitle(_:forSegmentAt:)` + public func titleForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, title -> Void in + segmentedControl.setTitle(title, forSegmentAt: index) + } + } + + /// Reactive wrapper for `setImage(_:forSegmentAt:)` + public func imageForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, image -> Void in + segmentedControl.setImage(image, forSegmentAt: index) + } + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift new file mode 100644 index 00000000..07d4adb5 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift @@ -0,0 +1,29 @@ +// +// UISlider+Rx.swift +// RxCocoa +// +// Created by Alexander van der Werff on 28/05/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UISlider { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { slider in + slider.value + }, setter: { slider, value in + slider.value = value + } + ) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift new file mode 100644 index 00000000..29f63860 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift @@ -0,0 +1,29 @@ +// +// UIStepper+Rx.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 9/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIStepper { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { stepper in + stepper.value + }, setter: { stepper, value in + stepper.value = value + } + ) + } +} + +#endif + diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift new file mode 100644 index 00000000..6e116b39 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift @@ -0,0 +1,38 @@ +// +// UISwitch+Rx.swift +// RxCocoa +// +// Created by Carlos García on 8/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UISwitch { + + /// Reactive wrapper for `isOn` property. + public var isOn: ControlProperty { + value + } + + /// Reactive wrapper for `isOn` property. + /// + /// ⚠️ Versions prior to iOS 10.2 were leaking `UISwitch`'s, so on those versions + /// underlying observable sequence won't complete when nothing holds a strong reference + /// to `UISwitch`. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { uiSwitch in + uiSwitch.isOn + }, setter: { uiSwitch, value in + uiSwitch.isOn = value + } + ) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift new file mode 100644 index 00000000..e9896672 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift @@ -0,0 +1,92 @@ +// +// UITabBar+Rx.swift +// RxCocoa +// +// Created by Jesse Farless on 5/13/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/** + iOS only + */ +#if os(iOS) +extension Reactive where Base: UITabBar { + + /// Reactive wrapper for `delegate` message `tabBar(_:willBeginCustomizing:)`. + public var willBeginCustomizing: ControlEvent<[UITabBarItem]> { + + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willBeginCustomizing:))) + .map { a in + return try castOrThrow([UITabBarItem].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didBeginCustomizing:)`. + public var didBeginCustomizing: ControlEvent<[UITabBarItem]> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didBeginCustomizing:))) + .map { a in + return try castOrThrow([UITabBarItem].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:willEndCustomizing:changed:)`. + public var willEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willEndCustomizing:changed:))) + .map { (a: [Any]) -> (([UITabBarItem], Bool)) in + let items = try castOrThrow([UITabBarItem].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (items, changed) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didEndCustomizing:changed:)`. + public var didEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didEndCustomizing:changed:))) + .map { (a: [Any]) -> (([UITabBarItem], Bool)) in + let items = try castOrThrow([UITabBarItem].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (items, changed) + } + + return ControlEvent(events: source) + } + +} +#endif + +/** + iOS and tvOS + */ + +extension Reactive where Base: UITabBar { + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTabBarDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didSelect:)`. + public var didSelectItem: ControlEvent { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didSelect:))) + .map { a in + return try castOrThrow(UITabBarItem.self, a[1]) + } + + return ControlEvent(events: source) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift new file mode 100644 index 00000000..4b48e8e5 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift @@ -0,0 +1,79 @@ +// +// UITabBarController+Rx.swift +// RxCocoa +// +// Created by Yusuke Kita on 2016/12/07. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/** + iOS only + */ +#if os(iOS) +extension Reactive where Base: UITabBarController { + + /// Reactive wrapper for `delegate` message `tabBarController:willBeginCustomizing:`. + public var willBeginCustomizing: ControlEvent<[UIViewController]> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willBeginCustomizing:))) + .map { a in + return try castOrThrow([UIViewController].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBarController:willEndCustomizing:changed:`. + public var willEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willEndCustomizing:changed:))) + .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in + let viewControllers = try castOrThrow([UIViewController].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (viewControllers, changed) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBarController:didEndCustomizing:changed:`. + public var didEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didEndCustomizing:changed:))) + .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in + let viewControllers = try castOrThrow([UIViewController].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (viewControllers, changed) + } + + return ControlEvent(events: source) + } +} +#endif + +/** + iOS and tvOS + */ + + extension Reactive where Base: UITabBarController { + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTabBarControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message `tabBarController:didSelect:`. + public var didSelect: ControlEvent { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didSelect:))) + .map { a in + return try castOrThrow(UIViewController.self, a[1]) + } + + return ControlEvent(events: source) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift new file mode 100644 index 00000000..f30197d6 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift @@ -0,0 +1,429 @@ +// +// UITableView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +// Items + +extension Reactive where Base: UITableView { + + /** + Binds sequences of elements to table view rows. + + - parameter source: Observable sequence of items. + - parameter cellFactory: Transform between sequence elements and view cells. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: tableView.rx.items) { (tableView, row, element) in + let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! + cell.textLabel?.text = "\(element) @ row \(row)" + return cell + } + .disposed(by: disposeBag) + + */ + public func items + (_ source: Source) + -> (_ cellFactory: @escaping (UITableView, Int, Sequence.Element) -> UITableViewCell) + -> Disposable + where Source.Element == Sequence { + return { cellFactory in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + return self.items(dataSource: dataSource)(source) + } + } + + /** + Binds sequences of elements to table view rows. + + - parameter cellIdentifier: Identifier used to dequeue cells. + - parameter source: Observable sequence of items. + - parameter configureCell: Transform between sequence elements and view cells. + - parameter cellType: Type of table view cell. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in + cell.textLabel?.text = "\(element) @ row \(row)" + } + .disposed(by: disposeBag) + */ + public func items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (_ source: Source) + -> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void) + -> Disposable + where Source.Element == Sequence { + return { source in + return { configureCell in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper { tv, i, item in + let indexPath = IndexPath(item: i, section: 0) + let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell + configureCell(i, item, cell) + return cell + } + return self.items(dataSource: dataSource)(source) + } + } + } + + + /** + Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation. + This method will retain the data source for as long as the subscription isn't disposed (result `Disposable` + being disposed). + In case `source` observable sequence terminates successfully, the data source will present latest element + until the subscription isn't disposed. + + - parameter dataSource: Data source used to transform elements to view cells. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + */ + public func items< + DataSource: RxTableViewDataSourceType & UITableViewDataSource, + Source: ObservableType> + (dataSource: DataSource) + -> (_ source: Source) + -> Disposable + where DataSource.Element == Source.Element { + return { source in + // This is called for side effects only, and to make sure delegate proxy is in place when + // data source is being bound. + // This is needed because theoretically the data source subscription itself might + // call `self.rx.delegate`. If that happens, it might cause weird side effects since + // setting data source will set delegate, and UITableView might get into a weird state. + // Therefore it's better to set delegate proxy first, just to be sure. + _ = self.delegate + // Strong reference is needed because data source is in use until result subscription is disposed + return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource as UITableViewDataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in + guard let tableView = tableView else { + return + } + dataSource.tableView(tableView, observedEvent: event) + } + } + } + +} + +extension Reactive where Base: UITableView { + /** + Reactive wrapper for `dataSource`. + + For more information take a look at `DelegateProxyType` protocol documentation. + */ + public var dataSource: DelegateProxy { + RxTableViewDataSourceProxy.proxy(for: base) + } + + /** + Installs data source as forwarding delegate on `rx.dataSource`. + Data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter dataSource: Data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setDataSource(_ dataSource: UITableViewDataSource) + -> Disposable { + RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) + } + + // events + + /** + Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. + */ + public var itemSelected: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. + */ + public var itemDeselected: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didHighlightRowAt:`. + */ + public var itemHighlighted: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didHighlightRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didUnhighlightRowAt:`. + */ + public var itemUnhighlighted: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUnhighlightRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`. + */ + public var itemAccessoryButtonTapped: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + */ + public var itemInserted: ControlEvent { + let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) + .filter { a in + return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert + } + .map { a in + return (try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + */ + public var itemDeleted: ControlEvent { + let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) + .filter { a in + return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete + } + .map { a in + return try castOrThrow(IndexPath.self, a[2]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`. + */ + public var itemMoved: ControlEvent { + let source: Observable = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:))) + .map { a in + return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`. + */ + public var willDisplayCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:))) + .map { a in + return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`. + */ + public var didEndDisplayingCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:))) + .map { a in + return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelSelected(MyModel.self) + .map { ... + ``` + */ + public func modelSelected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelDeselected(MyModel.self) + .map { ... + ``` + */ + public func modelDeselected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelDeleted(MyModel.self) + .map { ... + ``` + */ + public func modelDeleted(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemDeleted.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Synchronous helper method for retrieving a model at indexPath through a reactive data source. + */ + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.") + + let element = try dataSource.model(at: indexPath) + + return castOrFatalError(element) + } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension Reactive where Base: UITableView { + + /// Reactive wrapper for `prefetchDataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var prefetchDataSource: DelegateProxy { + RxTableViewDataSourcePrefetchingProxy.proxy(for: base) + } + + /** + Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. + Prefetch data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter prefetchDataSource: Prefetch data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setPrefetchDataSource(_ prefetchDataSource: UITableViewDataSourcePrefetching) + -> Disposable { + return RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `prefetchDataSource` message `tableView(_:prefetchRowsAt:)`. + public var prefetchRows: ControlEvent<[IndexPath]> { + let source = RxTableViewDataSourcePrefetchingProxy.proxy(for: base).prefetchRowsPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for `prefetchDataSource` message `tableView(_:cancelPrefetchingForRowsAt:)`. + public var cancelPrefetchingForRows: ControlEvent<[IndexPath]> { + let source = prefetchDataSource.methodInvoked(#selector(UITableViewDataSourcePrefetching.tableView(_:cancelPrefetchingForRowsAt:))) + .map { a in + return try castOrThrow(Array.self, a[1]) + } + + return ControlEvent(events: source) + } + +} +#endif + +#if os(tvOS) + + extension Reactive where Base: UITableView { + + /** + Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`. + */ + public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { + + let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:))) + .map { a -> (context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in + let context = try castOrThrow(UITableViewFocusUpdateContext.self, a[1]) + let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) + return (context: context, animationCoordinator: animationCoordinator) + } + + return ControlEvent(events: source) + } + } +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift new file mode 100644 index 00000000..46e0e488 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift @@ -0,0 +1,55 @@ +// +// UITextField+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UITextField { + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { textField in + textField.text + }, + setter: { textField, value in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textField.text != value { + textField.text = value + } + } + ) + } + + /// Bindable sink for `attributedText` property. + public var attributedText: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { textField in + textField.attributedText + }, + setter: { textField, value in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textField.attributedText != value { + textField.attributedText = value + } + } + ) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift new file mode 100644 index 00000000..3395d9b9 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift @@ -0,0 +1,125 @@ +// +// UITextView+Rx.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 7/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UITextView { + /// Reactive wrapper for `text` property + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + let source: Observable = Observable.deferred { [weak textView = self.base] in + let text = textView?.text + + let textChanged = textView?.textStorage + // This project uses text storage notifications because + // that's the only way to catch autocorrect changes + // in all cases. Other suggestions are welcome. + .rx.didProcessEditingRangeChangeInLength + // This observe on is here because text storage + // will emit event while process is not completely done, + // so rebinding a value will cause an exception to be thrown. + .observe(on:MainScheduler.asyncInstance) + .map { _ in + return textView?.textStorage.string + } + ?? Observable.empty() + + return textChanged + .startWith(text) + } + + let bindingObserver = Binder(self.base) { (textView, text: String?) in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textView.text != text { + textView.text = text + } + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + + /// Reactive wrapper for `attributedText` property. + public var attributedText: ControlProperty { + let source: Observable = Observable.deferred { [weak textView = self.base] in + let attributedText = textView?.attributedText + + let textChanged: Observable = textView?.textStorage + // This project uses text storage notifications because + // that's the only way to catch autocorrect changes + // in all cases. Other suggestions are welcome. + .rx.didProcessEditingRangeChangeInLength + // This observe on is here because attributedText storage + // will emit event while process is not completely done, + // so rebinding a value will cause an exception to be thrown. + .observe(on:MainScheduler.asyncInstance) + .map { _ in + return textView?.attributedText + } + ?? Observable.empty() + + return textChanged + .startWith(attributedText) + } + + let bindingObserver = Binder(self.base) { (textView, attributedText: NSAttributedString?) in + // This check is important because setting text value always clears control state + // including marked text selection which is important for proper input + // when IME input method is used. + if textView.attributedText != attributedText { + textView.attributedText = attributedText + } + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// Reactive wrapper for `delegate` message. + public var didBeginEditing: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidBeginEditing(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didEndEditing: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidEndEditing(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didChange: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChange(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didChangeSelection: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChangeSelection(_:))) + .map { _ in + return () + }) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift new file mode 100644 index 00000000..b3b4d847 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift @@ -0,0 +1,57 @@ +// +// WKWebView+Rx.swift +// RxCocoa +// +// Created by Giuseppe Lanza on 14/02/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(macOS) + +import RxSwift +import WebKit + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +extension Reactive where Base: WKWebView { + + /// Reactive wrapper for `navigationDelegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var navigationDelegate: DelegateProxy { + RxWKNavigationDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didCommit: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didCommit:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didStartLoad: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didStartProvisionalNavigation:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didFinishLoad: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFinish:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didFailLoad: Observable<(WKNavigation, Error)> { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFail:withError:))) + .map { a in + ( + try castOrThrow(WKNavigation.self, a[1]), + try castOrThrow(Error.self, a[2]) + ) + } + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift new file mode 100644 index 00000000..7c223618 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift @@ -0,0 +1,33 @@ +// +// NSButton+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import RxSwift +import Cocoa + +extension Reactive where Base: NSButton { + + /// Reactive wrapper for control event. + public var tap: ControlEvent { + self.controlEvent + } + + /// Reactive wrapper for `state` property`. + public var state: ControlProperty { + return self.base.rx.controlProperty( + getter: { control in + return control.state + }, setter: { (control: NSButton, state: NSControl.StateValue) in + control.state = state + } + ) + } +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift new file mode 100644 index 00000000..534f40ca --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift @@ -0,0 +1,87 @@ +// +// NSControl+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +private var rx_value_key: UInt8 = 0 +private var rx_control_events_key: UInt8 = 0 + +extension Reactive where Base: NSControl { + + /// Reactive wrapper for control event. + public var controlEvent: ControlEvent<()> { + MainScheduler.ensureRunningOnMainThread() + + let source = self.lazyInstanceObservable(&rx_control_events_key) { () -> Observable in + Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let observer = ControlTarget(control: control) { _ in + observer.on(.next(())) + } + + return observer + } + .take(until: self.deallocated) + .share() + } + + return ControlEvent(events: source) + } + + /// Creates a `ControlProperty` that is triggered by target/action pattern value updates. + /// + /// - parameter getter: Property value getter. + /// - parameter setter: Property value setter. + public func controlProperty( + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + MainScheduler.ensureRunningOnMainThread() + + let source = self.base.rx.lazyInstanceObservable(&rx_value_key) { () -> Observable<()> in + return Observable.create { [weak weakControl = self.base] (observer: AnyObserver<()>) in + guard let control = weakControl else { + observer.on(.completed) + return Disposables.create() + } + + observer.on(.next(())) + + let observer = ControlTarget(control: control) { _ in + if weakControl != nil { + observer.on(.next(())) + } + } + + return observer + } + .take(until: self.deallocated) + .share(replay: 1, scope: .whileConnected) + } + .flatMap { [weak base] _ -> Observable in + guard let control = base else { return Observable.empty() } + return Observable.just(getter(control)) + } + + let bindingObserver = Binder(self.base, binding: setter) + + return ControlProperty(values: source, valueSink: bindingObserver) + } +} + + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift new file mode 100644 index 00000000..2e5b19a8 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift @@ -0,0 +1,30 @@ +// +// NSSlider+Rx.swift +// RxCocoa +// +// Created by Junior B. on 24/05/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import RxSwift +import Cocoa + +extension Reactive where Base: NSSlider { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return self.base.rx.controlProperty( + getter: { control -> Double in + return control.doubleValue + }, + setter: { control, value in + control.doubleValue = value + } + ) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift new file mode 100644 index 00000000..ce69f9e9 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift @@ -0,0 +1,87 @@ +// +// NSTextField+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +/// Delegate proxy for `NSTextField`. +/// +/// For more information take a look at `DelegateProxyType`. +open class RxTextFieldDelegateProxy + : DelegateProxy + , DelegateProxyType + , NSTextFieldDelegate { + + /// Typed parent object. + public weak private(set) var textField: NSTextField? + + /// Initializes `RxTextFieldDelegateProxy` + /// + /// - parameter textField: Parent object for delegate proxy. + init(textField: NSTextField) { + self.textField = textField + super.init(parentObject: textField, delegateProxy: RxTextFieldDelegateProxy.self) + } + + public static func registerKnownImplementations() { + self.register { RxTextFieldDelegateProxy(textField: $0) } + } + + fileprivate let textSubject = PublishSubject() + + // MARK: Delegate methods + open func controlTextDidChange(_ notification: Notification) { + let textField: NSTextField = castOrFatalError(notification.object) + let nextValue = textField.stringValue + self.textSubject.on(.next(nextValue)) + _forwardToDelegate?.controlTextDidChange?(notification) + } + + // MARK: Delegate proxy methods + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> NSTextFieldDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: NSTextFieldDelegate?, to object: ParentObject) { + object.delegate = delegate + } + +} + +extension Reactive where Base: NSTextField { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTextFieldDelegateProxy.proxy(for: self.base) + } + + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + let delegate = RxTextFieldDelegateProxy.proxy(for: self.base) + + let source = Observable.deferred { [weak textField = self.base] in + delegate.textSubject.startWith(textField?.stringValue) + }.take(until: self.deallocated) + + let observer = Binder(self.base) { (control, value: String?) in + control.stringValue = value ?? "" + } + + return ControlProperty(values: source, valueSink: observer.asObserver()) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift new file mode 100644 index 00000000..c3134e4f --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift @@ -0,0 +1,94 @@ +// +// NSTextView+Rx.swift +// RxCocoa +// +// Created by Cee on 8/5/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +/// Delegate proxy for `NSTextView`. +/// +/// For more information take a look at `DelegateProxyType`. +open class RxTextViewDelegateProxy: DelegateProxy, DelegateProxyType, NSTextViewDelegate { + + #if compiler(>=5.2) + /// Typed parent object. + /// + /// - note: Since Swift 5.2 and Xcode 11.4, Apple have suddenly + /// disallowed using `weak` for NSTextView. For more details + /// see this GitHub Issue: https://git.io/JvSRn + public private(set) var textView: NSTextView? + #else + /// Typed parent object. + public weak private(set) var textView: NSTextView? + #endif + + /// Initializes `RxTextViewDelegateProxy` + /// + /// - parameter textView: Parent object for delegate proxy. + init(textView: NSTextView) { + self.textView = textView + super.init(parentObject: textView, delegateProxy: RxTextViewDelegateProxy.self) + } + + public static func registerKnownImplementations() { + self.register { RxTextViewDelegateProxy(textView: $0) } + } + + fileprivate let textSubject = PublishSubject() + + // MARK: Delegate methods + + open func textDidChange(_ notification: Notification) { + let textView: NSTextView = castOrFatalError(notification.object) + let nextValue = textView.string + self.textSubject.on(.next(nextValue)) + self._forwardToDelegate?.textDidChange?(notification) + } + + // MARK: Delegate proxy methods + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> NSTextViewDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: NSTextViewDelegate?, to object: ParentObject) { + object.delegate = delegate + } + +} + +extension Reactive where Base: NSTextView { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTextViewDelegateProxy.proxy(for: self.base) + } + + /// Reactive wrapper for `string` property. + public var string: ControlProperty { + let delegate = RxTextViewDelegateProxy.proxy(for: self.base) + + let source = Observable.deferred { [weak textView = self.base] in + delegate.textSubject.startWith(textView?.string ?? "") + }.take(until: self.deallocated) + + let observer = Binder(self.base) { control, value in + control.string = value + } + + return ControlProperty(values: source, valueSink: observer.asObserver()) + } + +} + +#endif diff --git a/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift new file mode 100644 index 00000000..f4256d11 --- /dev/null +++ b/ChatBot/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift @@ -0,0 +1,21 @@ +// +// NSView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 12/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + import Cocoa + import RxSwift + + extension Reactive where Base: NSView { + /// Bindable sink for `alphaValue` property. + public var alpha: Binder { + return Binder(self.base) { view, value in + view.alphaValue = value + } + } + } +#endif diff --git a/ChatBot/Pods/RxRelay/LICENSE.md b/ChatBot/Pods/RxRelay/LICENSE.md new file mode 100644 index 00000000..e32511b3 --- /dev/null +++ b/ChatBot/Pods/RxRelay/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ChatBot/Pods/RxRelay/README.md b/ChatBot/Pods/RxRelay/README.md new file mode 100644 index 00000000..a95d9e0c --- /dev/null +++ b/ChatBot/Pods/RxRelay/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+
Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.5.0' + pod 'RxCocoa', '6.5.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.5.0' + pod 'RxTest', '6.5.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.5.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.5.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/ChatBot/Pods/RxRelay/RxRelay/BehaviorRelay.swift b/ChatBot/Pods/RxRelay/RxRelay/BehaviorRelay.swift new file mode 100644 index 00000000..e02fc8f5 --- /dev/null +++ b/ChatBot/Pods/RxRelay/RxRelay/BehaviorRelay.swift @@ -0,0 +1,42 @@ +// +// BehaviorRelay.swift +// RxRelay +// +// Created by Krunoslav Zaher on 10/7/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// BehaviorRelay is a wrapper for `BehaviorSubject`. +/// +/// Unlike `BehaviorSubject` it can't terminate with error or completed. +public final class BehaviorRelay: ObservableType { + private let subject: BehaviorSubject + + /// Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + /// Current value of behavior subject + public var value: Element { + // this try! is ok because subject can't error out or be disposed + return try! self.subject.value() + } + + /// Initializes behavior relay with initial value. + public init(value: Element) { + self.subject = BehaviorSubject(value: value) + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObservable() + } +} diff --git a/ChatBot/Pods/RxRelay/RxRelay/Observable+Bind.swift b/ChatBot/Pods/RxRelay/RxRelay/Observable+Bind.swift new file mode 100644 index 00000000..08c4a971 --- /dev/null +++ b/ChatBot/Pods/RxRelay/RxRelay/Observable+Bind.swift @@ -0,0 +1,149 @@ +// +// Observable+Bind.swift +// RxRelay +// +// Created by Shai Mishali on 09/04/2019. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableType { + /** + Creates new subscription and sends elements to publish relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + bind(to: relays) + } + + /** + Creates new subscription and sends elements to publish relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter relays: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to publish relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [PublishRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to publish relay: \(error)") + case .completed: + break + } + } + } + + /** + Creates new subscription and sends elements to behavior relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + self.bind(to: relays) + } + + /** + Creates new subscription and sends elements to behavior relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter relays: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to behavior relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [BehaviorRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to behavior relay: \(error)") + case .completed: + break + } + } + } + + /** + Creates new subscription and sends elements to replay relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + self.bind(to: relays) + } + + /** + Creates new subscription and sends elements to replay relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter relays: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to replay relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter relays: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [ReplayRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to behavior relay: \(error)") + case .completed: + break + } + } + } +} diff --git a/ChatBot/Pods/RxRelay/RxRelay/PublishRelay.swift b/ChatBot/Pods/RxRelay/RxRelay/PublishRelay.swift new file mode 100644 index 00000000..a9c8ac42 --- /dev/null +++ b/ChatBot/Pods/RxRelay/RxRelay/PublishRelay.swift @@ -0,0 +1,36 @@ +// +// PublishRelay.swift +// RxRelay +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// PublishRelay is a wrapper for `PublishSubject`. +/// +/// Unlike `PublishSubject` it can't terminate with error or completed. +public final class PublishRelay: ObservableType { + private let subject: PublishSubject + + // Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + /// Initializes with internal empty subject. + public init() { + self.subject = PublishSubject() + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObservable() + } +} diff --git a/ChatBot/Pods/RxRelay/RxRelay/ReplayRelay.swift b/ChatBot/Pods/RxRelay/RxRelay/ReplayRelay.swift new file mode 100644 index 00000000..3cc87cd0 --- /dev/null +++ b/ChatBot/Pods/RxRelay/RxRelay/ReplayRelay.swift @@ -0,0 +1,50 @@ +// +// ReplayRelay.swift +// RxRelay +// +// Created by Zsolt Kovacs on 12/22/19. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// ReplayRelay is a wrapper for `ReplaySubject`. +/// +/// Unlike `ReplaySubject` it can't terminate with an error or complete. +public final class ReplayRelay: ObservableType { + private let subject: ReplaySubject + + // Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + private init(subject: ReplaySubject) { + self.subject = subject + } + + /// Creates new instance of `ReplayRelay` that replays at most `bufferSize` last elements sent to it. + /// + /// - parameter bufferSize: Maximal number of elements to replay to observers after subscription. + /// - returns: New instance of replay relay. + public static func create(bufferSize: Int) -> ReplayRelay { + ReplayRelay(subject: ReplaySubject.create(bufferSize: bufferSize)) + } + + /// Creates a new instance of `ReplayRelay` that buffers all the sent to it. + /// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable' + /// number of elements. + public static func createUnbound() -> ReplayRelay { + ReplayRelay(subject: ReplaySubject.createUnbounded()) + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObserver() + } +} diff --git a/ChatBot/Pods/RxRelay/RxRelay/Utils.swift b/ChatBot/Pods/RxRelay/RxRelay/Utils.swift new file mode 100644 index 00000000..5954fb98 --- /dev/null +++ b/ChatBot/Pods/RxRelay/RxRelay/Utils.swift @@ -0,0 +1,17 @@ +// +// Utils.swift +// RxRelay +// +// Created by Shai Mishali on 09/04/2019. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} diff --git a/ChatBot/Pods/RxSwift/LICENSE.md b/ChatBot/Pods/RxSwift/LICENSE.md new file mode 100644 index 00000000..e32511b3 --- /dev/null +++ b/ChatBot/Pods/RxSwift/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/ChatBot/Pods/RxSwift/Platform/AtomicInt.swift b/ChatBot/Pods/RxSwift/Platform/AtomicInt.swift new file mode 100644 index 00000000..98479fd2 --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/AtomicInt.swift @@ -0,0 +1,71 @@ +// +// AtomicInt.swift +// Platform +// +// Created by Krunoslav Zaher on 10/28/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +final class AtomicInt: NSLock { + fileprivate var value: Int32 + public init(_ value: Int32 = 0) { + self.value = value + } +} + +@discardableResult +@inline(__always) +func add(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value += value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func sub(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value -= value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func fetchOr(_ this: AtomicInt, _ mask: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value |= mask + this.unlock() + return oldValue +} + +@inline(__always) +func load(_ this: AtomicInt) -> Int32 { + this.lock() + let oldValue = this.value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func increment(_ this: AtomicInt) -> Int32 { + add(this, 1) +} + +@discardableResult +@inline(__always) +func decrement(_ this: AtomicInt) -> Int32 { + sub(this, 1) +} + +@inline(__always) +func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool { + (load(this) & mask) != 0 +} diff --git a/ChatBot/Pods/RxSwift/Platform/DataStructures/Bag.swift b/ChatBot/Pods/RxSwift/Platform/DataStructures/Bag.swift new file mode 100644 index 00000000..5720a3b4 --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/DataStructures/Bag.swift @@ -0,0 +1,181 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + private var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + lhs.rawValue == rhs.rawValue +} diff --git a/ChatBot/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/ChatBot/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 00000000..75d7bea7 --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,23 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Iterator = AnyIterator + + private let repeatedValue: Element + + init(repeatedValue: Element) { + self.repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = self.repeatedValue + return AnyIterator { repeatedValue } + } +} diff --git a/ChatBot/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift b/ChatBot/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 00000000..9ed856b9 --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let hasHigherPriority: (Element, Element) -> Bool + private let isEqual: (Element, Element) -> Bool + + private var elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + self.hasHigherPriority = hasHigherPriority + self.isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + elements.append(element) + bubbleToHigherPriority(elements.count - 1) + } + + func peek() -> Element? { + elements.first + } + + var isEmpty: Bool { + elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< elements.count { + if self.isEqual(elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == elements.count - 1 + if !removingLast { + elements.swapAt(index, elements.count - 1) + } + + _ = elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard self.hasHigherPriority(elements[unbalancedIndex], elements[parentIndex]) else { break } + elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < elements.count && self.hasHigherPriority(elements[leftChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < elements.count && self.hasHigherPriority(elements[rightChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + elements.debugDescription + } +} diff --git a/ChatBot/Pods/RxSwift/Platform/DataStructures/Queue.swift b/ChatBot/Pods/RxSwift/Platform/DataStructures/Queue.swift new file mode 100644 index 00000000..625d4733 --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/DataStructures/Queue.swift @@ -0,0 +1,148 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let resizeFactor = 2 + + private var storage: ContiguousArray + private var innerCount = 0 + private var pushNextIndex = 0 + private let initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + initialCapacity = capacity + + storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = pushNextIndex - count + return index < 0 ? index + storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { count == 0 } + + /// - returns: Number of elements inside queue. + var count: Int { innerCount } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = self.count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = storage[0 ..< numberOfElementsInSecondBatch] + + self.innerCount = count + pushNextIndex = count + storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == storage.count { + resizeTo(Swift.max(storage.count, 1) * resizeFactor) + } + + storage[pushNextIndex] = element + pushNextIndex += 1 + innerCount += 1 + + if pushNextIndex >= storage.count { + pushNextIndex -= storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + storage[index] = nil + innerCount -= 1 + } + + return storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = storage.count / (resizeFactor * resizeFactor) + if count < downsizeLimit && downsizeLimit >= initialCapacity { + resizeTo(storage.count / resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var innerCount = count + + return AnyIterator { + if innerCount == 0 { + return nil + } + + defer { + innerCount -= 1 + i += 1 + } + + if i >= self.storage.count { + i -= self.storage.count + } + + return self.storage[i] + } + } +} diff --git a/ChatBot/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift b/ChatBot/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 00000000..aaf24cae --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/ChatBot/Pods/RxSwift/Platform/Platform.Darwin.swift b/ChatBot/Pods/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 00000000..eacc1943 --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,35 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/ChatBot/Pods/RxSwift/Platform/Platform.Linux.swift b/ChatBot/Pods/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 00000000..52a3e3af --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,32 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import Foundation + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + if let newValue = value { + Thread.current.threadDictionary[key] = newValue + } + else { + Thread.current.threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/ChatBot/Pods/RxSwift/Platform/RecursiveLock.swift b/ChatBot/Pods/RxSwift/Platform/RecursiveLock.swift new file mode 100644 index 00000000..10b9bbb0 --- /dev/null +++ b/ChatBot/Pods/RxSwift/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/ChatBot/Pods/RxSwift/README.md b/ChatBot/Pods/RxSwift/README.md new file mode 100644 index 00000000..a95d9e0c --- /dev/null +++ b/ChatBot/Pods/RxSwift/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.5.0' + pod 'RxCocoa', '6.5.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.5.0' + pod 'RxTest', '6.5.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.5.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.5.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/ChatBot/Pods/RxSwift/RxSwift/AnyObserver.swift b/ChatBot/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 00000000..e92cc816 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/AnyObserver.swift @@ -0,0 +1,69 @@ +// +// AnyObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObserverType`. +/// +/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type. +public struct AnyObserver : ObserverType { + /// Anonymous event handler type. + public typealias EventHandler = (Event) -> Void + + private let observer: EventHandler + + /// Construct an instance whose `on(event)` calls `eventHandler(event)` + /// + /// - parameter eventHandler: Event handler that observes sequences events. + public init(eventHandler: @escaping EventHandler) { + self.observer = eventHandler + } + + /// Construct an instance whose `on(event)` calls `observer.on(event)` + /// + /// - parameter observer: Observer that receives sequence events. + public init(_ observer: Observer) where Observer.Element == Element { + self.observer = observer.on + } + + /// Send `event` to this observer. + /// + /// - parameter event: Event instance. + public func on(_ event: Event) { + self.observer(event) + } + + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + self + } +} + +extension AnyObserver { + /// Collection of `AnyObserver`s + typealias s = Bag<(Event) -> Void> +} + +extension ObserverType { + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(self) + } + + /// Transforms observer of type R to type E using custom transform method. + /// Each event sent to result observer is transformed and sent to `self`. + /// + /// - returns: observer that transforms events. + public func mapObserver(_ transform: @escaping (Result) throws -> Element) -> AnyObserver { + AnyObserver { e in + self.on(e.map(transform)) + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Binder.swift b/ChatBot/Pods/RxSwift/RxSwift/Binder.swift new file mode 100644 index 00000000..1aae0959 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Binder.swift @@ -0,0 +1,59 @@ +// +// Binder.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/** + Observer that enforces interface binding rules: + * can't bind errors (in debug builds binding of errors causes `fatalError` in release builds errors are being logged) + * ensures binding is performed on a specific scheduler + + `Binder` doesn't retain target and in case target is released, element isn't bound. + + By default it binds elements on main scheduler. + */ +public struct Binder: ObserverType { + public typealias Element = Value + + private let binding: (Event) -> Void + + /// Initializes `Binder` + /// + /// - parameter target: Target object. + /// - parameter scheduler: Scheduler used to bind the events. + /// - parameter binding: Binding logic. + public init(_ target: Target, scheduler: ImmediateSchedulerType = MainScheduler(), binding: @escaping (Target, Value) -> Void) { + weak var weakTarget = target + + self.binding = { event in + switch event { + case .next(let element): + _ = scheduler.schedule(element) { element in + if let target = weakTarget { + binding(target, element) + } + return Disposables.create() + } + case .error(let error): + rxFatalErrorInDebug("Binding error: \(error)") + case .completed: + break + } + } + } + + /// Binds next element to owner view as described in `binding`. + public func on(_ event: Event) { + self.binding(event) + } + + /// Erases type of observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(eventHandler: self.on) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Cancelable.swift b/ChatBot/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 00000000..1fa7a677 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Cancelable.swift @@ -0,0 +1,13 @@ +// +// Cancelable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents disposable resource with state tracking. +public protocol Cancelable : Disposable { + /// Was resource disposed. + var isDisposed: Bool { get } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 00000000..502597e9 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,100 @@ +// +// AsyncLock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +In case nobody holds this lock, the work will be queued and executed immediately +on thread that is requesting lock. + +In case there is somebody currently holding that lock, action will be enqueued. +When owned of the lock finishes with it's processing, it will also execute +and pending work. + +That means that enqueued work could possibly be executed later on a different thread. +*/ +final class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + private var _lock = SpinLock() + + private var queue: Queue = Queue(capacity: 0) + + private var isExecuting: Bool = false + private var hasFaulted: Bool = false + + // lock { + func lock() { + self._lock.lock() + } + + func unlock() { + self._lock.unlock() + } + // } + + private func enqueue(_ action: I) -> I? { + self.lock(); defer { self.unlock() } + if self.hasFaulted { + return nil + } + + if self.isExecuting { + self.queue.enqueue(action) + return nil + } + + self.isExecuting = true + + return action + } + + private func dequeue() -> I? { + self.lock(); defer { self.unlock() } + if !self.queue.isEmpty { + return self.queue.dequeue() + } + else { + self.isExecuting = false + return nil + } + } + + func invoke(_ action: I) { + let firstEnqueuedAction = self.enqueue(action) + + if let firstEnqueuedAction = firstEnqueuedAction { + firstEnqueuedAction.invoke() + } + else { + // action is enqueued, it's somebody else's concern now + return + } + + while true { + let nextAction = self.dequeue() + + if let nextAction = nextAction { + nextAction.invoke() + } + else { + return + } + } + } + + func dispose() { + self.synchronizedDispose() + } + + func synchronized_dispose() { + self.queue = Queue(capacity: 0) + self.hasFaulted = true + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 00000000..7232f23f --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,23 @@ +// +// Lock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol Lock { + func lock() + func unlock() +} + +// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html +typealias SpinLock = RecursiveLock + +extension RecursiveLock : Lock { + @inline(__always) + final func performLocked(_ action: () -> T) -> T { + self.lock(); defer { self.unlock() } + return action() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 00000000..8a98007d --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,16 @@ +// +// LockOwnerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol LockOwnerType: AnyObject, Lock { + var lock: RecursiveLock { get } +} + +extension LockOwnerType { + func lock() { self.lock.lock() } + func unlock() { self.lock.unlock() } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 00000000..527a2fbe --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedDisposeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedDisposeType: AnyObject, Disposable, Lock { + func synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + self.lock(); defer { self.unlock() } + self.synchronized_dispose() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 00000000..19168d77 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedOnType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedOnType: AnyObject, ObserverType, Lock { + func synchronized_on(_ event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(_ event: Event) { + self.lock(); defer { self.unlock() } + self.synchronized_on(event) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 00000000..988b86f4 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,13 @@ +// +// SynchronizedUnsubscribeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedUnsubscribeType: AnyObject { + associatedtype DisposeKey + + func synchronizedUnsubscribe(_ disposeKey: DisposeKey) +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/ChatBot/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 00000000..52bf93c5 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,19 @@ +// +// ConnectableObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public protocol ConnectableObservableType : ObservableType { + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + func connect() -> Disposable +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Date+Dispatch.swift b/ChatBot/Pods/RxSwift/RxSwift/Date+Dispatch.swift new file mode 100644 index 00000000..90f70c56 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Date+Dispatch.swift @@ -0,0 +1,64 @@ +// +// Date+Dispatch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/14/19. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +extension DispatchTimeInterval { + var convertToSecondsFactor: Double { + switch self { + case .nanoseconds: return 1_000_000_000.0 + case .microseconds: return 1_000_000.0 + case .milliseconds: return 1_000.0 + case .seconds: return 1.0 + case .never: fatalError() + @unknown default: fatalError() + } + } + + func map(_ transform: (Int, Double) -> Int) -> DispatchTimeInterval { + switch self { + case .nanoseconds(let value): return .nanoseconds(transform(value, 1_000_000_000.0)) + case .microseconds(let value): return .microseconds(transform(value, 1_000_000.0)) + case .milliseconds(let value): return .milliseconds(transform(value, 1_000.0)) + case .seconds(let value): return .seconds(transform(value, 1.0)) + case .never: return .never + @unknown default: fatalError() + } + } + + var isNow: Bool { + switch self { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): return value == 0 + case .never: return false + @unknown default: fatalError() + } + } + + internal func reduceWithSpanBetween(earlierDate: Date, laterDate: Date) -> DispatchTimeInterval { + return self.map { value, factor in + let interval = laterDate.timeIntervalSince(earlierDate) + let remainder = Double(value) - interval * factor + guard remainder > 0 else { return 0 } + return Int(remainder.rounded(.toNearestOrAwayFromZero)) + } + } +} + +extension Date { + + internal func addingDispatchInterval(_ dispatchInterval: DispatchTimeInterval) -> Date { + switch dispatchInterval { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): + return self.addingTimeInterval(TimeInterval(value) / dispatchInterval.convertToSecondsFactor) + case .never: return Date.distantFuture + @unknown default: fatalError() + } + } + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 00000000..b79c77a7 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposable.swift @@ -0,0 +1,13 @@ +// +// Disposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 00000000..591aafa5 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,59 @@ +// +// AnonymousDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an Action-based disposable. +/// +/// When dispose method is called, disposal action will be dereferenced. +private final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private let disposed = AtomicInt(0) + private var disposeAction: DisposeAction? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + private init(_ disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + // Non-deprecated version of the constructor, used by `Disposables.create(with:)` + fileprivate init(disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + fileprivate func dispose() { + if fetchOr(self.disposed, 1) == 0 { + if let action = self.disposeAction { + self.disposeAction = nil + action() + } + } + } +} + +extension Disposables { + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter dispose: Disposal action which will be run upon calling `dispose`. + public static func create(with dispose: @escaping () -> Void) -> Cancelable { + AnonymousDisposable(disposeAction: dispose) + } + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 00000000..a3d49370 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,53 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents two disposable resources that are disposed together. +private final class BinaryDisposable : DisposeBase, Cancelable { + + private let disposed = AtomicInt(0) + + // state + private var disposable1: Disposable? + private var disposable2: Disposable? + + /// - returns: Was resource disposed. + var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs new binary disposable from two disposables. + /// + /// - parameter disposable1: First disposable + /// - parameter disposable2: Second disposable + init(_ disposable1: Disposable, _ disposable2: Disposable) { + self.disposable1 = disposable1 + self.disposable2 = disposable2 + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + func dispose() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable1?.dispose() + self.disposable2?.dispose() + self.disposable1 = nil + self.disposable2 = nil + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable) -> Cancelable { + BinaryDisposable(disposable1, disposable2) + } + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 00000000..c7d73e96 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,33 @@ +// +// BooleanDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that can be checked for disposal status. +public final class BooleanDisposable : Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(isDisposed: true) + private var disposed = false + + /// Initializes a new instance of the `BooleanDisposable` class + public init() { + } + + /// Initializes a new instance of the `BooleanDisposable` class with given value + public init(isDisposed: Bool) { + self.disposed = isDisposed + } + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.disposed + } + + /// Sets the status to disposed, which can be observer through the `isDisposed` property. + public func dispose() { + self.disposed = true + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 00000000..bb4efe6a --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,147 @@ +// +// CompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a group of disposable resources that are disposed together. +public final class CompositeDisposable : DisposeBase, Cancelable { + /// Key used to remove disposable from composite disposable + public struct DisposeKey { + fileprivate let key: BagKey + fileprivate init(key: BagKey) { + self.key = key + } + } + + private var lock = SpinLock() + + // state + private var disposables: Bag? = Bag() + + public var isDisposed: Bool { + self.lock.performLocked { self.disposables == nil } + } + + public override init() { + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + _ = self.disposables!.insert(disposable4) + + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(disposables: [Disposable]) { + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /** + Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + + - parameter disposable: Disposable to add. + - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already + disposed `nil` will be returned. + */ + public func insert(_ disposable: Disposable) -> DisposeKey? { + let key = self._insert(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _insert(_ disposable: Disposable) -> DisposeKey? { + self.lock.performLocked { + let bagKey = self.disposables?.insert(disposable) + return bagKey.map(DisposeKey.init) + } + } + + /// - returns: Gets the number of disposables contained in the `CompositeDisposable`. + public var count: Int { + self.lock.performLocked { self.disposables?.count ?? 0 } + } + + /// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. + /// + /// - parameter disposeKey: Key used to identify disposable to be removed. + public func remove(for disposeKey: DisposeKey) { + self._remove(for: disposeKey)?.dispose() + } + + private func _remove(for disposeKey: DisposeKey) -> Disposable? { + self.lock.performLocked { self.disposables?.removeKey(disposeKey.key) } + } + + /// Disposes all disposables in the group and removes them from the group. + public func dispose() { + if let disposables = self._dispose() { + disposeAll(in: disposables) + } + } + + private func _dispose() -> Bag? { + self.lock.performLocked { + let current = self.disposables + self.disposables = nil + return current + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { + CompositeDisposable(disposable1, disposable2, disposable3) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { + var disposables = disposables + disposables.append(disposable1) + disposables.append(disposable2) + disposables.append(disposable3) + return CompositeDisposable(disposables: disposables) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposables: [Disposable]) -> Cancelable { + switch disposables.count { + case 2: + return Disposables.create(disposables[0], disposables[1]) + default: + return CompositeDisposable(disposables: disposables) + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/Disposables.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/Disposables.swift new file mode 100644 index 00000000..8cd6e28c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/Disposables.swift @@ -0,0 +1,13 @@ +// +// Disposables.swift +// RxSwift +// +// Created by Mohsen Ramezanpoor on 01/08/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/// A collection of utility methods for common disposable operations. +public struct Disposables { + private init() {} +} + diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 00000000..1a673bcc --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,144 @@ +// +// DisposeBag.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Disposable { + /// Adds `self` to `bag` + /// + /// - parameter bag: `DisposeBag` to add `self` to. + public func disposed(by bag: DisposeBag) { + bag.insert(self) + } +} + +/** +Thread safe bag that disposes added disposables on `deinit`. + +This returns ARC (RAII) like resource management to `RxSwift`. + +In case contained disposables need to be disposed, just put a different dispose bag +or create a new one in its place. + + self.existingDisposeBag = DisposeBag() + +In case explicit disposal is necessary, there is also `CompositeDisposable`. +*/ +public final class DisposeBag: DisposeBase { + + private var lock = SpinLock() + + // state + private var disposables = [Disposable]() + private var isDisposed = false + + /// Constructs new empty dispose bag. + public override init() { + super.init() + } + + /// Adds `disposable` to be disposed when dispose bag is being deinited. + /// + /// - parameter disposable: Disposable to add. + public func insert(_ disposable: Disposable) { + self._insert(disposable)?.dispose() + } + + private func _insert(_ disposable: Disposable) -> Disposable? { + self.lock.performLocked { + if self.isDisposed { + return disposable + } + + self.disposables.append(disposable) + + return nil + } + } + + /// This is internal on purpose, take a look at `CompositeDisposable` instead. + private func dispose() { + let oldDisposables = self._dispose() + + for disposable in oldDisposables { + disposable.dispose() + } + } + + private func _dispose() -> [Disposable] { + self.lock.performLocked { + let disposables = self.disposables + + self.disposables.removeAll(keepingCapacity: false) + self.isDisposed = true + + return disposables + } + } + + deinit { + self.dispose() + } +} + +extension DisposeBag { + /// Convenience init allows a list of disposables to be gathered for disposal. + public convenience init(disposing disposables: Disposable...) { + self.init() + self.disposables += disposables + } + + /// Convenience init which utilizes a function builder to let you pass in a list of + /// disposables to make a DisposeBag of. + public convenience init(@DisposableBuilder builder: () -> [Disposable]) { + self.init(disposing: builder()) + } + + /// Convenience init allows an array of disposables to be gathered for disposal. + public convenience init(disposing disposables: [Disposable]) { + self.init() + self.disposables += disposables + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(_ disposables: Disposable...) { + self.insert(disposables) + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(@DisposableBuilder builder: () -> [Disposable]) { + self.insert(builder()) + } + + /// Convenience function allows an array of disposables to be gathered for disposal. + public func insert(_ disposables: [Disposable]) { + self.lock.performLocked { + if self.isDisposed { + disposables.forEach { $0.dispose() } + } else { + self.disposables += disposables + } + } + } + + /// A function builder accepting a list of Disposables and returning them as an array. + #if swift(>=5.4) + @resultBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #else + @_functionBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #endif + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 00000000..0d4b2fb7 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,22 @@ +// +// DisposeBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for all disposables. +public class DisposeBase { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 00000000..dd436ba9 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,30 @@ +// +// NopDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable that does nothing on disposal. +/// +/// Nop = No Operation +private struct NopDisposable : Disposable { + + fileprivate static let noOp: Disposable = NopDisposable() + + private init() { + + } + + /// Does nothing. + public func dispose() { + } +} + +extension Disposables { + /** + Creates a disposable that does nothing on disposal. + */ + static public func create() -> Disposable { NopDisposable.noOp } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 00000000..a59f7789 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,112 @@ +// +// RefCountDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. +public final class RefCountDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + private var disposable = nil as Disposable? + private var primaryDisposed = false + private var count = 0 + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.lock.performLocked { self.disposable == nil } + } + + /// Initializes a new instance of the `RefCountDisposable`. + public init(disposable: Disposable) { + self.disposable = disposable + super.init() + } + + /** + Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable. + + When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned. + */ + public func retain() -> Disposable { + self.lock.performLocked { + if self.disposable != nil { + do { + _ = try incrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return Disposables.create() + } + } + } + + /// Disposes the underlying disposable only when all dependent disposables have been disposed. + public func dispose() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable, !self.primaryDisposed { + self.primaryDisposed = true + + if self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + fileprivate func release() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable { + do { + _ = try decrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable decrement on release failed") + } + + guard self.count >= 0 else { + rxFatalError("RefCountDisposable counter is lower than 0") + } + + if self.primaryDisposed && self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } +} + +internal final class RefCountInnerDisposable: DisposeBase, Disposable +{ + private let parent: RefCountDisposable + private let isDisposed = AtomicInt(0) + + init(_ parent: RefCountDisposable) { + self.parent = parent + super.init() + } + + internal func dispose() + { + if fetchOr(self.isDisposed, 1) == 0 { + self.parent.release() + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 00000000..2cf997bc --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,50 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private let disposeScheduledDisposable: (ScheduledDisposable) -> Disposable = { sd in + sd.disposeInner() + return Disposables.create() +} + +/// Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +public final class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private let disposed = AtomicInt(0) + + // state + private var disposable: Disposable? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /** + Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`. + + - parameter scheduler: Scheduler where the disposable resource will be disposed on. + - parameter disposable: Disposable resource to dispose on the given scheduler. + */ + public init(scheduler: ImmediateSchedulerType, disposable: Disposable) { + self.scheduler = scheduler + self.disposable = disposable + } + + /// Disposes the wrapped disposable on the provided scheduler. + public func dispose() { + _ = self.scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable!.dispose() + self.disposable = nil + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 00000000..ef4690d3 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,73 @@ +// +// SerialDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. +public final class SerialDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + + // state + private var current = nil as Disposable? + private var disposed = false + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.disposed + } + + /// Initializes a new instance of the `SerialDisposable`. + override public init() { + super.init() + } + + /** + Gets or sets the underlying disposable. + + Assigning this property disposes the previous disposable object. + + If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. + */ + public var disposable: Disposable { + get { + self.lock.performLocked { + self.current ?? Disposables.create() + } + } + set (newDisposable) { + let disposable: Disposable? = self.lock.performLocked { + if self.isDisposed { + return newDisposable + } + else { + let toDispose = self.current + self.current = newDisposable + return toDispose + } + } + + if let disposable = disposable { + disposable.dispose() + } + } + } + + /// Disposes the underlying disposable as well as all future replacements. + public func dispose() { + self._dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + self.lock.performLocked { + guard !self.isDisposed else { return nil } + + self.disposed = true + let current = self.current + self.current = nil + return current + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 00000000..4a5fb866 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,72 @@ +// +// SingleAssignmentDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + +If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. +*/ +public final class SingleAssignmentDisposable : DisposeBase, Cancelable { + + private struct DisposeState: OptionSet { + let rawValue: Int32 + + static let disposed = DisposeState(rawValue: 1 << 0) + static let disposableSet = DisposeState(rawValue: 1 << 1) + } + + // state + private let state = AtomicInt(0) + private var disposable = nil as Disposable? + + /// - returns: A value that indicates whether the object is disposed. + public var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + /// Initializes a new instance of the `SingleAssignmentDisposable`. + public override init() { + super.init() + } + + /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. + /// + /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** + public func setDisposable(_ disposable: Disposable) { + self.disposable = disposable + + let previousState = fetchOr(self.state, DisposeState.disposableSet.rawValue) + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + rxFatalError("oldState.disposable != nil") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + disposable.dispose() + self.disposable = nil + } + } + + /// Disposes the underlying disposable. + public func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + guard let disposable = self.disposable else { + rxFatalError("Disposable not set") + } + disposable.dispose() + self.disposable = nil + } + } + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/ChatBot/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 00000000..a406c84c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,21 @@ +// +// SubscriptionDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct SubscriptionDisposable : Disposable { + private let key: T.DisposeKey + private weak var owner: T? + + init(owner: T, key: T.DisposeKey) { + self.owner = owner + self.key = key + } + + func dispose() { + self.owner?.synchronizedUnsubscribe(self.key) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Errors.swift b/ChatBot/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 00000000..d2d2917e --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Errors.swift @@ -0,0 +1,52 @@ +// +// Errors.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/// Generic Rx error codes. +public enum RxError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error occurred. + case unknown + /// Performing an action on disposed object. + case disposed(object: AnyObject) + /// Arithmetic overflow error. + case overflow + /// Argument out of range error. + case argumentOutOfRange + /// Sequence doesn't contain any elements. + case noElements + /// Sequence contains more than one element. + case moreThanOneElement + /// Timeout error. + case timeout +} + +extension RxError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case .disposed(let object): + return "Object `\(object)` was already disposed." + case .overflow: + return "Arithmetic overflow occurred." + case .argumentOutOfRange: + return "Argument out of range." + case .noElements: + return "Sequence doesn't contain any elements." + case .moreThanOneElement: + return "Sequence contains more than one element." + case .timeout: + return "Sequence timeout." + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Event.swift b/ChatBot/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 00000000..01861a85 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Event.swift @@ -0,0 +1,104 @@ +// +// Event.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a sequence event. +/// +/// Sequence grammar: +/// **next\* (error | completed)** +@frozen public enum Event { + /// Next element is produced. + case next(Element) + + /// Sequence terminated with an error. + case error(Swift.Error) + + /// Sequence completed successfully. + case completed +} + +extension Event: CustomDebugStringConvertible { + /// Description of event. + public var debugDescription: String { + switch self { + case .next(let value): + return "next(\(value))" + case .error(let error): + return "error(\(error))" + case .completed: + return "completed" + } + } +} + +extension Event { + /// Is `completed` or `error` event. + public var isStopEvent: Bool { + switch self { + case .next: return false + case .error, .completed: return true + } + } + + /// If `next` event, returns element value. + public var element: Element? { + if case .next(let value) = self { + return value + } + return nil + } + + /// If `error` event, returns error. + public var error: Swift.Error? { + if case .error(let error) = self { + return error + } + return nil + } + + /// If `completed` event, returns `true`. + public var isCompleted: Bool { + if case .completed = self { + return true + } + return false + } +} + +extension Event { + /// Maps sequence elements using transform. If error happens during the transform, `.error` + /// will be returned as value. + public func map(_ transform: (Element) throws -> Result) -> Event { + do { + switch self { + case let .next(element): + return .next(try transform(element)) + case let .error(error): + return .error(error) + case .completed: + return .completed + } + } + catch let e { + return .error(e) + } + } +} + +/// A type that can be converted to `Event`. +public protocol EventConvertible { + /// Type of element in event + associatedtype Element + + /// Event representation of this instance + var event: Event { get } +} + +extension Event: EventConvertible { + /// Event representation of this instance + public var event: Event { self } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift b/ChatBot/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift new file mode 100644 index 00000000..97946837 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift @@ -0,0 +1,50 @@ +// +// Bag+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/19/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + + +// MARK: forEach + +@inline(__always) +func dispatch(_ bag: Bag<(Event) -> Void>, _ event: Event) { + bag._value0?(event) + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value(event) + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element(event) + } + } +} + +/// Dispatches `dispose` to all disposables contained inside bag. +func disposeAll(in bag: Bag) { + bag._value0?.dispose() + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element.dispose() + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/GroupedObservable.swift b/ChatBot/Pods/RxSwift/RxSwift/GroupedObservable.swift new file mode 100644 index 00000000..189a8c46 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/GroupedObservable.swift @@ -0,0 +1,35 @@ +// +// GroupedObservable.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an observable sequence of elements that have a common key. +public struct GroupedObservable : ObservableType { + /// Gets the common key. + public let key: Key + + private let source: Observable + + /// Initializes grouped observable sequence with key and source observable sequence. + /// + /// - parameter key: Grouped observable sequence key + /// - parameter source: Observable sequence that represents sequence of elements for the key + /// - returns: Grouped observable sequence of elements for the specific key + public init(key: Key, source: Observable) { + self.key = key + self.source = source + } + + /// Subscribes `observer` to receive events for this sequence. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.source.subscribe(observer) + } + + /// Converts `self` to `Observable` sequence. + public func asObservable() -> Observable { + self.source + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/ChatBot/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 00000000..954fbf04 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,36 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an object that immediately schedules units of work. +public protocol ImmediateSchedulerType { + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable +} + +extension ImmediateSchedulerType { + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRecursive(_ state: State, action: @escaping (_ state: State, _ recurse: (State) -> Void) -> Void) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return Disposables.create(with: recursiveScheduler.dispose) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observable+Concurrency.swift b/ChatBot/Pods/RxSwift/RxSwift/Observable+Concurrency.swift new file mode 100644 index 00000000..c1df7eee --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observable+Concurrency.swift @@ -0,0 +1,68 @@ +// +// Observable+Concurrency.swift +// RxSwift +// +// Created by Shai Mishali on 22/09/2021. +// Copyright © 2021 Krunoslav Zaher. All rights reserved. +// + +#if swift(>=5.5.2) && canImport(_Concurrency) +import Foundation + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension ObservableConvertibleType { + /// Allows iterating over the values of an Observable + /// asynchronously via Swift's concurrency features (`async/await`) + /// + /// A sample usage would look like so: + /// + /// ```swift + /// do { + /// for try await value in observable.values { + /// // Handle emitted values + /// } + /// } catch { + /// // Handle error + /// } + /// ``` + var values: AsyncThrowingStream { + AsyncThrowingStream { continuation in + let disposable = asObservable().subscribe( + onNext: { value in continuation.yield(value) }, + onError: { error in continuation.finish(throwing: error) }, + onCompleted: { continuation.finish() }, + onDisposed: { continuation.onTermination?(.cancelled) } + ) + + continuation.onTermination = { @Sendable _ in + disposable.dispose() + } + } + } +} + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public extension AsyncSequence { + /// Convert an `AsyncSequence` to an `Observable` emitting + /// values of the asynchronous sequence's type + /// + /// - returns: An `Observable` of the async sequence's type + func asObservable() -> Observable { + Observable.create { observer in + let task = Task { + do { + for try await value in self { + observer.onNext(value) + } + + observer.onCompleted() + } catch { + observer.onError(error) + } + } + + return Disposables.create { task.cancel() } + } + } +} +#endif diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observable.swift b/ChatBot/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 00000000..93a3ed78 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observable.swift @@ -0,0 +1,31 @@ +// +// Observable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObservableType`. +/// +/// It represents a push style sequence. +public class Observable : ObservableType { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + rxAbstractMethod() + } + + public func asObservable() -> Observable { self } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + diff --git a/ChatBot/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/ChatBot/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 00000000..0f56a816 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,18 @@ +// +// ObservableConvertibleType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that can be converted to observable sequence (`Observable`). +public protocol ObservableConvertibleType { + /// Type of elements in sequence. + associatedtype Element + + /// Converts `self` to `Observable` sequence. + /// + /// - returns: Observable sequence that represents `self`. + func asObservable() -> Observable +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift b/ChatBot/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift new file mode 100644 index 00000000..ac850c3b --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift @@ -0,0 +1,174 @@ +// +// ObservableType+Extensions.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if DEBUG + import Foundation +#endif + +extension ObservableType { + /** + Subscribes an event handler to an observable sequence. + + - parameter on: Action to invoke for each event in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe(_ on: @escaping (Event) -> Void) -> Disposable { + let observer = AnonymousObserver { e in + on(e) + } + return self.asObservable().subscribe(observer) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onError: ((Object, Swift.Error) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + subscribe( + onNext: { [weak object] in + guard let object = object else { return } + onNext?(object, $0) + }, + onError: { [weak object] in + guard let object = object else { return } + onError?(object, $0) + }, + onCompleted: { [weak object] in + guard let object = object else { return } + onCompleted?(object) + }, + onDisposed: { [weak object] in + guard let object = object else { return } + onDisposed?(object) + } + ) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + onNext: ((Element) -> Void)? = nil, + onError: ((Swift.Error) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + let disposable: Disposable + + if let disposed = onDisposed { + disposable = Disposables.create(with: disposed) + } + else { + disposable = Disposables.create() + } + + #if DEBUG + let synchronizationTracker = SynchronizationTracker() + #endif + + let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : [] + + let observer = AnonymousObserver { event in + + #if DEBUG + synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { synchronizationTracker.unregister() } + #endif + + switch event { + case .next(let value): + onNext?(value) + case .error(let error): + if let onError = onError { + onError(error) + } + else { + Hooks.defaultErrorHandler(callStack, error) + } + disposable.dispose() + case .completed: + onCompleted?() + disposable.dispose() + } + } + return Disposables.create( + self.asObservable().subscribe(observer), + disposable + ) + } +} + +import Foundation + +extension Hooks { + public typealias DefaultErrorHandler = (_ subscriptionCallStack: [String], _ error: Error) -> Void + public typealias CustomCaptureSubscriptionCallstack = () -> [String] + + private static let lock = RecursiveLock() + private static var _defaultErrorHandler: DefaultErrorHandler = { subscriptionCallStack, error in + #if DEBUG + let serializedCallStack = subscriptionCallStack.joined(separator: "\n") + print("Unhandled error happened: \(error)") + if !serializedCallStack.isEmpty { + print("subscription called from:\n\(serializedCallStack)") + } + #endif + } + private static var _customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack = { + #if DEBUG + return Thread.callStackSymbols + #else + return [] + #endif + } + + /// Error handler called in case onError handler wasn't provided. + public static var defaultErrorHandler: DefaultErrorHandler { + get { + lock.performLocked { _defaultErrorHandler } + } + set { + lock.performLocked { _defaultErrorHandler = newValue } + } + } + + /// Subscription callstack block to fetch custom callstack information. + public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack { + get { + lock.performLocked { _customCaptureSubscriptionCallstack } + } + set { + lock.performLocked { _customCaptureSubscriptionCallstack = newValue } + } + } +} + diff --git a/ChatBot/Pods/RxSwift/RxSwift/ObservableType.swift b/ChatBot/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 00000000..279bf7f4 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/ObservableType.swift @@ -0,0 +1,45 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a push style sequence. +public protocol ObservableType: ObservableConvertibleType { + /** + Subscribes `observer` to receive events for this sequence. + + ### Grammar + + **Next\* (Error | Completed)?** + + * sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer` + * once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements + + It is possible that events are sent from different threads, but no two events can be sent concurrently to + `observer`. + + ### Resource Management + + When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements + will be freed. + + To cancel production of sequence elements and free resources immediately, call `dispose` on returned + subscription. + + - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. + */ + func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element +} + +extension ObservableType { + + /// Default implementation of converting `ObservableType` to `Observable`. + public func asObservable() -> Observable { + // temporary workaround + //return Observable.create(subscribe: self.subscribe) + Observable.create { o in self.subscribe(o) } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/AddRef.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/AddRef.swift new file mode 100644 index 00000000..a96dfcb0 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/AddRef.swift @@ -0,0 +1,44 @@ +// +// AddRef.swift +// RxSwift +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AddRefSink : Sink, ObserverType { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final class AddRef : Producer { + + private let source: Observable + private let refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + self.source = source + self.refCount = refCount + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let releaseDisposable = self.refCount.retain() + let sink = AddRefSink(observer: observer, cancel: cancel) + let subscription = Disposables.create(releaseDisposable, self.source.subscribe(sink)) + + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Amb.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Amb.swift new file mode 100644 index 00000000..efc17a8d --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Amb.swift @@ -0,0 +1,157 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + public static func amb(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + sequence.reduce(Observable.never()) { a, o in + a.amb(o.asObservable()) + } + } +} + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + public func amb + (_ right: O2) + -> Observable where O2.Element == Element { + Amb(left: self.asObservable(), right: right.asObservable()) + } +} + +private enum AmbState { + case neither + case left + case right +} + +final private class AmbObserver: ObserverType { + typealias Element = Observer.Element + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + private let parent: Parent + fileprivate var sink: Sink + fileprivate var cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: @escaping Sink) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + + self.parent = parent + self.sink = sink + self.cancel = cancel + } + + func on(_ event: Event) { + self.sink(self, event) + if event.isStopEvent { + self.cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final private class AmbSink: Sink { + typealias Element = Observer.Element + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let parent: Parent + + private let lock = RecursiveLock() + // state + private var choice = AmbState.neither + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = Disposables.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + let decide = { (o: AmbObserverType, event: Event, me: AmbState, otherSubscription: Disposable) in + self.lock.performLocked { + if self.choice == .neither { + self.choice = me + o.sink = forwardEvent + o.cancel = disposeAll + otherSubscription.dispose() + } + + if self.choice == me { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + } + } + + let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .left, subscription2) + } + + let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .right, subscription1) + } + + subscription1.setDisposable(self.parent.left.subscribe(sink1)) + subscription2.setDisposable(self.parent.right.subscribe(sink2)) + + return disposeAll + } +} + +final private class Amb: Producer { + fileprivate let left: Observable + fileprivate let right: Observable + + init(left: Observable, right: Observable) { + self.left = left + self.right = right + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AmbSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift new file mode 100644 index 00000000..6fa62578 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift @@ -0,0 +1,48 @@ +// +// AsMaybe.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsMaybeSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class AsMaybe: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsMaybeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/AsSingle.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/AsSingle.swift new file mode 100644 index 00000000..b39932f1 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/AsSingle.swift @@ -0,0 +1,51 @@ +// +// AsSingle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsSingleSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + self.forwardOn(.completed) + } + else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class AsSingle: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsSingleSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Buffer.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Buffer.swift new file mode 100644 index 00000000..087c4cf5 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Buffer.swift @@ -0,0 +1,138 @@ +// +// Buffer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[Element]> { + BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class BufferTimeCount: Producer<[Element]> { + + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [Element] { + let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == [Element] { + typealias Parent = BufferTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + // state + private let timerD = SerialDisposable() + private var buffer = [Element]() + private var windowID = 0 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.createTimer(self.windowID) + return Disposables.create(timerD, parent.source.subscribe(self)) + } + + func startNewWindowAndSendCurrentOne() { + self.windowID = self.windowID &+ 1 + let windowID = self.windowID + + let buffer = self.buffer + self.buffer = [] + self.forwardOn(.next(buffer)) + + self.createTimer(windowID) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.buffer.append(element) + + if self.buffer.count == self.parent.count { + self.startNewWindowAndSendCurrentOne() + } + + case .error(let error): + self.buffer = [] + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(self.buffer)) + self.forwardOn(.completed) + self.dispose() + } + } + + func createTimer(_ windowID: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let disposable = self.parent.scheduler.scheduleRelative(windowID, dueTime: self.parent.timeSpan) { previousWindowID in + self.lock.performLocked { + if previousWindowID != self.windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposable) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Catch.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Catch.swift new file mode 100644 index 00000000..2efd6606 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Catch.swift @@ -0,0 +1,275 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + public func `catch`(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + Catch(source: self.asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + @available(*, deprecated, renamed: "catch(_:)") + public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + `catch`(handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + public func catchAndReturn(_ element: Element) + -> Observable { + Catch(source: self.asObservable(), handler: { _ in Observable.just(element) }) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + @available(*, deprecated, renamed: "catchAndReturn(_:)") + public func catchErrorJustReturn(_ element: Element) + -> Observable { + catchAndReturn(element) + } +} + +extension ObservableType { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + @available(*, deprecated, renamed: "catch(onSuccess:onFailure:onDisposed:)") + public static func catchError(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + `catch`(sequence: sequence) + } + + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + public static func `catch`(sequence: Sequence) -> Observable + where Sequence.Element == Observable { + CatchSequence(sources: sequence) + } +} + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + public func retry() -> Observable { + CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + public func retry(_ maxAttemptCount: Int) + -> Observable { + CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount)) + } +} + +// catch with callback + +final private class CatchSinkProxy: ObserverType { + typealias Element = Observer.Element + typealias Parent = CatchSink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.parent.forwardOn(event) + + switch event { + case .next: + break + case .error, .completed: + self.parent.dispose() + } + } +} + +final private class CatchSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = Catch + + private let parent: Parent + private let subscription = SerialDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + self.subscription.disposable = d1 + d1.setDisposable(self.parent.source.subscribe(self)) + + return self.subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed: + self.forwardOn(event) + self.dispose() + case .error(let error): + do { + let catchSequence = try self.parent.handler(error) + + let observer = CatchSinkProxy(parent: self) + + self.subscription.disposable = catchSequence.subscribe(observer) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Catch: Producer { + typealias Handler = (Swift.Error) throws -> Observable + + fileprivate let source: Observable + fileprivate let handler: Handler + + init(source: Observable, handler: @escaping Handler) { + self.source = source + self.handler = handler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// catch enumerable + +final private class CatchSequenceSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = CatchSequence + + private var lastError: Swift.Error? + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error(let error): + self.lastError = error + self.schedule(.moveNext) + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.makeIterator(), nil) + } + else { + return nil + } + } +} + +final private class CatchSequence: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + let sources: Sequence + + init(sources: Sequence) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSequenceSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift new file mode 100644 index 00000000..4350851c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift @@ -0,0 +1,165 @@ +// +// CombineLatest+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) + } +} + +final private class CombineLatestCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = CombineLatestCollectionType + typealias SourceElement = Collection.Element.Element + + let parent: Parent + + let lock = RecursiveLock() + + // state + var numberOfValues = 0 + var values: [SourceElement?] + var isDone: [Bool] + var numberOfDone = 0 + var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [SourceElement?](repeating: nil, count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + if self.values[atIndex] == nil { + self.numberOfValues += 1 + } + + self.values[atIndex] = element + + if self.numberOfValues < self.parent.count { + let numberOfOthersThatAreDone = self.numberOfDone - (self.isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + let result = try self.parent.resultSelector(self.values.map { $0! }) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + self.subscriptions[j].setDisposable(disposable) + + j += 1 + } + + if self.parent.sources.isEmpty { + do { + let result = try self.parent.resultSelector([]) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return Disposables.create(subscriptions) + } +} + +final private class CombineLatestCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift new file mode 100644 index 00000000..e69bbab4 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift @@ -0,0 +1,843 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class CombineLatestSink2_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest2 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2) + } +} + +final class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class CombineLatestSink3_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest3 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3) + } +} + +final class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class CombineLatestSink4_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest4 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4) + } +} + +final class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class CombineLatestSink5_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest5 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5) + } +} + +final class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class CombineLatestSink6_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest6 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6) + } +} + +final class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class CombineLatestSink7_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest7 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7) + } +} + +final class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class CombineLatestSink8_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest8 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + var latestElement8: E8! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + let observer8 = CombineLatestObserver(lock: self.lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self.latestElement8 = e }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7, self.latestElement8) + } +} + +final class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift new file mode 100644 index 00000000..caa02564 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift @@ -0,0 +1,131 @@ +// +// CombineLatest.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol CombineLatestProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = Observer.Element + + let lock = RecursiveLock() + + private let arity: Int + private var numberOfValues = 0 + private var numberOfDone = 0 + private var hasValue: [Bool] + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.arity = arity + self.hasValue = [Bool](repeating: false, count: arity) + self.isDone = [Bool](repeating: false, count: arity) + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func next(_ index: Int) { + if !self.hasValue[index] { + self.hasValue[index] = true + self.numberOfValues += 1 + } + + if self.numberOfValues == self.arity { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + else { + var allOthersDone = true + + for i in 0 ..< self.arity { + if i != index && !self.isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + self.forwardOn(.completed) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + if self.isDone[index] { + return + } + + self.isDone[index] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.arity { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private let parent: CombineLatestProtocol + + let lock: RecursiveLock + private let index: Int + private let this: Disposable + private let setLatestValue: ValueSetter + + init(lock: RecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setLatestValue = setLatestValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.setLatestValue(value) + self.parent.next(self.index) + case .error(let error): + self.this.dispose() + self.parent.fail(error) + case .completed: + self.this.dispose() + self.parent.done(self.index) + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/CompactMap.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/CompactMap.swift new file mode 100644 index 00000000..7dbcdfbe --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/CompactMap.swift @@ -0,0 +1,76 @@ +// +// CompactMap.swift +// RxSwift +// +// Created by Michael Long on 04/09/2019. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into an optional form and filters all optional results. + + - parameter transform: A transform function to apply to each source element and which returns an element or nil. + - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. + + */ + public func compactMap(_ transform: @escaping (Element) throws -> Result?) + -> Observable { + CompactMap(source: self.asObservable(), transform: transform) + } +} + +final private class CompactMapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType? + + typealias ResultType = Observer.Element + typealias Element = SourceType + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + if let mappedElement = try self.transform(element) { + self.forwardOn(.next(mappedElement)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class CompactMap: Producer { + typealias Transform = (SourceType) throws -> ResultType? + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = CompactMapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Concat.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Concat.swift new file mode 100644 index 00000000..b2fb1a2e --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Concat.swift @@ -0,0 +1,131 @@ +// +// Concat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + public func concat(_ second: Source) -> Observable where Source.Element == Element { + Observable.concat([self.asObservable(), second.asObservable()]) + } +} + +extension ObservableType { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + return Concat(sources: sequence, count: nil) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: Collection) -> Observable + where Collection.Element == Observable { + return Concat(sources: collection, count: Int64(collection.count)) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sources: Observable ...) -> Observable { + Concat(sources: sources, count: Int64(sources.count)) + } +} + +final private class ConcatSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event){ + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.schedule(.moveNext) + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source.sources.makeIterator(), source.count) + } + else { + return nil + } + } +} + +final private class Concat: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + fileprivate let sources: Sequence + fileprivate let count: IntMax? + + init(sources: Sequence, count: IntMax?) { + self.sources = sources + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ConcatSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), self.count)) + return (sink: sink, subscription: subscription) + } +} + diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Create.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Create.swift new file mode 100644 index 00000000..ca81442c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Create.swift @@ -0,0 +1,78 @@ +// +// Create.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable { + AnonymousObservable(subscribe) + } +} + +final private class AnonymousObservableSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = AnonymousObservable + + // state + private let isStopped = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + switch event { + case .next: + if load(self.isStopped) == 1 { + return + } + self.forwardOn(event) + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.forwardOn(event) + self.dispose() + } + } + } + + func run(_ parent: Parent) -> Disposable { + parent.subscribeHandler(AnyObserver(self)) + } +} + +final private class AnonymousObservable: Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: @escaping SubscribeHandler) { + self.subscribeHandler = subscribeHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AnonymousObservableSink(observer: observer, cancel: cancel) + let subscription = sink.run(self) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Debounce.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Debounce.swift new file mode 100644 index 00000000..dfab0045 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Debounce.swift @@ -0,0 +1,119 @@ +// +// Debounce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/11/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DebounceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Debounce + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var id = 0 as UInt64 + private var value: Element? + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.id = self.id &+ 1 + let currentId = self.id + self.value = element + + + let scheduler = self.parent.scheduler + let dueTime = self.parent.dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)) + case .error: + self.value = nil + self.forwardOn(event) + self.dispose() + case .completed: + if let value = self.value { + self.value = nil + self.forwardOn(.next(value)) + } + self.forwardOn(.completed) + self.dispose() + } + } + + func propagate(_ currentId: UInt64) -> Disposable { + self.lock.performLocked { + let originalValue = self.value + + if let value = originalValue, self.id == currentId { + self.value = nil + self.forwardOn(.next(value)) + } + + return Disposables.create() + } + } +} + +final private class Debounce: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DebounceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Debug.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Debug.swift new file mode 100644 index 00000000..762e394f --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Debug.swift @@ -0,0 +1,102 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - parameter trimOutput: Should output be trimmed to max 40 characters. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self, identifier: identifier, trimOutput: trimOutput, file: file, line: line, function: function) + } +} + +private let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +private func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) { + print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)") +} + +final private class DebugSink: Sink, ObserverType where Observer.Element == Source.Element { + typealias Element = Observer.Element + typealias Parent = Debug + + private let parent: Parent + private let timestampFormatter = DateFormatter() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.timestampFormatter.dateFormat = dateFormat + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "subscribed") + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + + let eventNormalized = (eventText.count > maxEventTextLength) && self.parent.trimOutput + ? String(eventText.prefix(maxEventTextLength / 2)) + "..." + String(eventText.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "Event \(eventNormalized)") + + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + override func dispose() { + if !self.isDisposed { + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "isDisposed") + } + super.dispose() + } +} + +final private class Debug: Producer { + fileprivate let identifier: String + fileprivate let trimOutput: Bool + private let source: Source + + init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) { + self.trimOutput = trimOutput + if let identifier = identifier { + self.identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndex(of: "/") { + trimmedFile = String(file[file.index(after: lastIndex) ..< file.endIndex]) + } + else { + trimmedFile = file + } + self.identifier = "\(trimmedFile):\(line) (\(function))" + } + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = DebugSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Decode.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Decode.swift new file mode 100644 index 00000000..8bc73425 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Decode.swift @@ -0,0 +1,34 @@ +// +// Decode.swift +// RxSwift +// +// Created by Shai Mishali on 24/07/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +public extension ObservableType where Element == Data { + /// Attempt to decode the emitted `Data` using a provided decoder. + /// + /// - parameter type: A `Decodable`-conforming type to attempt to decode to + /// - parameter decoder: A capable decoder, e.g. `JSONDecoder` or `PropertyListDecoder` + /// + /// - note: If using a custom decoder, it must conform to the `DataDecoder` protocol. + /// + /// - returns: An `Observable` of the decoded type + func decode(type: Item.Type, + decoder: Decoder) -> Observable { + map { try decoder.decode(type, from: $0) } + } +} + +/// Represents an entity capable of decoding raw `Data` +/// into a concrete `Decodable` type +public protocol DataDecoder { + func decode(_ type: Item.Type, from data: Data) throws -> Item +} + +extension JSONDecoder: DataDecoder {} +extension PropertyListDecoder: DataDecoder {} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift new file mode 100644 index 00000000..8d133d8f --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift @@ -0,0 +1,66 @@ +// +// DefaultIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter default: Default element to be sent if the source does not emit any elements + - returns: An observable sequence which emits default element end completes in case the original sequence is empty + */ + public func ifEmpty(default: Element) -> Observable { + DefaultIfEmpty(source: self.asObservable(), default: `default`) + } +} + +final private class DefaultIfEmptySink: Sink, ObserverType { + typealias Element = Observer.Element + private let `default`: Element + private var isEmpty = true + + init(default: Element, observer: Observer, cancel: Cancelable) { + self.default = `default` + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.isEmpty { + self.forwardOn(.next(self.default)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class DefaultIfEmpty: Producer { + private let source: Observable + private let `default`: SourceType + + init(source: Observable, `default`: SourceType) { + self.source = source + self.default = `default` + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = DefaultIfEmptySink(default: self.default, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Deferred.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Deferred.swift new file mode 100644 index 00000000..b81cb166 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Deferred.swift @@ -0,0 +1,75 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () throws -> Observable) + -> Observable { + Deferred(observableFactory: observableFactory) + } +} + +final private class DeferredSink: Sink, ObserverType where Source.Element == Observer.Element { + typealias Element = Observer.Element + + private let observableFactory: () throws -> Source + + init(observableFactory: @escaping () throws -> Source, observer: Observer, cancel: Cancelable) { + self.observableFactory = observableFactory + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let result = try self.observableFactory() + return result.subscribe(self) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + + switch event { + case .next: + break + case .error: + self.dispose() + case .completed: + self.dispose() + } + } +} + +final private class Deferred: Producer { + typealias Factory = () throws -> Source + + private let observableFactory : Factory + + init(observableFactory: @escaping Factory) { + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == Source.Element { + let sink = DeferredSink(observableFactory: self.observableFactory, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Delay.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Delay.swift new file mode 100644 index 00000000..9f71c32d --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Delay.swift @@ -0,0 +1,174 @@ +// +// Delay.swift +// RxSwift +// +// Created by tarunon on 2016/02/09. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySink + : Sink + , ObserverType { + typealias Element = Observer.Element + typealias Source = Observable + typealias DisposeKey = Bag.KeyType + + private let lock = RecursiveLock() + + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + private let sourceSubscription = SingleAssignmentDisposable() + private let cancelable = SerialDisposable() + + // is scheduled some action + private var active = false + // is "run loop" on different scheduler running + private var running = false + private var errorEvent: Event? + + // state + private var queue = Queue<(eventTime: RxTime, event: Event)>(capacity: 0) + + init(observer: Observer, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { + self.dueTime = dueTime + self.scheduler = scheduler + super.init(observer: observer, cancel: cancel) + } + + // All of these complications in this method are caused by the fact that + // error should be propagated immediately. Error can be potentially received on different + // scheduler so this process needs to be synchronized somehow. + // + // Another complication is that scheduler is potentially concurrent so internal queue is used. + func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { + self.lock.lock() + let hasFailed = self.errorEvent != nil + if !hasFailed { + self.running = true + } + self.lock.unlock() + + if hasFailed { + return + } + + var ranAtLeastOnce = false + + while true { + self.lock.lock() + let errorEvent = self.errorEvent + + let eventToForwardImmediately = ranAtLeastOnce ? nil : self.queue.dequeue()?.event + let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !self.queue.isEmpty ? self.queue.peek().eventTime : nil + + if errorEvent == nil { + if eventToForwardImmediately != nil { + } + else if nextEventToScheduleOriginalTime != nil { + self.running = false + } + else { + self.running = false + self.active = false + } + } + self.lock.unlock() + + if let errorEvent = errorEvent { + self.forwardOn(errorEvent) + self.dispose() + return + } + else { + if let eventToForwardImmediately = eventToForwardImmediately { + ranAtLeastOnce = true + self.forwardOn(eventToForwardImmediately) + if case .completed = eventToForwardImmediately { + self.dispose() + return + } + } + else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { + scheduler.schedule((), dueTime: self.dueTime.reduceWithSpanBetween(earlierDate: nextEventToScheduleOriginalTime, laterDate: self.scheduler.now)) + return + } + else { + return + } + } + } + } + + func on(_ event: Event) { + if event.isStopEvent { + self.sourceSubscription.dispose() + } + + switch event { + case .error: + self.lock.lock() + let shouldSendImmediately = !self.running + self.queue = Queue(capacity: 0) + self.errorEvent = event + self.lock.unlock() + + if shouldSendImmediately { + self.forwardOn(event) + self.dispose() + } + default: + self.lock.lock() + let shouldSchedule = !self.active + self.active = true + self.queue.enqueue((self.scheduler.now, event)) + self.lock.unlock() + + if shouldSchedule { + self.cancelable.disposable = self.scheduler.scheduleRecursive((), dueTime: self.dueTime, action: self.drainQueue) + } + } + } + + func run(source: Observable) -> Disposable { + self.sourceSubscription.setDisposable(source.subscribe(self)) + return Disposables.create(sourceSubscription, cancelable) + } +} + +final private class Delay: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySink(observer: observer, dueTime: self.dueTime, scheduler: self.scheduler, cancel: cancel) + let subscription = sink.run(source: self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift new file mode 100644 index 00000000..fd8c4951 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift @@ -0,0 +1,58 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySubscriptionSink + : Sink, ObserverType { + typealias Element = Observer.Element + + func on(_ event: Event) { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + +} + +final private class DelaySubscription: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySubscriptionSink(observer: observer, cancel: cancel) + let subscription = self.scheduler.scheduleRelative((), dueTime: self.dueTime) { _ in + return self.source.subscribe(sink) + } + + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift new file mode 100644 index 00000000..2ccd5462 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift @@ -0,0 +1,51 @@ +// +// Dematerialize.swift +// RxSwift +// +// Created by Jamie Pinkham on 3/13/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: EventConvertible { + /** + Convert any previously materialized Observable into it's original form. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: The dematerialized observable sequence. + */ + public func dematerialize() -> Observable { + Dematerialize(source: self.asObservable()) + } + +} + +private final class DematerializeSink: Sink, ObserverType where Observer.Element == T.Element { + fileprivate func on(_ event: Event) { + switch event { + case .next(let element): + self.forwardOn(element.event) + if element.event.isStopEvent { + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Dematerialize: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == T.Element { + let sink = DematerializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift new file mode 100644 index 00000000..c127b5aa --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift @@ -0,0 +1,137 @@ +// +// DistinctUntilChanged.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> Key) + -> Observable { + self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool) + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } + + /** + Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path + */ + public func distinctUntilChanged(at keyPath: KeyPath) -> + Observable { + self.distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] } + } +} + +final private class DistinctUntilChangedSink: Sink, ObserverType { + typealias Element = Observer.Element + + private let parent: DistinctUntilChanged + private var currentKey: Key? + + init(parent: DistinctUntilChanged, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let key = try self.parent.selector(value) + var areEqual = false + if let currentKey = self.currentKey { + areEqual = try self.parent.comparer(currentKey, key) + } + + if areEqual { + return + } + + self.currentKey = key + + self.forwardOn(event) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + private let source: Observable + fileprivate let selector: KeySelector + fileprivate let comparer: EqualityComparer + + init(source: Observable, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { + self.source = source + self.selector = selector + self.comparer = comparer + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Do.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Do.swift new file mode 100644 index 00000000..3c8c68b3 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Do.swift @@ -0,0 +1,112 @@ +// +// Do.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter afterError: Action to invoke after errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, afterError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable(), eventHandler: { e in + switch e { + case .next(let element): + try onNext?(element) + case .error(let e): + try onError?(e) + case .completed: + try onCompleted?() + } + }, afterEventHandler: { e in + switch e { + case .next(let element): + try afterNext?(element) + case .error(let e): + try afterError?(e) + case .completed: + try afterCompleted?() + } + }, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + } +} + +final private class DoSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + + init(eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, observer: Observer, cancel: Cancelable) { + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + do { + try self.eventHandler(event) + self.forwardOn(event) + try self.afterEventHandler(event) + if event.isStopEvent { + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Do: Producer { + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let source: Observable + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + private let onSubscribe: (() -> Void)? + private let onSubscribed: (() -> Void)? + private let onDispose: (() -> Void)? + + init(source: Observable, eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, onSubscribe: (() -> Void)?, onSubscribed: (() -> Void)?, onDispose: (() -> Void)?) { + self.source = source + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + self.onSubscribe = onSubscribe + self.onSubscribed = onSubscribed + self.onDispose = onDispose + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + self.onSubscribe?() + let sink = DoSink(eventHandler: self.eventHandler, afterEventHandler: self.afterEventHandler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + self.onSubscribed?() + let onDispose = self.onDispose + let allSubscriptions = Disposables.create { + subscription.dispose() + onDispose?() + } + return (sink: sink, subscription: allSubscriptions) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/ElementAt.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/ElementAt.swift new file mode 100644 index 00000000..3f09c708 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/ElementAt.swift @@ -0,0 +1,105 @@ +// +// ElementAt.swift +// RxSwift +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + @available(*, deprecated, renamed: "element(at:)") + public func elementAt(_ index: Int) + -> Observable { + element(at: index) + } + + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + public func element(at index: Int) + -> Observable { + ElementAt(source: self.asObservable(), index: index, throwOnEmpty: true) + } +} + +final private class ElementAtSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = ElementAt + + let parent: Parent + var i: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.i = parent.index + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + + if self.i == 0 { + self.forwardOn(event) + self.forwardOn(.completed) + self.dispose() + } + + do { + _ = try decrementChecked(&self.i) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + if self.parent.throwOnEmpty { + self.forwardOn(.error(RxError.argumentOutOfRange)) + } else { + self.forwardOn(.completed) + } + + self.dispose() + } + } +} + +final private class ElementAt: Producer { + let source: Observable + let throwOnEmpty: Bool + let index: Int + + init(source: Observable, index: Int, throwOnEmpty: Bool) { + if index < 0 { + rxFatalError("index can't be negative") + } + + self.source = source + self.index = index + self.throwOnEmpty = throwOnEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Empty.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Empty.swift new file mode 100644 index 00000000..9ca59659 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Empty.swift @@ -0,0 +1,27 @@ +// +// Empty.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + public static func empty() -> Observable { + EmptyProducer() + } +} + +final private class EmptyProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.completed) + return Disposables.create() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Enumerated.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Enumerated.swift new file mode 100644 index 00000000..ef8a0ff0 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Enumerated.swift @@ -0,0 +1,61 @@ +// +// Enumerated.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/6/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Enumerates the elements of an observable sequence. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - returns: An observable sequence that contains tuples of source sequence elements and their indexes. + */ + public func enumerated() + -> Observable<(index: Int, element: Element)> { + Enumerated(source: self.asObservable()) + } +} + +final private class EnumeratedSink: Sink, ObserverType where Observer.Element == (index: Int, element: Element) { + var index = 0 + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let nextIndex = try incrementChecked(&self.index) + let next = (index: nextIndex, element: value) + self.forwardOn(.next(next)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Enumerated: Producer<(index: Int, element: Element)> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == (index: Int, element: Element) { + let sink = EnumeratedSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Error.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Error.swift new file mode 100644 index 00000000..2e722d67 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Error.swift @@ -0,0 +1,33 @@ +// +// Error.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + public static func error(_ error: Swift.Error) -> Observable { + ErrorProducer(error: error) + } +} + +final private class ErrorProducer: Producer { + private let error: Swift.Error + + init(error: Swift.Error) { + self.error = error + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.error(self.error)) + return Disposables.create() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Filter.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Filter.swift new file mode 100644 index 00000000..61d3ce79 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Filter.swift @@ -0,0 +1,86 @@ +// +// Filter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + Filter(source: self.asObservable(), predicate: predicate) + } +} + +extension ObservableType { + /** + Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + public func ignoreElements() + -> Observable { + self.flatMap { _ in Observable.empty() } + } +} + +final private class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = Observer.Element + + private let predicate: Predicate + + init(predicate: @escaping Predicate, observer: Observer, cancel: Cancelable) { + self.predicate = predicate + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let satisfies = try self.predicate(value) + if satisfies { + self.forwardOn(.next(value)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class Filter: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + private let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = FilterSink(predicate: self.predicate, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/First.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/First.swift new file mode 100644 index 00000000..00141148 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/First.swift @@ -0,0 +1,41 @@ +// +// First.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/31/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class FirstSink : Sink, ObserverType where Observer.Element == Element? { + typealias Parent = First + + func on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(nil)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class First: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element? { + let sink = FirstSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Generate.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Generate.swift new file mode 100644 index 00000000..7b924b38 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Generate.swift @@ -0,0 +1,87 @@ +// +// Generate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + public static func generate(initialState: Element, condition: @escaping (Element) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (Element) throws -> Element) -> Observable { + Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } +} + +final private class GenerateSink: Sink { + typealias Parent = Generate + + private let parent: Parent + + private var state: Sequence + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.state = parent.initialState + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(true) { isFirst, recurse -> Void in + do { + if !isFirst { + self.state = try self.parent.iterate(self.state) + } + + if try self.parent.condition(self.state) { + let result = try self.parent.resultSelector(self.state) + self.forwardOn(.next(result)) + + recurse(false) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + } +} + +final private class Generate: Producer { + fileprivate let initialState: Sequence + fileprivate let condition: (Sequence) throws -> Bool + fileprivate let iterate: (Sequence) throws -> Sequence + fileprivate let resultSelector: (Sequence) throws -> Element + fileprivate let scheduler: ImmediateSchedulerType + + init(initialState: Sequence, condition: @escaping (Sequence) throws -> Bool, iterate: @escaping (Sequence) throws -> Sequence, resultSelector: @escaping (Sequence) throws -> Element, scheduler: ImmediateSchedulerType) { + self.initialState = initialState + self.condition = condition + self.iterate = iterate + self.resultSelector = resultSelector + self.scheduler = scheduler + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/GroupBy.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/GroupBy.swift new file mode 100644 index 00000000..88cbda76 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/GroupBy.swift @@ -0,0 +1,133 @@ +// +// GroupBy.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /* + Groups the elements of an observable sequence according to a specified key selector function. + + - seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html) + + - parameter keySelector: A function to extract the key for each element. + - returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + public func groupBy(keySelector: @escaping (Element) throws -> Key) + -> Observable> { + GroupBy(source: self.asObservable(), selector: keySelector) + } +} + +final private class GroupedObservableImpl: Observable { + private var subject: PublishSubject + private var refCount: RefCountDisposable + + init(subject: PublishSubject, refCount: RefCountDisposable) { + self.subject = subject + self.refCount = refCount + } + + override public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + let release = self.refCount.retain() + let subscription = self.subject.subscribe(observer) + return Disposables.create(release, subscription) + } +} + + +final private class GroupBySink + : Sink + , ObserverType where Observer.Element == GroupedObservable { + typealias ResultType = Observer.Element + typealias Parent = GroupBy + + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + private var refCountDisposable: RefCountDisposable! + private var groupedSubjectTable: [Key: PublishSubject] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.groupedSubjectTable = [Key: PublishSubject]() + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.refCountDisposable = RefCountDisposable(disposable: self.subscription) + + self.subscription.setDisposable(self.parent.source.subscribe(self)) + + return self.refCountDisposable + } + + private func onGroupEvent(key: Key, value: Element) { + if let writer = self.groupedSubjectTable[key] { + writer.on(.next(value)) + } else { + let writer = PublishSubject() + self.groupedSubjectTable[key] = writer + + let group = GroupedObservable( + key: key, + source: GroupedObservableImpl(subject: writer, refCount: refCountDisposable) + ) + + self.forwardOn(.next(group)) + writer.on(.next(value)) + } + } + + final func on(_ event: Event) { + switch event { + case let .next(value): + do { + let groupKey = try self.parent.selector(value) + self.onGroupEvent(key: groupKey, value: value) + } + catch let e { + self.error(e) + return + } + case let .error(e): + self.error(e) + case .completed: + self.forwardOnGroups(event: .completed) + self.forwardOn(.completed) + self.subscription.dispose() + self.dispose() + } + } + + final func error(_ error: Swift.Error) { + self.forwardOnGroups(event: .error(error)) + self.forwardOn(.error(error)) + self.subscription.dispose() + self.dispose() + } + + final func forwardOnGroups(event: Event) { + for writer in self.groupedSubjectTable.values { + writer.on(event) + } + } +} + +final private class GroupBy: Producer> { + typealias KeySelector = (Element) throws -> Key + + fileprivate let source: Observable + fileprivate let selector: KeySelector + + init(source: Observable, selector: @escaping KeySelector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == GroupedObservable { + let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) + return (sink: sink, subscription: sink.run()) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Just.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Just.swift new file mode 100644 index 00000000..93490837 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Just.swift @@ -0,0 +1,87 @@ +// +// Just.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element) -> Observable { + Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Observable { + JustScheduled(element: element, scheduler: scheduler) + } +} + +final private class JustScheduledSink: Sink { + typealias Parent = JustScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let scheduler = self.parent.scheduler + return scheduler.schedule(self.parent.element) { element in + self.forwardOn(.next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class JustScheduled: Producer { + fileprivate let scheduler: ImmediateSchedulerType + fileprivate let element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.element = element + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class Just: Producer { + private let element: Element + + init(element: Element) { + self.element = element + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.next(self.element)) + observer.on(.completed) + return Disposables.create() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Map.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Map.swift new file mode 100644 index 00000000..0691273c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Map.swift @@ -0,0 +1,77 @@ +// +// Map.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter transform: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + public func map(_ transform: @escaping (Element) throws -> Result) + -> Observable { + Map(source: self.asObservable(), transform: transform) + } +} + +final private class MapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType + + typealias ResultType = Observer.Element + typealias Element = SourceType + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + let mappedElement = try self.transform(element) + self.forwardOn(.next(mappedElement)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Map: Producer { + typealias Transform = (SourceType) throws -> ResultType + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = MapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Materialize.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Materialize.swift new file mode 100644 index 00000000..e2577be5 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Materialize.swift @@ -0,0 +1,44 @@ +// +// Materialize.swift +// RxSwift +// +// Created by sergdort on 08/03/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Convert any Observable into an Observable of its events. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: An observable sequence that wraps events in an Event. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable. + */ + public func materialize() -> Observable> { + Materialize(source: self.asObservable()) + } +} + +private final class MaterializeSink: Sink, ObserverType where Observer.Element == Event { + + func on(_ event: Event) { + self.forwardOn(.next(event)) + if event.isStopEvent { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Materialize: Producer> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MaterializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Merge.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Merge.swift new file mode 100644 index 00000000..51a64629 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Merge.swift @@ -0,0 +1,600 @@ +// +// Merge.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMap(source: self.asObservable(), selector: selector) + } + +} + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapFirst(source: self.asObservable(), selector: selector) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> Observable { + Merge(source: self.asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> Observable { + MergeLimited(source: self.asObservable(), maxConcurrent: maxConcurrent) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + public func concat() -> Observable { + self.merge(maxConcurrent: 1) + } +} + +extension ObservableType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Collection) -> Observable where Collection.Element == Observable { + MergeArray(sources: Array(sources)) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [Observable]) -> Observable { + MergeArray(sources: sources) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Observable...) -> Observable { + MergeArray(sources: sources) + } +} + +// MARK: concatMap + +extension ObservableType { + /** + Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + + public func concatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return ConcatMap(source: self.asObservable(), selector: selector) + } +} + +private final class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where SourceSequence.Element == Observer.Element { + typealias Element = Observer.Element + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Parent = MergeLimitedSink + + private let parent: Parent + private let disposeKey: DisposeKey + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + if let next = self.parent.queue.dequeue() { + self.parent.subscribe(next, group: self.parent.group) + } + else { + self.parent.activeCount -= 1 + + if self.parent.stopped && self.parent.activeCount == 0 { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + } + } + } +} + +private final class ConcatMapSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(maxConcurrent: 1, observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeLimitedBasicSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + + override func performMap(_ element: SourceSequence) throws -> SourceSequence { + element + } +} + +private class MergeLimitedSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias QueueType = Queue + + let maxConcurrent: Int + + let lock = RecursiveLock() + + // state + var stopped = false + var activeCount = 0 + var queue = QueueType(capacity: 2) + + let sourceSubscription = SingleAssignmentDisposable() + let group = CompositeDisposable() + + init(maxConcurrent: Int, observer: Observer, cancel: Cancelable) { + self.maxConcurrent = maxConcurrent + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let disposable = source.subscribe(self) + self.sourceSubscription.setDisposable(disposable) + return self.group + } + + func subscribe(_ innerSource: SourceSequence, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.insert(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.setDisposable(disposable) + } + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + let subscribe: Bool + if self.activeCount < self.maxConcurrent { + self.activeCount += 1 + subscribe = true + } + else { + do { + let value = try self.performMap(element) + self.queue.enqueue(value) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + subscribe = false + } + + if subscribe { + do { + return try self.performMap(element) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return nil + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let sequence = self.nextElementArrived(element: element) { + self.subscribe(sequence, group: self.group) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + if self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + else { + self.sourceSubscription.dispose() + } + + self.stopped = true + } + } + } +} + +final private class MergeLimited: Producer { + private let source: Observable + private let maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + self.source = source + self.maxConcurrent = maxConcurrent + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeLimitedBasicSink(maxConcurrent: self.maxConcurrent, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +// MARK: Merge + +private final class MergeBasicSink : MergeSink where Observer.Element == Source.Element { + override func performMap(_ element: Source) throws -> Source { + element + } +} + +// MARK: flatMap + +private final class FlatMapSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +// MARK: FlatMapFirst + +private final class FlatMapFirstSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + override var subscribeNext: Bool { + self.activeCount == 0 + } + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeSinkIter : ObserverType where Observer.Element == SourceSequence.Element { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Element = Observer.Element + + private let parent: Parent + private let disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.parent.lock.performLocked { + switch event { + case .next(let value): + self.parent.forwardOn(.next(value)) + case .error(let error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + self.parent.activeCount -= 1 + self.parent.checkCompleted() + } + } + } +} + + +private class MergeSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias ResultType = Observer.Element + typealias Element = SourceElement + + let lock = RecursiveLock() + + var subscribeNext: Bool { + true + } + + // state + let group = CompositeDisposable() + let sourceSubscription = SingleAssignmentDisposable() + + var activeCount = 0 + var stopped = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + if !self.subscribeNext { + return nil + } + + do { + let value = try self.performMap(element) + self.activeCount += 1 + return value + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return nil + } + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let value = self.nextElementArrived(element: element) { + self.subscribeInner(value.asObservable()) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + self.stopped = true + self.sourceSubscription.dispose() + self.checkCompleted() + } + } + } + + func subscribeInner(_ source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = self.group.insert(iterDisposable) { + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.setDisposable(subscription) + } + } + + func run(_ sources: [Observable]) -> Disposable { + self.activeCount += sources.count + + for source in sources { + self.subscribeInner(source) + } + + self.stopped = true + + self.checkCompleted() + + return self.group + } + + @inline(__always) + func checkCompleted() { + if self.stopped && self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let subscription = source.subscribe(self) + self.sourceSubscription.setDisposable(subscription) + + return self.group + } +} + +// MARK: Producers + +final private class FlatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapFirst: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapFirstSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class ConcatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = ConcatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class Merge : Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeBasicSink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class MergeArray: Producer { + private let sources: [Observable] + + init(sources: [Observable]) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MergeBasicSink, Observer>(observer: observer, cancel: cancel) + let subscription = sink.run(self.sources) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Multicast.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Multicast.swift new file mode 100644 index 00000000..1ebcf021 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Multicast.swift @@ -0,0 +1,405 @@ +// +// Multicast.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. + */ +public class ConnectableObservable + : Observable + , ConnectableObservableType { + + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + public func connect() -> Disposable { + rxAbstractMethod() + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + public func multicast(_ subjectSelector: @escaping () throws -> Subject, selector: @escaping (Observable) throws -> Observable) + -> Observable where Subject.Observer.Element == Element { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func publish() -> ConnectableObservable { + self.multicast { PublishSubject() } + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replay(_ bufferSize: Int) + -> ConnectableObservable { + self.multicast { ReplaySubject.create(bufferSize: bufferSize) } + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replayAll() + -> ConnectableObservable { + self.multicast { ReplaySubject.createUnbounded() } + } +} + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + public func refCount() -> Observable { + RefCount(source: self) + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(_ subject: Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: { subject }) + } + + /** + Multicasts the source sequence notifications through an instantiated subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + Subject is cleared on connection disposal or in case source sequence produces terminal event. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter makeSubject: Factory function used to instantiate a subject for each connection. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(makeSubject: @escaping () -> Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: makeSubject) + } +} + +final private class Connection: ObserverType, Disposable { + typealias Element = Subject.Observer.Element + + private var lock: RecursiveLock + // state + private var parent: ConnectableObservableAdapter? + private var subscription : Disposable? + private var subjectObserver: Subject.Observer + + private let disposed = AtomicInt(0) + + init(parent: ConnectableObservableAdapter, subjectObserver: Subject.Observer, lock: RecursiveLock, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + self.lock = lock + self.subjectObserver = subjectObserver + } + + func on(_ event: Event) { + if isFlagSet(self.disposed, 1) { + return + } + if event.isStopEvent { + self.dispose() + } + self.subjectObserver.on(event) + } + + func dispose() { + lock.lock(); defer { lock.unlock() } + fetchOr(self.disposed, 1) + guard let parent = self.parent else { + return + } + + if parent.connection === self { + parent.connection = nil + parent.subject = nil + } + self.parent = nil + + self.subscription?.dispose() + self.subscription = nil + } +} + +final private class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + private let source: Observable + private let makeSubject: () -> Subject + + fileprivate let lock = RecursiveLock() + fileprivate var subject: Subject? + + // state + fileprivate var connection: ConnectionType? + + init(source: Observable, makeSubject: @escaping () -> Subject) { + self.source = source + self.makeSubject = makeSubject + self.subject = nil + self.connection = nil + } + + override func connect() -> Disposable { + return self.lock.performLocked { + if let connection = self.connection { + return connection + } + + let singleAssignmentDisposable = SingleAssignmentDisposable() + let connection = Connection(parent: self, subjectObserver: self.lazySubject.asObserver(), lock: self.lock, subscription: singleAssignmentDisposable) + self.connection = connection + let subscription = self.source.subscribe(connection) + singleAssignmentDisposable.setDisposable(subscription) + return connection + } + } + + private var lazySubject: Subject { + if let subject = self.subject { + return subject + } + + let subject = self.makeSubject() + self.subject = subject + return subject + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Subject.Element { + self.lazySubject.subscribe(observer) + } +} + +final private class RefCountSink + : Sink + , ObserverType where ConnectableSource.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RefCount + + private let parent: Parent + + private var connectionIdSnapshot: Int64 = -1 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + + self.connectionIdSnapshot = self.parent.connectionId + + if self.isDisposed { + return Disposables.create() + } + + if self.parent.count == 0 { + self.parent.count = 1 + self.parent.connectableSubscription = self.parent.source.connect() + } + else { + self.parent.count += 1 + } + + return Disposables.create { + subscription.dispose() + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + if self.parent.connectionId != self.connectionIdSnapshot { + return + } + if self.parent.count == 1 { + self.parent.count = 0 + guard let connectableSubscription = self.parent.connectableSubscription else { + return + } + + connectableSubscription.dispose() + self.parent.connectableSubscription = nil + } + else if self.parent.count > 1 { + self.parent.count -= 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + } + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error, .completed: + self.parent.lock.lock() + if self.parent.connectionId == self.connectionIdSnapshot { + let connection = self.parent.connectableSubscription + defer { connection?.dispose() } + self.parent.count = 0 + self.parent.connectionId = self.parent.connectionId &+ 1 + self.parent.connectableSubscription = nil + } + self.parent.lock.unlock() + self.forwardOn(event) + self.dispose() + } + } +} + +final private class RefCount: Producer { + fileprivate let lock = RecursiveLock() + + // state + fileprivate var count = 0 + fileprivate var connectionId: Int64 = 0 + fileprivate var connectableSubscription = nil as Disposable? + + fileprivate let source: ConnectableSource + + init(source: ConnectableSource) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == ConnectableSource.Element { + let sink = RefCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class MulticastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let parent: MutlicastType + + init(parent: MutlicastType, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let subject = try self.parent.subjectSelector() + let connectable = ConnectableObservableAdapter(source: self.parent.source, makeSubject: { subject }) + + let observable = try self.parent.selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return Disposables.create(subscription, connection) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + switch event { + case .next: break + case .error, .completed: + self.dispose() + } + } +} + +final private class Multicast: Producer { + typealias SubjectSelectorType = () throws -> Subject + typealias SelectorType = (Observable) throws -> Observable + + fileprivate let source: Observable + fileprivate let subjectSelector: SubjectSelectorType + fileprivate let selector: SelectorType + + init(source: Observable, subjectSelector: @escaping SubjectSelectorType, selector: @escaping SelectorType) { + self.source = source + self.subjectSelector = subjectSelector + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = MulticastSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Never.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Never.swift new file mode 100644 index 00000000..7b456eed --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Never.swift @@ -0,0 +1,27 @@ +// +// Never.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> Observable { + NeverProducer() + } +} + +final private class NeverProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + Disposables.create() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift new file mode 100644 index 00000000..6b8689e1 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift @@ -0,0 +1,243 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + public func observe(on scheduler: ImmediateSchedulerType) + -> Observable { + guard let serialScheduler = scheduler as? SerialDispatchQueueScheduler else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + + return ObserveOnSerialDispatchQueue(source: self.asObservable(), + scheduler: serialScheduler) + } + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "observe(on:)") + public func observeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + observe(on: scheduler) + } +} + +final private class ObserveOn: Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case stopped = 0 + // pump is running + case running = 1 +} + +final private class ObserveOnSink: ObserverBase { + typealias Element = Observer.Element + + let scheduler: ImmediateSchedulerType + + var lock = SpinLock() + let observer: Observer + + // state + var state = ObserveOnState.stopped + var queue = Queue>(capacity: 10) + + let scheduleDisposable = SerialDisposable() + let cancel: Cancelable + + init(scheduler: ImmediateSchedulerType, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + } + + override func onCore(_ event: Event) { + let shouldStart = self.lock.performLocked { () -> Bool in + self.queue.enqueue(event) + + switch self.state { + case .stopped: + self.state = .running + return true + case .running: + return false + } + } + + if shouldStart { + self.scheduleDisposable.disposable = self.scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(_ state: (), _ recurse: (()) -> Void) { + let (nextEvent, observer) = self.lock.performLocked { () -> (Event?, Observer) in + if !self.queue.isEmpty { + return (self.queue.dequeue(), self.observer) + } + else { + self.state = .stopped + return (nil, self.observer) + } + } + + if let nextEvent = nextEvent, !self.cancel.isDisposed { + observer.on(nextEvent) + if nextEvent.isStopEvent { + self.dispose() + } + } + else { + return + } + + let shouldContinue = self.shouldContinue_synchronized() + + if shouldContinue { + recurse(()) + } + } + + func shouldContinue_synchronized() -> Bool { + self.lock.performLocked { + let isEmpty = self.queue.isEmpty + if isEmpty { self.state = .stopped } + return !isEmpty + } + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + self.scheduleDisposable.dispose() + } +} + +#if TRACE_RESOURCES + private let numberOfSerialDispatchObservables = AtomicInt(0) + extension Resources { + /** + Counts number of `SerialDispatchQueueObservables`. + + Purposed for unit tests. + */ + public static var numberOfSerialDispatchQueueObservables: Int32 { + return load(numberOfSerialDispatchObservables) + } + } +#endif + +final private class ObserveOnSerialDispatchQueueSink: ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: Observer + + let cancel: Cancelable + + var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink, event: Event)) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + super.init() + + self.cachedScheduleLambda = { pair in + guard !cancel.isDisposed else { return Disposables.create() } + + pair.sink.observer.on(pair.event) + + if pair.event.isStopEvent { + pair.sink.dispose() + } + + return Disposables.create() + } + } + + override func onCore(_ event: Event) { + _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + } +} + +final private class ObserveOnSerialDispatchQueue: Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + _ = increment(numberOfSerialDispatchObservables) + #endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + _ = decrement(numberOfSerialDispatchObservables) + } + #endif +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Optional.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Optional.swift new file mode 100644 index 00000000..64f8f1fd --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Optional.swift @@ -0,0 +1,95 @@ +// +// Optional.swift +// RxSwift +// +// Created by tarunon on 2016/12/13. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?) -> Observable { + ObservableOptional(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?, scheduler: ImmediateSchedulerType) -> Observable { + ObservableOptionalScheduled(optional: optional, scheduler: scheduler) + } +} + +final private class ObservableOptionalScheduledSink: Sink { + typealias Element = Observer.Element + typealias Parent = ObservableOptionalScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedule(self.parent.optional) { (optional: Element?) -> Disposable in + if let next = optional { + self.forwardOn(.next(next)) + return self.parent.scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } else { + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class ObservableOptionalScheduled: Producer { + fileprivate let optional: Element? + fileprivate let scheduler: ImmediateSchedulerType + + init(optional: Element?, scheduler: ImmediateSchedulerType) { + self.optional = optional + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class ObservableOptional: Producer { + private let optional: Element? + + init(optional: Element?) { + self.optional = optional + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if let element = self.optional { + observer.on(.next(element)) + } + observer.on(.completed) + return Disposables.create() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Producer.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Producer.swift new file mode 100644 index 00000000..e611930a --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Producer.swift @@ -0,0 +1,92 @@ +// +// Producer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Producer: Observable { + override init() { + super.init() + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if !CurrentThreadScheduler.isScheduleRequired { + // The returned disposable needs to release all references once it was disposed. + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + } + } + + func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + rxAbstractMethod() + } +} + +private final class SinkDisposer: Cancelable { + private enum DisposeState: Int32 { + case disposed = 1 + case sinkAndSubscriptionSet = 2 + } + + private let state = AtomicInt(0) + private var sink: Disposable? + private var subscription: Disposable? + + var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { + self.sink = sink + self.subscription = subscription + + let previousState = fetchOr(self.state, DisposeState.sinkAndSubscriptionSet.rawValue) + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + rxFatalError("Sink and subscription were already set") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + sink.dispose() + subscription.dispose() + self.sink = nil + self.subscription = nil + } + } + + func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + guard let sink = self.sink else { + rxFatalError("Sink not set") + } + guard let subscription = self.subscription else { + rxFatalError("Subscription not set") + } + + sink.dispose() + subscription.dispose() + + self.sink = nil + self.subscription = nil + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Range.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Range.swift new file mode 100644 index 00000000..24535324 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Range.swift @@ -0,0 +1,73 @@ +// +// Range.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + public static func range(start: Element, count: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +final private class RangeProducer: Producer { + fileprivate let start: Element + fileprivate let count: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(start: Element, count: Element, scheduler: ImmediateSchedulerType) { + guard count >= 0 else { + rxFatalError("count can't be negative") + } + + guard start &+ (count - 1) >= start || count == 0 else { + rxFatalError("overflow of count") + } + + self.start = start + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RangeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class RangeSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = RangeProducer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(0 as Observer.Element) { i, recurse in + if i < self.parent.count { + self.forwardOn(.next(self.parent.start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Reduce.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Reduce.swift new file mode 100644 index 00000000..d5fab347 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Reduce.swift @@ -0,0 +1,109 @@ +// +// Reduce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A, mapResult: @escaping (A) throws -> Result) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } +} + +final private class ReduceSink: Sink, ObserverType { + typealias ResultType = Observer.Element + typealias Parent = Reduce + + private let parent: Parent + private var accumulation: AccumulateType + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulation = parent.seed + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + self.accumulation = try self.parent.accumulator(self.accumulation, value) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + do { + let result = try self.parent.mapResult(self.accumulation) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Reduce: Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + private let source: Observable + fileprivate let seed: AccumulateType + fileprivate let accumulator: AccumulatorType + fileprivate let mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { + self.source = source + self.seed = seed + self.accumulator = accumulator + self.mapResult = mapResult + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = ReduceSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Repeat.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Repeat.swift new file mode 100644 index 00000000..69a3ba02 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Repeat.swift @@ -0,0 +1,57 @@ +// +// Repeat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + public static func repeatElement(_ element: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RepeatElement(element: element, scheduler: scheduler) + } +} + +final private class RepeatElement: Producer { + fileprivate let element: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.element = element + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RepeatElementSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + + return (sink: sink, subscription: subscription) + } +} + +final private class RepeatElementSink: Sink { + typealias Parent = RepeatElement + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.element) { e, recurse in + self.forwardOn(.next(e)) + recurse(e) + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift new file mode 100644 index 00000000..1b2a6f13 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift @@ -0,0 +1,211 @@ +// +// RetryWhen.swift +// RxSwift +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + retry(when: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +final private class RetryTriggerSink + : ObserverType where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = TriggerObservable.Element + + typealias Parent = RetryWhenSequenceSinkIter + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.parent.lastError = nil + self.parent.parent.schedule(.moveNext) + case .error(let e): + self.parent.parent.forwardOn(.error(e)) + self.parent.parent.dispose() + case .completed: + self.parent.parent.forwardOn(.completed) + self.parent.parent.dispose() + } + } +} + +final private class RetryWhenSequenceSinkIter + : ObserverType + , Disposable where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequenceSink + + fileprivate let parent: Parent + private let errorHandlerSubscription = SingleAssignmentDisposable() + private let subscription: Disposable + + init(parent: Parent, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error(let error): + self.parent.lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + self.subscription.dispose() + + let errorHandlerSubscription = self.parent.notifier.subscribe(RetryTriggerSink(parent: self)) + self.errorHandlerSubscription.setDisposable(errorHandlerSubscription) + self.parent.errorSubject.on(.next(failedWith)) + } + else { + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } + + final func dispose() { + self.subscription.dispose() + self.errorHandlerSubscription.dispose() + } +} + +final private class RetryWhenSequenceSink + : TailRecursiveSink where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequence + + let lock = RecursiveLock() + + private let parent: Parent + + fileprivate var lastError: Swift.Error? + fileprivate let errorSubject = PublishSubject() + private let handler: Observable + fileprivate let notifier = PublishSubject() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.handler = parent.notificationHandler(self.errorSubject).asObservable() + super.init(observer: observer, cancel: cancel) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + self.lastError = nil + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are side effects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + let subscription = SingleAssignmentDisposable() + let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription) + subscription.setDisposable(source.subscribe(iter)) + return iter + } + + override func run(_ sources: SequenceGenerator) -> Disposable { + let triggerSubscription = self.handler.subscribe(self.notifier.asObserver()) + let superSubscription = super.run(sources) + return Disposables.create(superSubscription, triggerSubscription) + } +} + +final private class RetryWhenSequence: Producer where Sequence.Element: ObservableType { + typealias Element = Sequence.Element.Element + + private let sources: Sequence + fileprivate let notificationHandler: (Observable) -> TriggerObservable + + init(sources: Sequence, notificationHandler: @escaping (Observable) -> TriggerObservable) { + self.sources = sources + self.notificationHandler = notificationHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RetryWhenSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Sample.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Sample.swift new file mode 100644 index 00000000..9301c9af --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Sample.swift @@ -0,0 +1,139 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Samples the source observable sequence using a sampler observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, you may provide a default value to be emitted, instead + to the resulting sequence otherwise no element is sent.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - parameter defaultValue: a value to return if there are no new elements between sampler ticks + - returns: Sampled observable sequence. + */ + public func sample(_ sampler: Source, defaultValue: Element? = nil) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable(), defaultValue: defaultValue) + } +} + +final private class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = SampleType + + typealias Parent = SampleSequenceSink + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next, .completed: + if let element = parent.element ?? self.parent.defaultValue { + self.parent.element = nil + self.parent.forwardOn(.next(element)) + } + + if self.parent.atEnd { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + } + } +} + +final private class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = Sample + + fileprivate let parent: Parent + fileprivate let defaultValue: Element? + + let lock = RecursiveLock() + + // state + fileprivate var element = nil as Element? + fileprivate var atEnd = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable, defaultValue: Element? = nil) { + self.parent = parent + self.defaultValue = defaultValue + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.sourceSubscription.setDisposable(self.parent.source.subscribe(self)) + let samplerSubscription = self.parent.sampler.subscribe(SamplerSink(parent: self)) + + return Disposables.create(sourceSubscription, samplerSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.element = element + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.atEnd = true + self.sourceSubscription.dispose() + } + } + +} + +final private class Sample: Producer { + fileprivate let source: Observable + fileprivate let sampler: Observable + fileprivate let defaultValue: Element? + + init(source: Observable, sampler: Observable, defaultValue: Element? = nil) { + self.source = source + self.sampler = sampler + self.defaultValue = defaultValue + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel, defaultValue: self.defaultValue) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Scan.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Scan.swift new file mode 100644 index 00000000..ecf69c80 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Scan.swift @@ -0,0 +1,100 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(into seed: A, accumulator: @escaping (inout A, Element) throws -> Void) + -> Observable { + Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed) { acc, element in + let currentAcc = acc + acc = try accumulator(currentAcc, element) + } + } +} + +final private class ScanSink: Sink, ObserverType { + typealias Accumulate = Observer.Element + typealias Parent = Scan + + private let parent: Parent + private var accumulate: Accumulate + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulate = parent.seed + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + try self.parent.accumulator(&self.accumulate, element) + self.forwardOn(.next(self.accumulate)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } + +} + +final private class Scan: Producer { + typealias Accumulator = (inout Accumulate, Element) throws -> Void + + private let source: Observable + fileprivate let seed: Accumulate + fileprivate let accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: @escaping Accumulator) { + self.source = source + self.seed = seed + self.accumulator = accumulator + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Accumulate { + let sink = ScanSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Sequence.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Sequence.swift new file mode 100644 index 00000000..c6d10896 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Sequence.swift @@ -0,0 +1,89 @@ +// +// Sequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + ObservableSequence(elements: elements, scheduler: scheduler) + } +} + +extension ObservableType { + /** + Converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + ObservableSequence(elements: array, scheduler: scheduler) + } + + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable where Sequence.Element == Element { + ObservableSequence(elements: sequence, scheduler: scheduler) + } +} + +final private class ObservableSequenceSink: Sink where Sequence.Element == Observer.Element { + typealias Parent = ObservableSequence + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.elements.makeIterator()) { iterator, recurse in + var mutableIterator = iterator + if let next = mutableIterator.next() { + self.forwardOn(.next(next)) + recurse(mutableIterator) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class ObservableSequence: Producer { + fileprivate let elements: Sequence + fileprivate let scheduler: ImmediateSchedulerType + + init(elements: Sequence, scheduler: ImmediateSchedulerType) { + self.elements = elements + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift new file mode 100644 index 00000000..59d440dc --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift @@ -0,0 +1,443 @@ +// +// ShareReplayScope.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/28/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/// Subject lifetime scope +public enum SubjectLifetimeScope { + /** + **Each connection will have it's own subject instance to store replay events.** + **Connections will be isolated from each another.** + + Configures the underlying implementation to behave equivalent to. + + ``` + source.multicast(makeSubject: { MySubject() }).refCount() + ``` + + **This is the recommended default.** + + This has the following consequences: + * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. + * Each connection to source observable sequence will use it's own subject. + * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. + + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .whileConnected) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + + ``` + + Notice how time interval is different and `Performing work ...` is printed each time) + + ``` + Performing work ... + next 1495998900.82141 + completed + + Performing work ... + next 1495998900.82359 + completed + + Performing work ... + next 1495998900.82444 + completed + + + ``` + + */ + case whileConnected + + /** + **One subject will store replay events for all connections to source.** + **Connections won't be isolated from each another.** + + Configures the underlying implementation behave equivalent to. + + ``` + source.multicast(MySubject()).refCount() + ``` + + This has the following consequences: + * Using `retry` or `concat` operators after this operator usually isn't advised. + * Each connection to source observable sequence will share the same subject. + * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will + continue holding a reference to the same subject. + If at some later moment a new observer initiates a new connection to source it can potentially receive + some of the stale events received during previous connection. + * After source sequence terminates any new observer will always immediately receive replayed elements and terminal event. + No new subscriptions to source observable sequence will be attempted. + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .forever) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + ``` + + Notice how time interval is the same, replayed, and `Performing work ...` is printed only once + + ``` + Performing work ... + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + ``` + + */ + case forever +} + +extension ObservableType { + + /** + Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. + + This operator is equivalent to: + * `.whileConnected` + ``` + // Each connection will have it's own subject instance to store replay events. + // Connections will be isolated from each another. + source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() + ``` + * `.forever` + ``` + // One subject will store replay events for all connections to source. + // Connections won't be isolated from each another. + source.multicast(Replay.create(bufferSize: replay)).refCount() + ``` + + It uses optimized versions of the operators for most common operations. + + - parameter replay: Maximum element count of the replay buffer. + - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) + -> Observable { + switch scope { + case .forever: + switch replay { + case 0: return self.multicast(PublishSubject()).refCount() + default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() + } + case .whileConnected: + switch replay { + case 0: return ShareWhileConnected(source: self.asObservable()) + case 1: return ShareReplay1WhileConnected(source: self.asObservable()) + default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() + } + } + } +} + +private final class ShareReplay1WhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareReplay1WhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + private var element: Element? + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next(let element): + self.element = element + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + if let element = self.element { + observer.on(.next(element)) + } + + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareReplay1WhileConnected + : Observable { + + fileprivate typealias Connection = ShareReplay1WhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareReplay1WhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} + +private final class ShareWhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareWhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next: + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareWhileConnected + : Observable { + + fileprivate typealias Connection = ShareWhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareWhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift new file mode 100644 index 00000000..04e22176 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift @@ -0,0 +1,104 @@ +// +// SingleAsync.swift +// RxSwift +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single() + -> Observable { + SingleAsync(source: self.asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + SingleAsync(source: self.asObservable(), predicate: predicate) + } +} + +private final class SingleAsyncSink : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SingleAsync + + private let parent: Parent + private var seenValue: Bool = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let forward = try self.parent.predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + self.forwardOn(.error(error as Swift.Error)) + self.dispose() + return + } + + if self.seenValue { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + return + } + + self.seenValue = true + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.seenValue { + self.forwardOn(.completed) + } else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Sink.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Sink.swift new file mode 100644 index 00000000..ed4fec01 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Sink.swift @@ -0,0 +1,75 @@ +// +// Sink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Sink: Disposable { + fileprivate let observer: Observer + fileprivate let cancel: Cancelable + private let disposed = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + init(observer: Observer, cancel: Cancelable) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.observer = observer + self.cancel = cancel + } + + final func forwardOn(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + if isFlagSet(self.disposed, 1) { + return + } + self.observer.on(event) + } + + final func forwarder() -> SinkForward { + SinkForward(forward: self) + } + + final var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + func dispose() { + fetchOr(self.disposed, 1) + self.cancel.dispose() + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final class SinkForward: ObserverType { + typealias Element = Observer.Element + + private let forward: Sink + + init(forward: Sink) { + self.forward = forward + } + + final func on(_ event: Event) { + switch event { + case .next: + self.forward.observer.on(event) + case .error, .completed: + self.forward.observer.on(event) + self.forward.cancel.dispose() + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Skip.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Skip.swift new file mode 100644 index 00000000..5856f374 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Skip.swift @@ -0,0 +1,158 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> Observable { + SkipCount(source: self.asObservable(), count: count) + } +} + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final private class SkipCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipCount + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining <= 0 { + self.forwardOn(.next(value)) + } + else { + self.remaining -= 1 + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class SkipTimeSink: Sink, ObserverType where Observer.Element == Element { + typealias Parent = SkipTime + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if self.open { + self.forwardOn(.next(value)) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.open = true + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift new file mode 100644 index 00000000..c8fe1934 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift @@ -0,0 +1,152 @@ +// +// SkipUntil.swift +// RxSwift +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + public func skip(until other: Source) + -> Observable { + SkipUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + @available(*, deprecated, renamed: "skip(until:)") + public func skipUntil(_ other: Source) + -> Observable { + skip(until: other) + } +} + +final private class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardElements = true + self.subscription.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif + +} + + +final private class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = SkipUntil + + let lock = RecursiveLock() + private let parent: Parent + fileprivate var forwardElements = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + if self.forwardElements { + self.forwardOn(event) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.forwardElements { + self.forwardOn(event) + } + self.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = self.parent.source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + self.sourceSubscription.setDisposable(sourceSubscription) + otherObserver.subscription.setDisposable(otherSubscription) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class SkipUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift new file mode 100644 index 00000000..a62f88dd --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift @@ -0,0 +1,87 @@ +// +// SkipWhile.swift +// RxSwift +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + public func skip(while predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @available(*, deprecated, renamed: "skip(while:)") + public func skipWhile(_ predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } +} + +final private class SkipWhileSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipWhile + + private let parent: Parent + private var running = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + } + + if self.running { + self.forwardOn(.next(value)) + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/StartWith.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/StartWith.swift new file mode 100644 index 00000000..13fb31d3 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/StartWith.swift @@ -0,0 +1,42 @@ +// +// StartWith.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ elements: Element ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +final private class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + for e in self.elements { + observer.on(.next(e)) + } + + return (sink: Disposables.create(), subscription: self.source.subscribe(observer)) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift new file mode 100644 index 00000000..e8e41d9c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift @@ -0,0 +1,103 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + public func subscribe(on scheduler: ImmediateSchedulerType) + -> Observable { + SubscribeOn(source: self, scheduler: scheduler) + } + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "subscribe(on:)") + public func subscribeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + subscribe(on: scheduler) + } +} + +final private class SubscribeOnSink: Sink, ObserverType where Ob.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + let disposeSchedule = self.parent.scheduler.schedule(()) { _ -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return Disposables.create() + } + + cancelSchedule.setDisposable(disposeSchedule) + + return disposeEverything + } +} + +final private class SubscribeOn: Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Ob.Element { + let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Switch.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Switch.swift new file mode 100644 index 00000000..5aa60b97 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Switch.swift @@ -0,0 +1,251 @@ +// +// Switch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapLatest(source: self.asObservable(), selector: selector) + } + + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Infallible { + return Infallible(flatMapLatest(selector)) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> Observable { + Switch(source: self.asObservable()) + } +} + +private class SwitchSink + : Sink + , ObserverType where Source.Element == Observer.Element { + typealias Element = SourceType + + private let subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + private let innerSubscription: SerialDisposable = SerialDisposable() + + let lock = RecursiveLock() + + // state + fileprivate var stopped = false + fileprivate var latest = 0 + fileprivate var hasLatest = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + self.subscriptions.setDisposable(subscription) + return Disposables.create(subscriptions, innerSubscription) + } + + func performMap(_ element: SourceType) throws -> Source { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: Element) -> (Int, Observable)? { + self.lock.lock(); defer { self.lock.unlock() } + + do { + let observable = try self.performMap(element).asObservable() + self.hasLatest = true + self.latest = self.latest &+ 1 + return (self.latest, observable) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + return nil + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let (latest, observable) = self.nextElementArrived(element: element) { + let d = SingleAssignmentDisposable() + self.innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, this: d) + let disposable = observable.subscribe(observer) + d.setDisposable(disposable) + } + case .error(let error): + self.lock.lock(); defer { self.lock.unlock() } + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.lock.lock(); defer { self.lock.unlock() } + self.stopped = true + + self.subscriptions.dispose() + + if !self.hasLatest { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where Source.Element == Observer.Element { + typealias Element = Source.Element + typealias Parent = SwitchSink + + private let parent: Parent + private let id: Int + private let this: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, id: Int, this: Disposable) { + self.parent = parent + self.id = id + self.this = this + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: break + case .error, .completed: + self.this.dispose() + } + + if self.parent.latest != self.id { + return + } + + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.hasLatest = false + if self.parent.stopped { + self.parent.forwardOn(event) + self.parent.dispose() + } + } + } +} + +// MARK: Specializations + +final private class SwitchIdentitySink: SwitchSink + where Observer.Element == Source.Element { + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: Source) throws -> Source { + element + } +} + +final private class MapSwitchSink: SwitchSink where Observer.Element == Source.Element { + typealias Selector = (SourceType) throws -> Source + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> Source { + try self.selector(element) + } +} + +// MARK: Producers + +final private class Switch: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = SwitchIdentitySink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapLatest: Producer { + typealias Selector = (SourceType) throws -> Source + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = MapSwitchSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift new file mode 100644 index 00000000..037bf697 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift @@ -0,0 +1,104 @@ +// +// SwitchIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter other: Observable sequence being returned when source sequence is empty. + - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. + */ + public func ifEmpty(switchTo other: Observable) -> Observable { + SwitchIfEmpty(source: self.asObservable(), ifEmpty: other) + } +} + +final private class SwitchIfEmpty: Producer { + + private let source: Observable + private let ifEmpty: Observable + + init(source: Observable, ifEmpty: Observable) { + self.source = source + self.ifEmpty = ifEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SwitchIfEmptySink(ifEmpty: self.ifEmpty, + observer: observer, + cancel: cancel) + let subscription = sink.run(self.source.asObservable()) + + return (sink: sink, subscription: subscription) + } +} + +final private class SwitchIfEmptySink: Sink + , ObserverType { + typealias Element = Observer.Element + + private let ifEmpty: Observable + private var isEmpty = true + private let ifEmptySubscription = SingleAssignmentDisposable() + + init(ifEmpty: Observable, observer: Observer, cancel: Cancelable) { + self.ifEmpty = ifEmpty + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + return Disposables.create(subscription, ifEmptySubscription) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + guard self.isEmpty else { + self.forwardOn(.completed) + self.dispose() + return + } + let ifEmptySink = SwitchIfEmptySinkIter(parent: self) + self.ifEmptySubscription.setDisposable(self.ifEmpty.subscribe(ifEmptySink)) + } + } +} + +final private class SwitchIfEmptySinkIter + : ObserverType { + typealias Element = Observer.Element + typealias Parent = SwitchIfEmptySink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Take.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Take.swift new file mode 100644 index 00000000..e5746880 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Take.swift @@ -0,0 +1,193 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + public func take(_ count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: self.asObservable(), count: count) + } + } +} + +extension ObservableType { + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + public func take(for duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + @available(*, deprecated, renamed: "take(for:scheduler:)") + public func take(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + take(for: duration, scheduler: scheduler) + } +} + +// count version + +final private class TakeCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeCount + + private let parent: Parent + + private var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining > 0 { + self.remaining -= 1 + + self.forwardOn(.next(value)) + + if self.remaining == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeCount: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == Element { + typealias Parent = TakeTime + + private let parent: Parent + + let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.lock.performLocked { + self.forwardOn(.completed) + self.dispose() + } + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class TakeTime: Producer { + typealias TimeInterval = RxTimeInterval + + fileprivate let source: Observable + fileprivate let duration: TimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/TakeLast.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/TakeLast.swift new file mode 100644 index 00000000..91833872 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/TakeLast.swift @@ -0,0 +1,78 @@ +// +// TakeLast.swift +// RxSwift +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + public func takeLast(_ count: Int) + -> Observable { + TakeLast(source: self.asObservable(), count: count) + } +} + +final private class TakeLastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeLast + + private let parent: Parent + + private var elements: Queue + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.elements = Queue(capacity: parent.count + 1) + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.elements.enqueue(value) + if self.elements.count > self.parent.count { + _ = self.elements.dequeue() + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + for e in self.elements { + self.forwardOn(.next(e)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class TakeLast: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeLastSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift new file mode 100644 index 00000000..6c28d19b --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift @@ -0,0 +1,285 @@ +// +// TakeWithPredicate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + public func take(until other: Source) + -> Observable { + TakeUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter predicate: A function to test each element for a condition. + - parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`. + + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + public func take(until predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + TakeUntilPredicate(source: self.asObservable(), + behavior: behavior, + predicate: predicate) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + public func take(while predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + take(until: { try !predicate($0) }, behavior: behavior) + } + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + @available(*, deprecated, renamed: "take(until:)") + public func takeUntil(_ other: Source) + -> Observable { + take(until: other) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter behavior: Whether or not to include the last element matching the predicate. + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + @available(*, deprecated, renamed: "take(until:behavior:)") + public func takeUntil(_ behavior: TakeBehavior, + predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: predicate, behavior: behavior) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @available(*, deprecated, renamed: "take(while:)") + public func takeWhile(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: { try !predicate($0) }, behavior: .exclusive) + } +} + +/// Behaviors for the take operator family. +public enum TakeBehavior { + /// Include the last element matching the predicate. + case inclusive + + /// Exclude the last element matching the predicate. + case exclusive +} + +// MARK: - TakeUntil Observable +final private class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + fileprivate let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(.completed) + self.parent.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +final private class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = TakeUntil + + private let parent: Parent + + let lock = RecursiveLock() + + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + otherObserver.subscription.setDisposable(otherSubscription) + let sourceSubscription = self.parent.source.subscribe(self) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class TakeUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// MARK: - TakeUntil Predicate +final private class TakeUntilPredicateSink + : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeUntilPredicate + + private let parent: Parent + private var running = true + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + return + } + + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + if self.running { + self.forwardOn(.next(value)) + } else { + if self.parent.behavior == .inclusive { + self.forwardOn(.next(value)) + } + + self.forwardOn(.completed) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeUntilPredicate: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + fileprivate let behavior: TakeBehavior + + init(source: Observable, + behavior: TakeBehavior, + predicate: @escaping Predicate) { + self.source = source + self.behavior = behavior + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilPredicateSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Throttle.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Throttle.swift new file mode 100644 index 00000000..86152a83 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Throttle.swift @@ -0,0 +1,160 @@ +// +// Throttle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) + -> Observable { + Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler) + } +} + +final private class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Throttle + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var lastUnsentElement: Element? + private var lastSentTime: Date? + private var completed: Bool = false + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + let now = self.parent.scheduler.now + + let reducedScheduledTime: RxTimeInterval + + if let lastSendingTime = self.lastSentTime { + reducedScheduledTime = self.parent.dueTime.reduceWithSpanBetween(earlierDate: lastSendingTime, laterDate: now) + } + else { + reducedScheduledTime = .nanoseconds(0) + } + + if reducedScheduledTime.isNow { + self.sendNow(element: element) + return + } + + if !self.parent.latest { + return + } + + let isThereAlreadyInFlightRequest = self.lastUnsentElement != nil + + self.lastUnsentElement = element + + if isThereAlreadyInFlightRequest { + return + } + + let scheduler = self.parent.scheduler + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + + d.setDisposable(scheduler.scheduleRelative(0, dueTime: reducedScheduledTime, action: self.propagate)) + case .error: + self.lastUnsentElement = nil + self.forwardOn(event) + self.dispose() + case .completed: + if self.lastUnsentElement != nil { + self.completed = true + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } + + private func sendNow(element: Element) { + self.lastUnsentElement = nil + self.forwardOn(.next(element)) + // in case element processing takes a while, this should give some more room + self.lastSentTime = self.parent.scheduler.now + } + + func propagate(_: Int) -> Disposable { + self.lock.performLocked { + if let lastUnsentElement = self.lastUnsentElement { + self.sendNow(element: lastUnsentElement) + } + + if self.completed { + self.forwardOn(.completed) + self.dispose() + } + } + + return Disposables.create() + } +} + +final private class Throttle: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let latest: Bool + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, latest: Bool, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.latest = latest + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Timeout.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Timeout.swift new file mode 100644 index 00000000..efcc7917 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Timeout.swift @@ -0,0 +1,151 @@ +// +// Timeout.swift +// RxSwift +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a `RxError.timeout` in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, other: Source, scheduler: SchedulerType) + -> Observable where Element == Source.Element { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} + +final private class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias Element = Observer.Element + typealias Parent = Timeout + + private let parent: Parent + + let lock = RecursiveLock() + + private let timerD = SerialDisposable() + private let subscription = SerialDisposable() + + private var id = 0 + private var switched = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + self.subscription.disposable = original + + self.createTimeoutTimer() + + original.setDisposable(self.parent.source.subscribe(self)) + + return Disposables.create(subscription, timerD) + } + + func on(_ event: Event) { + switch event { + case .next: + var onNextWins = false + + self.lock.performLocked { + onNextWins = !self.switched + if onNextWins { + self.id = self.id &+ 1 + } + } + + if onNextWins { + self.forwardOn(event) + self.createTimeoutTimer() + } + case .error, .completed: + var onEventWins = false + + self.lock.performLocked { + onEventWins = !self.switched + if onEventWins { + self.id = self.id &+ 1 + } + } + + if onEventWins { + self.forwardOn(event) + self.dispose() + } + } + } + + private func createTimeoutTimer() { + if self.timerD.isDisposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + self.timerD.disposable = nextTimer + + let disposeSchedule = self.parent.scheduler.scheduleRelative(self.id, dueTime: self.parent.dueTime) { state in + + var timerWins = false + + self.lock.performLocked { + self.switched = (state == self.id) + timerWins = self.switched + } + + if timerWins { + self.subscription.disposable = self.parent.other.subscribe(self.forwarder()) + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposeSchedule) + } +} + + +final private class Timeout: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let other: Observable + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.other = other + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Timer.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Timer.swift new file mode 100644 index 00000000..30bbdf67 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Timer.swift @@ -0,0 +1,117 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +import Foundation + +final private class TimerSink : Sink where Observer.Element : RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + private let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedulePeriodic(0 as Observer.Element, startAfter: self.parent.dueTime, period: self.parent.period!) { state in + self.lock.performLocked { + self.forwardOn(.next(state)) + return state &+ 1 + } + } + } +} + +final private class TimerOneOffSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRelative(self, dueTime: self.parent.dueTime) { [unowned self] _ -> Disposable in + self.forwardOn(.next(0)) + self.forwardOn(.completed) + self.dispose() + + return Disposables.create() + } + } +} + +final private class Timer: Producer { + fileprivate let scheduler: SchedulerType + fileprivate let dueTime: RxTimeInterval + fileprivate let period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + self.scheduler = scheduler + self.dueTime = dueTime + self.period = period + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + if self.period != nil { + let sink = TimerSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/ToArray.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/ToArray.swift new file mode 100644 index 00000000..76c7370a --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/ToArray.swift @@ -0,0 +1,64 @@ +// +// ToArray.swift +// RxSwift +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts an Observable into a Single that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: A Single sequence containing all the emitted elements as array. + */ + public func toArray() + -> Single<[Element]> { + PrimitiveSequence(raw: ToArray(source: self.asObservable())) + } +} + +final private class ToArraySink: Sink, ObserverType where Observer.Element == [SourceType] { + typealias Parent = ToArray + + let parent: Parent + var list = [SourceType]() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.list.append(value) + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + self.forwardOn(.next(self.list)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class ToArray: Producer<[SourceType]> { + let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [SourceType] { + let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Using.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Using.swift new file mode 100644 index 00000000..ca48d2fb --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Using.swift @@ -0,0 +1,90 @@ +// +// Using.swift +// RxSwift +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + public static func using(_ resourceFactory: @escaping () throws -> Resource, observableFactory: @escaping (Resource) throws -> Observable) -> Observable { + Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +final private class UsingSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = Using + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + var disposable = Disposables.create() + + do { + let resource = try self.parent.resourceFactory() + disposable = resource + let source = try self.parent.observableFactory(resource) + + return Disposables.create( + source.subscribe(self), + disposable + ) + } catch let error { + return Disposables.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(_ event: Event) { + switch event { + case let .next(value): + self.forwardOn(.next(value)) + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Using: Producer { + + typealias Element = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = (ResourceType) throws -> Observable + + fileprivate let resourceFactory: ResourceFactory + fileprivate let observableFactory: ObservableFactory + + + init(resourceFactory: @escaping ResourceFactory, observableFactory: @escaping ObservableFactory) { + self.resourceFactory = resourceFactory + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = UsingSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Window.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Window.swift new file mode 100644 index 00000000..b2a37a5c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Window.swift @@ -0,0 +1,168 @@ +// +// Window.swift +// RxSwift +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + public func window(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class WindowTimeCountSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where Observer.Element == Observable { + typealias Parent = WindowTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + private var subject = PublishSubject() + private var count = 0 + private var windowId = 0 + + private let timerD = SerialDisposable() + private let refCountDisposable: RefCountDisposable + private let groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + _ = self.groupDisposable.insert(self.timerD) + + self.refCountDisposable = RefCountDisposable(disposable: self.groupDisposable) + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + self.createTimer(self.windowId) + + _ = self.groupDisposable.insert(self.parent.source.subscribe(self)) + return self.refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + self.subject.on(.completed) + self.subject = PublishSubject() + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .next(let element): + self.subject.on(.next(element)) + + do { + _ = try incrementChecked(&self.count) + } catch let e { + self.subject.on(.error(e as Swift.Error)) + self.dispose() + } + + if self.count == self.parent.count { + newWindow = true + self.count = 0 + self.windowId += 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .error(let error): + self.subject.on(.error(error)) + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.subject.on(.completed) + self.forwardOn(.completed) + self.dispose() + } + + if newWindow { + self.createTimer(newId) + } + } + + func createTimer(_ windowId: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let scheduledRelative = self.parent.scheduler.scheduleRelative(windowId, dueTime: self.parent.timeSpan) { previousWindowId in + + var newId = 0 + + self.lock.performLocked { + if previousWindowId != self.windowId { + return + } + + self.count = 0 + self.windowId = self.windowId &+ 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return Disposables.create() + } + + nextTimer.setDisposable(scheduledRelative) + } +} + +final private class WindowTimeCount: Producer> { + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Observable { + let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift new file mode 100644 index 00000000..d2868121 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift @@ -0,0 +1,151 @@ +// +// WithLatestFrom.swift +// RxSwift +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} + +final private class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ResultType = Observer.Element + typealias Parent = WithLatestFrom + typealias Element = FirstType + + private let parent: Parent + + fileprivate var lock = RecursiveLock() + fileprivate var latest: SecondType? + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.setDisposable(self.parent.second.subscribe(sndO)) + let fstSubscription = self.parent.first.subscribe(self) + + return Disposables.create(fstSubscription, sndSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + guard let latest = self.latest else { return } + do { + let res = try self.parent.resultSelector(value, latest) + + self.forwardOn(.next(res)) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias ResultType = Observer.Element + typealias Parent = WithLatestFromSink + typealias Element = SecondType + + private let parent: Parent + private let disposable: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposable: Disposable) { + self.parent = parent + self.disposable = disposable + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + self.parent.latest = value + case .completed: + self.disposable.dispose() + case let .error(error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + } +} + +final private class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + fileprivate let first: Observable + fileprivate let second: Observable + fileprivate let resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: @escaping ResultSelector) { + self.first = first + self.second = second + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift new file mode 100644 index 00000000..076f6de8 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift @@ -0,0 +1,58 @@ +// +// WithUnretained.swift +// RxSwift +// +// Created by Vincent Pradeilles on 01/01/2021. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. + - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> Observable { + map { [weak obj] element -> Out in + guard let obj = obj else { throw UnretainedError.failedRetaining } + + return resultSelector(obj, element) + } + .catch{ error -> Observable in + guard let unretainedError = error as? UnretainedError, + unretainedError == .failedRetaining else { + return .error(error) + } + + return .empty() + } + } + + + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the sequence will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained(_ obj: Object) -> Observable<(Object, Element)> { + return withUnretained(obj) { ($0, $1) } + } +} + +private enum UnretainedError: Swift.Error { + case failedRetaining +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift new file mode 100644 index 00000000..2d7f8877 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift @@ -0,0 +1,168 @@ +// +// Zip+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + ZipCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + ZipCollectionType(sources: collection, resultSelector: { $0 }) + } + +} + +final private class ZipCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = ZipCollectionType + typealias SourceElement = Collection.Element.Element + + private let parent: Parent + + private let lock = RecursiveLock() + + // state + private var numberOfValues = 0 + private var values: [Queue] + private var isDone: [Bool] + private var numberOfDone = 0 + private var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [Queue](repeating: Queue(capacity: 4), count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + self.values[atIndex].enqueue(element) + + if self.values[atIndex].count == 1 { + self.numberOfValues += 1 + } + + if self.numberOfValues < self.parent.count { + if self.numberOfDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(self.parent.count) + + // recalculate number of values + self.numberOfValues = 0 + + for i in 0 ..< self.values.count { + arguments.append(self.values[i].dequeue()!) + if !self.values[i].isEmpty { + self.numberOfValues += 1 + } + } + + let result = try self.parent.resultSelector(arguments) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + self.subscriptions[j].setDisposable(disposable) + j += 1 + } + + if self.parent.sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(subscriptions) + } +} + +final private class ZipCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift new file mode 100644 index 00000000..b6d876d1 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift @@ -0,0 +1,934 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class ZipSink2_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip2 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!) + } +} + +final class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class ZipSink3_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip3 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!) + } +} + +final class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class ZipSink4_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip4 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!) + } +} + +final class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class ZipSink5_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip5 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!) + } +} + +final class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class ZipSink6_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip6 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!) + } +} + +final class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class ZipSink7_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip7 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!) + } +} + +final class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class ZipSink8_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip8 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + var values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + case 7: return !self.values8.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: self.lock, parent: self, index: 7, setNextValue: { self.values8.enqueue($0) }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!, self.values8.dequeue()!) + } +} + +final class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip.swift b/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip.swift new file mode 100644 index 00000000..328a40ef --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observables/Zip.swift @@ -0,0 +1,135 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ZipSinkProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = Observer.Element + + let arity: Int + + let lock = RecursiveLock() + + // state + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.isDone = [Bool](repeating: false, count: arity) + self.arity = arity + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func hasElements(_ index: Int) -> Bool { + rxAbstractMethod() + } + + func next(_ index: Int) { + var hasValueAll = true + + for i in 0 ..< self.arity { + if !self.hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + self.isDone[index] = true + + var allDone = true + + for done in self.isDone where !done { + allDone = false + break + } + + if allDone { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private var parent: ZipSinkProtocol? + + let lock: RecursiveLock + + // state + private let index: Int + private let this: Disposable + private let setNextValue: ValueSetter + + init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setNextValue = setNextValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + if self.parent != nil { + switch event { + case .next: + break + case .error: + self.this.dispose() + case .completed: + self.this.dispose() + } + } + + if let parent = self.parent { + switch event { + case .next(let value): + self.setNextValue(value) + parent.next(self.index) + case .error(let error): + parent.fail(error) + case .completed: + parent.done(self.index) + } + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/ObserverType.swift b/ChatBot/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 00000000..b7a66480 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/ObserverType.swift @@ -0,0 +1,40 @@ +// +// ObserverType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Supports push-style iteration over an observable sequence. +public protocol ObserverType { + /// The type of elements in sequence that observer can observe. + associatedtype Element + + /// Notify observer about sequence event. + /// + /// - parameter event: Event that occurred. + func on(_ event: Event) +} + +/// Convenience API extensions to provide alternate next, error, completed events +extension ObserverType { + + /// Convenience method equivalent to `on(.next(element: Element))` + /// + /// - parameter element: Next element to send to observer(s) + public func onNext(_ element: Element) { + self.on(.next(element)) + } + + /// Convenience method equivalent to `on(.completed)` + public func onCompleted() { + self.on(.completed) + } + + /// Convenience method equivalent to `on(.error(Swift.Error))` + /// - parameter error: Swift.Error to send to observer(s) + public func onError(_ error: Swift.Error) { + self.on(.error(error)) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/ChatBot/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 00000000..cbb42dc8 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,30 @@ +// +// AnonymousObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AnonymousObserver: ObserverBase { + typealias EventHandler = (Event) -> Void + + private let eventHandler : EventHandler + + init(_ eventHandler: @escaping EventHandler) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.eventHandler = eventHandler + } + + override func onCore(_ event: Event) { + self.eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/ChatBot/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 00000000..48e09868 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,32 @@ +// +// ObserverBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class ObserverBase : Disposable, ObserverType { + private let isStopped = AtomicInt(0) + + func on(_ event: Event) { + switch event { + case .next: + if load(self.isStopped) == 0 { + self.onCore(event) + } + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.onCore(event) + } + } + } + + func onCore(_ event: Event) { + rxAbstractMethod() + } + + func dispose() { + fetchOr(self.isStopped, 1) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/ChatBot/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 00000000..fd527001 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,151 @@ +// +// TailRecursiveSink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum TailRecursiveSinkCommand { + case moveNext + case dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Value = TailRecursiveSinkCommand + typealias Element = Observer.Element + typealias SequenceGenerator = (generator: Sequence.Iterator, remaining: IntMax?) + + var generators: [SequenceGenerator] = [] + var disposed = false + var subscription = SerialDisposable() + + // this is thread safe object + var gate = AsyncLock>>() + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ sources: SequenceGenerator) -> Disposable { + self.generators.append(sources) + + self.schedule(.moveNext) + + return self.subscription + } + + func invoke(_ command: TailRecursiveSinkCommand) { + switch command { + case .dispose: + self.disposeCommand() + case .moveNext: + self.moveNextCommand() + } + } + + // simple implementation for now + func schedule(_ command: TailRecursiveSinkCommand) { + self.gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + self.forwardOn(.completed) + self.dispose() + } + + func extract(_ observable: Observable) -> SequenceGenerator? { + rxAbstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? + + repeat { + guard let (g, left) = self.generators.last else { + break + } + + if self.isDisposed { + return + } + + self.generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + self.generators.append((e, knownOriginalLeft - 1)) + } + } + else { + self.generators.append((e, nil)) + } + + let nextGenerator = self.extract(nextCandidate) + + if let nextGenerator = nextGenerator { + self.generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < self.generators.count { + maxTailRecursiveSinkStackSize = self.generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + guard let existingNext = next else { + self.done() + return + } + + let disposable = SingleAssignmentDisposable() + self.subscription.disposable = disposable + disposable.setDisposable(self.subscribeToNext(existingNext)) + } + + func subscribeToNext(_ source: Observable) -> Disposable { + rxAbstractMethod() + } + + func disposeCommand() { + self.disposed = true + self.generators.removeAll(keepingCapacity: false) + } + + override func dispose() { + super.dispose() + + self.subscription.dispose() + self.gate.dispose() + + self.schedule(.dispose) + } +} + diff --git a/ChatBot/Pods/RxSwift/RxSwift/Reactive.swift b/ChatBot/Pods/RxSwift/RxSwift/Reactive.swift new file mode 100644 index 00000000..1bf390dc --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Reactive.swift @@ -0,0 +1,80 @@ +// +// Reactive.swift +// RxSwift +// +// Created by Yury Korolev on 5/2/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/** + Use `Reactive` proxy as customization point for constrained protocol extensions. + + General pattern would be: + + // 1. Extend Reactive protocol with constrain on Base + // Read as: Reactive Extension where Base is a SomeType + extension Reactive where Base: SomeType { + // 2. Put any specific reactive extension for SomeType here + } + + With this approach we can have more specialized methods and properties using + `Base` and not just specialized on common base type. + + `Binder`s are also automatically synthesized using `@dynamicMemberLookup` for writable reference properties of the reactive base. + */ + +@dynamicMemberLookup +public struct Reactive { + /// Base object to extend. + public let base: Base + + /// Creates extensions with base object. + /// + /// - parameter base: Base object. + public init(_ base: Base) { + self.base = base + } + + /// Automatically synthesized binder for a key path between the reactive + /// base and one of its properties + public subscript(dynamicMember keyPath: ReferenceWritableKeyPath) -> Binder where Base: AnyObject { + Binder(self.base) { base, value in + base[keyPath: keyPath] = value + } + } +} + +/// A type that has reactive extensions. +public protocol ReactiveCompatible { + /// Extended type + associatedtype ReactiveBase + + /// Reactive extensions. + static var rx: Reactive.Type { get set } + + /// Reactive extensions. + var rx: Reactive { get set } +} + +extension ReactiveCompatible { + /// Reactive extensions. + public static var rx: Reactive.Type { + get { Reactive.self } + // this enables using Reactive to "mutate" base type + // swiftlint:disable:next unused_setter_value + set { } + } + + /// Reactive extensions. + public var rx: Reactive { + get { Reactive(self) } + // this enables using Reactive to "mutate" base object + // swiftlint:disable:next unused_setter_value + set { } + } +} + +import Foundation + +/// Extend NSObject with `rx` proxy. +extension NSObject: ReactiveCompatible { } diff --git a/ChatBot/Pods/RxSwift/RxSwift/Rx.swift b/ChatBot/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 00000000..bcdd2794 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Rx.swift @@ -0,0 +1,142 @@ +// +// Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if TRACE_RESOURCES + private let resourceCount = AtomicInt(0) + + /// Resource utilization information + public struct Resources { + /// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. + public static var total: Int32 { + load(resourceCount) + } + + /// Increments `Resources.total` resource count. + /// + /// - returns: New resource count + public static func incrementTotal() -> Int32 { + increment(resourceCount) + } + + /// Decrements `Resources.total` resource count + /// + /// - returns: New resource count + public static func decrementTotal() -> Int32 { + decrement(resourceCount) + } + } +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError("Abstract method", file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +func incrementChecked(_ i: inout Int) throws -> Int { + if i == Int.max { + throw RxError.overflow + } + defer { i += 1 } + return i +} + +func decrementChecked(_ i: inout Int) throws -> Int { + if i == Int.min { + throw RxError.overflow + } + defer { i -= 1 } + return i +} + +#if DEBUG + import Foundation + final class SynchronizationTracker { + private let lock = RecursiveLock() + + public enum SynchronizationErrorMessages: String { + case variable = "Two different threads are trying to assign the same `Variable.value` unsynchronized.\n This is undefined behavior because the end result (variable value) is nondeterministic and depends on the \n operating system thread scheduler. This will cause random behavior of your program.\n" + case `default` = "Two different unsynchronized threads are trying to send some event simultaneously.\n This is undefined behavior because the ordering of the effects caused by these events is nondeterministic and depends on the \n operating system thread scheduler. This will result in a random behavior of your program.\n" + } + + private var threads = [UnsafeMutableRawPointer: Int]() + + private func synchronizationError(_ message: String) { + #if FATAL_SYNCHRONIZATION + rxFatalError(message) + #else + print(message) + #endif + } + + func register(synchronizationErrorMessage: SynchronizationErrorMessages) { + self.lock.lock(); defer { self.lock.unlock() } + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + let count = (self.threads[pointer] ?? 0) + 1 + + if count > 1 { + self.synchronizationError( + "⚠️ Reentrancy anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code,\n" + + " or that the system is not behaving in the expected way.\n" + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by enqueuing sequence events in some other way.\n" + ) + } + + self.threads[pointer] = count + + if self.threads.count > 1 { + self.synchronizationError( + "⚠️ Synchronization anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: " + synchronizationErrorMessage.rawValue + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by synchronizing sequence events in some other way.\n" + ) + } + } + + func unregister() { + self.lock.performLocked { + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + self.threads[pointer] = (self.threads[pointer] ?? 1) - 1 + if self.threads[pointer] == 0 { + self.threads[pointer] = nil + } + } + } + } + +#endif + +/// RxSwift global hooks +public enum Hooks { + + // Should capture call stack + public static var recordCallStackOnError: Bool = false + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/RxMutableBox.swift b/ChatBot/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 00000000..73476c36 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/RxMutableBox.swift @@ -0,0 +1,53 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) +/// As Swift 5 was released, A patch to `Thread` for Linux +/// changed `threadDictionary` to a `NSMutableDictionary` instead of +/// a `Dictionary`: https://github.com/apple/swift-corelibs-foundation/pull/1762/files +/// +/// This means that on Linux specifically, `RxMutableBox` must be a `NSObject` +/// or it won't be possible to store it in `Thread.threadDictionary`. +/// +/// For more information, read the discussion at: +/// https://github.com/ReactiveX/RxSwift/issues/1911#issuecomment-479723298 +import Foundation + +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: NSObject { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} +#else +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: CustomDebugStringConvertible { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /// - returns: Box description. + var debugDescription: String { + "MutatingBox(\(self.value))" + } +} +#endif diff --git a/ChatBot/Pods/RxSwift/RxSwift/SchedulerType.swift b/ChatBot/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 00000000..6c8fe4a3 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/SchedulerType.swift @@ -0,0 +1,71 @@ +// +// SchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +// Type that represents time interval in the context of RxSwift. +public typealias RxTimeInterval = DispatchTimeInterval + +/// Type that represents absolute time in the context of RxSwift. +public typealias RxTime = Date + +/// Represents an object that schedules units of work. +public protocol SchedulerType: ImmediateSchedulerType { + + /// - returns: Current time. + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(_ state: State, dueTime: RxTimeInterval, action: @escaping (State, AnyRecursiveScheduler) -> Void) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return Disposables.create(with: scheduler.dispose) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 00000000..02c47c91 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,82 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. +/// +/// This scheduler is suitable when some work needs to be performed in background. +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /// Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + /// + /// - parameter queue: Target dispatch queue. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public init(queue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: queue, leeway: leeway) + } + + /// Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + /// + /// - parameter qos: Target global dispatch queue, by quality of service class. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public convenience init(qos: DispatchQoS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue( + label: "rxswift.queue.\(qos)", + qos: qos, + attributes: [DispatchQueue.Attributes.concurrent], + target: nil), + leeway: leeway + ) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 00000000..c438d7d4 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,87 @@ +// +// ConcurrentMainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + private let mainScheduler: MainScheduler + private let mainQueue: DispatchQueue + + /// - returns: Current time. + public var now: Date { + self.mainScheduler.now as Date + } + + private init(mainScheduler: MainScheduler) { + self.mainQueue = DispatchQueue.main + self.mainScheduler = mainScheduler + } + + /// Singleton instance of `ConcurrentMainScheduler` + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if DispatchQueue.isMain { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if cancel.isDisposed { + return + } + + cancel.setDisposable(action(state)) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 00000000..16a7dd32 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,131 @@ +// +// CurrentThreadScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +#if os(Linux) + fileprivate enum CurrentThreadSchedulerQueueKey { + fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue" + } +#else + private class CurrentThreadSchedulerQueueKey: NSObject, NSCopying { + static let instance = CurrentThreadSchedulerQueueKey() + private override init() { + super.init() + } + + override var hash: Int { + return 0 + } + + public func copy(with zone: NSZone? = nil) -> Any { + return self + } + } +#endif + +/// Represents an object that schedules units of work on the current thread. +/// +/// This is the default scheduler for operators that generate elements. +/// +/// This scheduler is also sometimes called `trampoline scheduler`. +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /// The singleton instance of the current thread scheduler. + public static let instance = CurrentThreadScheduler() + + private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in + let key = UnsafeMutablePointer.allocate(capacity: 1) + defer { key.deallocate() } + + guard pthread_key_create(key, nil) == 0 else { + rxFatalError("isScheduleRequired key creation failed") + } + + return key.pointee + }() + + private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in + return UnsafeRawPointer(UnsafeMutablePointer.allocate(capacity: 1)) + }() + + static var queue : ScheduleQueue? { + get { + return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance) + } + set { + Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance) + } + } + + /// Gets a value that indicates whether the caller must call a `schedule` method. + public static private(set) var isScheduleRequired: Bool { + get { + return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil + } + set(isScheduleRequired) { + if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 { + rxFatalError("pthread_setspecific failed") + } + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.isDisposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + return scheduledItem + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 00000000..fede60e6 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,22 @@ +// +// HistoricalScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Provides a virtual time scheduler that uses `Date` for absolute time and `NSTimeInterval` for relative time. +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = Date(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 00000000..a8fae8a4 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,67 @@ +// +// HistoricalSchedulerTimeConverter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Converts historical virtual time into real time. +/// +/// Since historical virtual time is also measured in `Date`, this converter is identity function. +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + public typealias VirtualTimeUnit = RxTime + + /// Virtual time unit used to represent differences of virtual times. + public typealias VirtualTimeIntervalUnit = TimeInterval + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime { + virtualTime + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit { + time + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval { + virtualTimeInterval + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit { + timeInterval + } + + /** + Offsets `Date` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + time.addingTimeInterval(offset) + } + + /// Compares two `Date`s. + public func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs as Date) { + case .orderedAscending: + return .lessThan + case .orderedSame: + return .equal + case .orderedDescending: + return .greaterThan + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift new file mode 100644 index 00000000..53f148dc --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift @@ -0,0 +1,97 @@ +// +// DispatchQueueConfiguration.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/23/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +struct DispatchQueueConfiguration { + let queue: DispatchQueue + let leeway: DispatchTimeInterval +} + +extension DispatchQueueConfiguration { + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + self.queue.async { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + return cancel + } + + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let deadline = DispatchTime.now() + dueTime + + let compositeDisposable = CompositeDisposable() + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: deadline, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceptual change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if compositeDisposable.isDisposed { + return + } + _ = compositeDisposable.insert(action(state)) + cancelTimer.dispose() + }) + timer.resume() + + _ = compositeDisposable.insert(cancelTimer) + + return compositeDisposable + } + + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let initial = DispatchTime.now() + startAfter + + var timerState = state + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: initial, repeating: period, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceptual change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if cancelTimer.isDisposed { + return + } + timerState = action(timerState) + }) + timer.resume() + + return cancelTimer + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 00000000..0e150561 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,22 @@ +// +// InvocableScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct InvocableScheduledItem : InvocableType { + + let invocable: I + let state: I.Value + + init(invocable: I, state: I.Value) { + self.invocable = invocable + self.state = state + } + + func invoke() { + self.invocable.invoke(self.state) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 00000000..0dba4336 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,17 @@ +// +// InvocableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(_ value: Value) +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 00000000..3d790d7a --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,35 @@ +// +// ScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = (T) -> Disposable + + private let action: Action + private let state: T + + private let disposable = SingleAssignmentDisposable() + + var isDisposed: Bool { + self.disposable.isDisposed + } + + init(action: @escaping Action, state: T) { + self.action = action + self.state = state + } + + func invoke() { + self.disposable.setDisposable(self.action(self.state)) + } + + func dispose() { + self.disposable.dispose() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 00000000..d2b16cab --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,13 @@ +// +// ScheduledItemType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 00000000..f6a507f3 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,80 @@ +// +// MainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +#if !os(Linux) + import Foundation +#endif + +/** +Abstracts work that needs to be performed on `DispatchQueue.main`. In case `schedule` methods are called from `DispatchQueue.main`, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let mainQueue: DispatchQueue + + let numberEnqueued = AtomicInt(0) + + /// Initializes new instance of `MainScheduler`. + public init() { + self.mainQueue = DispatchQueue.main + super.init(serialQueue: self.mainQueue) + } + + /// Singleton instance of `MainScheduler` + public static let instance = MainScheduler() + + /// Singleton instance of `MainScheduler` that always schedules work asynchronously + /// and doesn't perform optimizations for calls scheduled from main queue. + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main) + + /// In case this method is called on a background thread it will throw an exception. + public static func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !DispatchQueue.isMain { + rxFatalError(errorMessage ?? "Executing on background thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + /// In case this method is running on a background thread it will throw an exception. + public static func ensureRunningOnMainThread(errorMessage: String? = nil) { + #if !os(Linux) // isMainThread is not implemented in Linux Foundation + guard Thread.isMainThread else { + rxFatalError(errorMessage ?? "Running on background thread.") + } + #endif + } + + override func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let previousNumberEnqueued = increment(self.numberEnqueued) + + if DispatchQueue.isMain && previousNumberEnqueued == 0 { + let disposable = action(state) + decrement(self.numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if !cancel.isDisposed { + cancel.setDisposable(action(state)) + } + + decrement(self.numberEnqueued) + } + + return cancel + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 00000000..f0ad3d3c --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,54 @@ +// +// OperationQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `NSOperationQueue`. +/// +/// This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: OperationQueue + public let queuePriority: Operation.QueuePriority + + /// Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + /// + /// - parameter operationQueue: Operation queue targeted to perform work on. + /// - parameter queuePriority: Queue priority which will be assigned to new operations. + public init(operationQueue: OperationQueue, queuePriority: Operation.QueuePriority = .normal) { + self.operationQueue = operationQueue + self.queuePriority = queuePriority + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + let operation = BlockOperation { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + operation.queuePriority = self.queuePriority + + self.operationQueue.addOperation(operation) + + return cancel + } + +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 00000000..0ee78cd1 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,220 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private enum ScheduleState { + case initial + case added(CompositeDisposable.DisposeKey) + case done +} + +/// Type erased recursive scheduler. +final class AnyRecursiveScheduler { + + typealias Action = (State, AnyRecursiveScheduler) -> Void + + private let lock = RecursiveLock() + + // state + private let group = CompositeDisposable() + + private var scheduler: SchedulerType + private var action: Action? + + init(scheduler: SchedulerType, action: @escaping Action) { + self.action = action + self.scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(_ state: State, dueTime: RxTimeInterval) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.scheduleRelative(state, dueTime: dueTime) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} + +/// Type erased recursive scheduler. +final class RecursiveImmediateScheduler { + typealias Action = (_ state: State, _ recurse: (State) -> Void) -> Void + + private var lock = SpinLock() + private let group = CompositeDisposable() + + private var action: Action? + private let scheduler: ImmediateSchedulerType + + init(action: @escaping Action, scheduler: ImmediateSchedulerType) { + self.action = action + self.scheduler = scheduler + } + + // immediate scheduling + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self.schedule) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 00000000..cab2bc8b --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,61 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum SchedulePeriodicRecursiveCommand { + case tick + case dispatchStart +} + +final class SchedulePeriodicRecursive { + typealias RecursiveAction = (State) -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let scheduler: SchedulerType + private let startAfter: RxTimeInterval + private let period: RxTimeInterval + private let action: RecursiveAction + + private var state: State + private let pendingTickCount = AtomicInt(0) + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) { + self.scheduler = scheduler + self.startAfter = startAfter + self.period = period + self.action = action + self.state = state + } + + func start() -> Disposable { + self.scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: self.startAfter, action: self.tick) + } + + func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .tick: + scheduler.schedule(.tick, dueTime: self.period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately. + // Else work will be scheduled after previous enqueued work completes. + if increment(self.pendingTickCount) == 0 { + self.tick(.dispatchStart, scheduler: scheduler) + } + + case .dispatchStart: + self.state = self.action(self.state) + // Start work and schedule check is this last batch of work + if decrement(self.pendingTickCount) > 1 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart) + } + } + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 00000000..bb0013c8 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,131 @@ +// +// SerialDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + /// - returns: Current time. + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps `serialQueue`. + + - parameter serialQueue: Target dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + // Swift 3.0 IUO + let serialQueue = DispatchQueue(label: internalSerialQueueName, + attributes: [], + target: queue) + self.init(serialQueue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps one of the global concurrent dispatch queues. + + - parameter qos: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + @available(macOS 10.10, *) + public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.scheduleInternal(state, action: action) + } + + func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 00000000..34151f70 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,97 @@ +// +// VirtualTimeConverterType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Parametrization for virtual time used by `VirtualTimeScheduler`s. +public protocol VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + associatedtype VirtualTimeUnit + + /// Virtual time unit used to represent differences of virtual times. + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `Date`. + - returns: `Date` corresponding to virtual time. + */ + func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `Date` to convert to virtual time. + - returns: Virtual time corresponding to `Date`. + */ + func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. + - returns: `NSTimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval + + /** + Converts from `NSTimeInterval` to virtual time interval. + + - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /// lhs < rhs. + case lessThan + /// lhs == rhs. + case equal + /// lhs > rhs. + case greaterThan +} + +extension VirtualTimeComparison { + /// lhs < rhs. + var lessThen: Bool { + self == .lessThan + } + + /// lhs > rhs + var greaterThan: Bool { + self == .greaterThan + } + + /// lhs == rhs + var equal: Bool { + self == .equal + } +} diff --git a/ChatBot/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 00000000..e74d5be6 --- /dev/null +++ b/ChatBot/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,267 @@ +// +// VirtualTimeScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for virtual time schedulers using a priority queue for scheduled items. +open class VirtualTimeScheduler + : SchedulerType { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var running : Bool + + private var currentClock: VirtualTime + + private var schedulerQueue : PriorityQueue> + private var converter: Converter + + private var nextId = 0 + + /// - returns: Current time. + public var now: RxTime { + self.converter.convertFromVirtualTime(self.clock) + } + + /// - returns: Scheduler's absolute time clock value. + public var clock: VirtualTime { + self.currentClock + } + + /// Creates a new virtual time scheduler. + /// + /// - parameter initialClock: Initial value for the clock. + public init(initialClock: VirtualTime, converter: Converter) { + self.currentClock = initialClock + self.running = false + self.converter = converter + self.schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .lessThan: + return true + case .equal: + return $0.id < $1.id + case .greaterThan: + return false + } + }, isEqual: { $0 === $1 }) + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: .microseconds(0)) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.now.addingDispatchInterval(dueTime) + let absoluteTime = self.converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return self.scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.converter.offsetVirtualTime(self.clock, offset: dueTime) + return self.scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(_ state: StateType, time: VirtualTime, action: @escaping (StateType) -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + return action(state) + }, time: time, id: self.nextId) + + self.nextId += 1 + + self.schedulerQueue.enqueue(item) + + _ = compositeDisposable.insert(item) + + return compositeDisposable + } + + /// Adjusts time of scheduling before adding item to schedule queue. + open func adjustScheduledTime(_ time: VirtualTime) -> VirtualTime { + time + } + + /// Starts the virtual time scheduler. + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + return + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = self.schedulerQueue.peek() { + if front.isDisposed { + self.schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /// Advances the scheduler's clock to the specified time, running all work till that point. + /// + /// - parameter virtualTime: Absolute time to advance the scheduler's clock to. + public func advanceTo(_ virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + fatalError("Scheduler is already running") + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.currentClock = virtualTime + self.running = false + } + + /// Advances the scheduler's clock by the specified relative time. + public func sleep(_ virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = self.converter.offsetVirtualTime(self.clock, offset: virtualInterval) + if self.converter.compareVirtualTime(sleepTo, self.clock).lessThen { + fatalError("Can't sleep to past.") + } + + self.currentClock = sleepTo + } + + /// Stops the virtual time scheduler. + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + self.running = false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler: CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + self.schedulerQueue.debugDescription + } +} + +final class VirtualSchedulerItem