1// Copyright 2018-present 650 Industries. All rights reserved.
2
3#import <objc/runtime.h>
4
5#import <React/RCTLog.h>
6#import <React/RCTUIManager.h>
7#import <React/RCTComponentData.h>
8#import <React/RCTModuleData.h>
9#import <React/RCTEventDispatcherProtocol.h>
10
11#import <jsi/jsi.h>
12
13#import <ExpoModulesCore/EXNativeModulesProxy.h>
14#import <ExpoModulesCore/EXEventEmitter.h>
15#import <ExpoModulesCore/EXViewManager.h>
16#import <ExpoModulesCore/EXViewManagerAdapter.h>
17#import <ExpoModulesCore/EXViewManagerAdapterClassesRegistry.h>
18#import <ExpoModulesCore/EXModuleRegistryProvider.h>
19#import <ExpoModulesCore/EXReactNativeEventEmitter.h>
20#import <ExpoModulesCore/EXJSIInstaller.h>
21#import <ExpoModulesCore/Swift.h>
22
23static const NSString *exportedMethodsNamesKeyPath = @"exportedMethods";
24static const NSString *viewManagersMetadataKeyPath = @"viewManagersMetadata";
25static const NSString *exportedConstantsKeyPath = @"modulesConstants";
26
27static const NSString *methodInfoKeyKey = @"key";
28static const NSString *methodInfoNameKey = @"name";
29static const NSString *methodInfoArgumentsCountKey = @"argumentsCount";
30
31@interface RCTBridge (RegisterAdditionalModuleClasses)
32
33- (NSArray<RCTModuleData *> *)registerModulesForClasses:(NSArray<Class> *)moduleClasses;
34- (void)registerAdditionalModuleClasses:(NSArray<Class> *)modules;
35
36@end
37
38@interface RCTBridge (JSIRuntime)
39
40- (void *)runtime;
41
42@end
43
44@interface EXNativeModulesProxy ()
45
46@property (nonatomic, strong) NSRegularExpression *regexp;
47@property (nonatomic, strong) EXModuleRegistry *exModuleRegistry;
48@property (nonatomic, strong) NSMutableDictionary<const NSString *, NSMutableDictionary<NSString *, NSNumber *> *> *exportedMethodsKeys;
49@property (nonatomic, strong) NSMutableDictionary<const NSString *, NSMutableDictionary<NSNumber *, NSString *> *> *exportedMethodsReverseKeys;
50@property (nonatomic) BOOL ownsModuleRegistry;
51
52@end
53
54@implementation EXNativeModulesProxy {
55  __weak EXAppContext * _Nullable _appContext;
56}
57
58@synthesize bridge = _bridge;
59
60RCT_EXPORT_MODULE(NativeUnimoduleProxy)
61
62/**
63 The designated initializer. It's used in the old setup where the native modules proxy
64 is registered in `extraModulesForBridge:` by the bridge delegate.
65 */
66- (instancetype)initWithModuleRegistry:(nullable EXModuleRegistry *)moduleRegistry
67{
68  if (self = [super init]) {
69    _exModuleRegistry = moduleRegistry != nil ? moduleRegistry : [[EXModuleRegistryProvider new] moduleRegistry];
70    _exportedMethodsKeys = [NSMutableDictionary dictionary];
71    _exportedMethodsReverseKeys = [NSMutableDictionary dictionary];
72    _ownsModuleRegistry = moduleRegistry == nil;
73  }
74  return self;
75}
76
77/**
78 Convenience initializer used by React Native in the new setup, where the modules are registered automatically.
79 */
80- (instancetype)init
81{
82  return [self initWithModuleRegistry:nil];
83}
84
85# pragma mark - React API
86
87+ (BOOL)requiresMainQueueSetup
88{
89  return YES;
90}
91
92- (NSDictionary *)constantsToExport
93{
94  NSMutableDictionary <NSString *, id> *exportedModulesConstants = [NSMutableDictionary dictionary];
95  // Grab all the constants exported by modules
96  for (EXExportedModule *exportedModule in [_exModuleRegistry getAllExportedModules]) {
97    @try {
98      exportedModulesConstants[[[exportedModule class] exportedModuleName]] = [exportedModule constantsToExport] ?: [NSNull null];
99    } @catch (NSException *exception) {
100      continue;
101    }
102  }
103  [exportedModulesConstants addEntriesFromDictionary:[_appContext exportedModulesConstants]];
104
105  // Also add `exportedMethodsNames`
106  NSMutableDictionary<const NSString *, NSMutableArray<NSMutableDictionary<const NSString *, id> *> *> *exportedMethodsNamesAccumulator = [NSMutableDictionary dictionary];
107  for (EXExportedModule *exportedModule in [_exModuleRegistry getAllExportedModules]) {
108    const NSString *exportedModuleName = [[exportedModule class] exportedModuleName];
109    exportedMethodsNamesAccumulator[exportedModuleName] = [NSMutableArray array];
110    [[exportedModule getExportedMethods] enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull exportedName, NSString * _Nonnull selectorName, BOOL * _Nonnull stop) {
111      NSMutableDictionary<const NSString *, id> *methodInfo = [NSMutableDictionary dictionaryWithDictionary:@{
112                                                                                                              methodInfoNameKey: exportedName,
113                                                                                                              // - 3 is for resolver and rejecter of the promise and the last, empty component
114                                                                                                              methodInfoArgumentsCountKey: @([[selectorName componentsSeparatedByString:@":"] count] - 3)
115                                                                                                              }];
116      [exportedMethodsNamesAccumulator[exportedModuleName] addObject:methodInfo];
117    }];
118    [self assignExportedMethodsKeys:exportedMethodsNamesAccumulator[exportedModuleName] forModuleName:exportedModuleName];
119  }
120
121  // Add entries from Swift modules
122  [exportedMethodsNamesAccumulator addEntriesFromDictionary:[_appContext exportedFunctionNames]];
123
124  // Also, add `viewManagersMetadata` for sanity check and testing purposes -- with names we know what managers to mock on UIManager
125  NSArray<EXViewManager *> *viewManagers = [_exModuleRegistry getAllViewManagers];
126  NSMutableDictionary<NSString *, NSDictionary *> *viewManagersMetadata = [[NSMutableDictionary alloc] initWithCapacity:[viewManagers count]];
127
128  for (EXViewManager *viewManager in viewManagers) {
129    viewManagersMetadata[viewManager.viewName] = @{
130      @"propsNames": [[viewManager getPropsNames] allKeys]
131    };
132  }
133
134  // Add entries from Swift view managers
135  [viewManagersMetadata addEntriesFromDictionary:[_appContext viewManagersMetadata]];
136
137  NSMutableDictionary <NSString *, id> *constantsAccumulator = [NSMutableDictionary dictionary];
138  constantsAccumulator[viewManagersMetadataKeyPath] = viewManagersMetadata;
139  constantsAccumulator[exportedConstantsKeyPath] = exportedModulesConstants;
140  constantsAccumulator[exportedMethodsNamesKeyPath] = exportedMethodsNamesAccumulator;
141
142  return constantsAccumulator;
143}
144
145- (void)setBridge:(RCTBridge *)bridge
146{
147  _appContext = [(ExpoBridgeModule *)[bridge moduleForClass:ExpoBridgeModule.class] appContext];
148  [_appContext setLegacyModuleRegistry:_exModuleRegistry];
149
150  if (!_bridge) {
151    // The `setBridge` can be called during module setup or after. Registering more modules
152    // during setup causes a crash due to mutating `_moduleDataByID` while it's being enumerated.
153    // In that case we register them asynchronously.
154    if ([[bridge valueForKey:@"_moduleSetupComplete"] boolValue]) {
155      [self registerExpoModulesInBridge:bridge];
156    } else {
157      dispatch_async(dispatch_get_main_queue(), ^{
158        [self registerExpoModulesInBridge:bridge];
159      });
160    }
161  }
162  _bridge = bridge;
163}
164
165RCT_EXPORT_METHOD(callMethod:(NSString *)moduleName methodNameOrKey:(id)methodNameOrKey arguments:(NSArray *)arguments resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
166{
167  // Backwards compatibility for the new architecture
168  if ([_appContext hasModule:moduleName]) {
169    [_appContext callFunction:methodNameOrKey onModule:moduleName withArgs:arguments resolve:resolve reject:reject];
170    return;
171  }
172
173  EXExportedModule *module = [_exModuleRegistry getExportedModuleForName:moduleName];
174  if (module == nil) {
175    NSString *reason = [NSString stringWithFormat:@"No exported module was found for name '%@'. Are you sure all the packages are linked correctly?", moduleName];
176    reject(@"E_NO_MODULE", reason, nil);
177    return;
178  }
179
180  if (!methodNameOrKey) {
181    reject(@"E_NO_METHOD", @"No method key or name provided", nil);
182    return;
183  }
184
185  NSString *methodName;
186  if ([methodNameOrKey isKindOfClass:[NSString class]]) {
187    methodName = (NSString *)methodNameOrKey;
188  } else if ([methodNameOrKey isKindOfClass:[NSNumber class]]) {
189    methodName = _exportedMethodsReverseKeys[moduleName][(NSNumber *)methodNameOrKey];
190  } else {
191    reject(@"E_INV_MKEY", @"Method key is neither a String nor an Integer -- don't know how to map it to method name.", nil);
192    return;
193  }
194
195  dispatch_async([module methodQueue], ^{
196    @try {
197      [module callExportedMethod:methodName withArguments:arguments resolver:resolve rejecter:reject];
198    } @catch (NSException *e) {
199      NSString *message = [NSString stringWithFormat:@"An exception was thrown while calling `%@.%@` with arguments `%@`: %@", moduleName, methodName, arguments, e];
200      reject(@"E_EXC", message, nil);
201    }
202  });
203}
204
205#pragma mark - Privates
206
207- (void)registerExpoModulesInBridge:(RCTBridge *)bridge
208{
209  // Registering expo modules (excluding Swifty view managers!) in bridge is needed only when the proxy module owns
210  // the registry (was autoinitialized by React Native). Otherwise they're registered by the registry adapter.
211  BOOL ownsModuleRegistry = _ownsModuleRegistry && ![bridge moduleIsInitialized:[EXReactNativeEventEmitter class]];
212
213  // An array of `RCTBridgeModule` classes to register.
214  NSMutableArray<Class<RCTBridgeModule>> *additionalModuleClasses = [NSMutableArray new];
215  NSMutableSet *visitedSweetModules = [NSMutableSet new];
216
217  // Add dynamic wrappers for view modules written in Sweet API.
218  for (ViewModuleWrapper *swiftViewModule in [_appContext getViewManagers]) {
219    Class wrappedViewModuleClass = [self registerComponentData:swiftViewModule inBridge:bridge];
220    [additionalModuleClasses addObject:wrappedViewModuleClass];
221    [visitedSweetModules addObject:swiftViewModule.name];
222  }
223
224  [additionalModuleClasses addObject:[ViewModuleWrapper class]];
225  [self registerLegacyComponentData:[ViewModuleWrapper class] inBridge:bridge];
226
227  // Add modules from legacy module registry only when the NativeModulesProxy owns the registry.
228  if (ownsModuleRegistry) {
229    // Event emitter is a bridge module, however it's also needed by expo modules,
230    // so later we'll register an instance created by React Native as expo module.
231    [additionalModuleClasses addObject:[EXReactNativeEventEmitter class]];
232
233    // Add dynamic wrappers for the classic view managers.
234    for (EXViewManager *viewManager in [_exModuleRegistry getAllViewManagers]) {
235      if (![visitedSweetModules containsObject:viewManager.viewName]) {
236        Class viewManagerWrapperClass = [EXViewManagerAdapterClassesRegistry createViewManagerAdapterClassForViewManager:viewManager];
237        [additionalModuleClasses addObject:viewManagerWrapperClass];
238        [self registerLegacyComponentData:viewManagerWrapperClass inBridge:bridge];
239      }
240    }
241
242    // View manager wrappers don't have their own prop configs, so we must register
243    // their base view managers that provides common props such as `proxiedProperties`.
244    // Otherwise, React Native may treat these props as invalid in subclassing views.
245    [additionalModuleClasses addObject:[EXViewManagerAdapter class]];
246
247    // Some modules might need access to the bridge.
248    for (id module in [_exModuleRegistry getAllInternalModules]) {
249      if ([module conformsToProtocol:@protocol(RCTBridgeModule)]) {
250        [module setValue:bridge forKey:@"bridge"];
251      }
252    }
253  }
254
255  // `registerAdditionalModuleClasses:` call below is not thread-safe if RCTUIManager is not initialized.
256  // The case happens especially with reanimated which accesses `bridge.uiManager` and initialize bridge in js thread.
257  // Accessing uiManager here, we try to make sure RCTUIManager is initialized.
258  [bridge uiManager];
259
260  // Register the view managers as additional modules.
261  [self registerAdditionalModuleClasses:additionalModuleClasses inBridge:bridge];
262
263  // Get the instance of `EXReactEventEmitter` bridge module and give it access to the interop bridge.
264  EXReactNativeEventEmitter *eventEmitter = [bridge moduleForClass:[EXReactNativeEventEmitter class]];
265  [eventEmitter setAppContext:_appContext];
266
267  // As the last step, when the registry is owned,
268  // register the event emitter and initialize the registry.
269  if (ownsModuleRegistry) {
270    [_exModuleRegistry registerInternalModule:eventEmitter];
271
272    // Let the modules consume the registry :)
273    // It calls `setModuleRegistry:` on all `EXModuleRegistryConsumer`s.
274    [_exModuleRegistry initialize];
275  }
276}
277
278- (void)registerAdditionalModuleClasses:(NSArray<Class> *)moduleClasses inBridge:(RCTBridge *)bridge
279{
280  // In remote debugging mode, i.e. executorClass is `RCTWebSocketExecutor`,
281  // there is a deadlock issue in `registerAdditionalModuleClasses:` and causes app freezed.
282  //   - The JS thread acquired the `RCTCxxBridge._moduleRegistryLock` lock in `RCTCxxBridge._initializeBridgeLocked`
283  //      = it further goes into RCTObjcExecutor and tries to get module config from main thread
284  //   - The main thread is pending in `RCTCxxBridge.registerAdditionalModuleClasses` where trying to acquire the same lock.
285  // To workaround the deadlock, we tend to use the non-locked registration and mutate the bridge internal module data.
286  // Since JS thread in this situation is waiting for main thread, it's safe to mutate module data without lock.
287  // The only risk should be the internal `_moduleRegistryCreated` flag without lock protection.
288  // As we just workaround in `RCTWebSocketExecutor` case, the risk of `_moduleRegistryCreated` race condition should be lower.
289  //
290  // Learn more about the non-locked initialization:
291  // https://github.com/facebook/react-native/blob/757bb75fbf837714725d7b2af62149e8e2a7ee51/React/CxxBridge/RCTCxxBridge.mm#L922-L935
292  // See the `_moduleRegistryCreated` false case
293  if ([NSStringFromClass([bridge executorClass]) isEqualToString:@"RCTWebSocketExecutor"]) {
294    NSNumber *moduleRegistryCreated = [bridge valueForKey:@"_moduleRegistryCreated"];
295    if (![moduleRegistryCreated boolValue]) {
296      [bridge registerModulesForClasses:moduleClasses];
297      return;
298    }
299  }
300
301  [bridge registerAdditionalModuleClasses:moduleClasses];
302}
303
304- (Class)registerComponentData:(ViewModuleWrapper *)viewModule inBridge:(RCTBridge *)bridge
305{
306  // Hacky way to get a dictionary with `RCTComponentData` from UIManager.
307  NSMutableDictionary<NSString *, RCTComponentData *> *componentDataByName = [bridge.uiManager valueForKey:@"_componentDataByName"];
308  Class wrappedViewModuleClass = [ViewModuleWrapper createViewModuleWrapperClassWithModule:viewModule];
309  NSString *className = NSStringFromClass(wrappedViewModuleClass);
310
311  if (componentDataByName[className]) {
312    // Just in case the component was already registered, let's leave a log that we're overriding it.
313    NSLog(@"Overriding ComponentData for view %@", className);
314  }
315
316  EXComponentData *componentData = [[EXComponentData alloc] initWithViewModule:viewModule
317                                                                  managerClass:wrappedViewModuleClass
318                                                                        bridge:bridge];
319  componentDataByName[className] = componentData;
320  return wrappedViewModuleClass;
321}
322
323/**
324 Bridge's `registerAdditionalModuleClasses:` method doesn't register
325 components in UIManager — we need to register them on our own.
326 */
327- (void)registerLegacyComponentData:(Class)moduleClass inBridge:(RCTBridge *)bridge
328{
329  // Hacky way to get a dictionary with `RCTComponentData` from UIManager.
330  NSMutableDictionary<NSString *, RCTComponentData *> *componentDataByName = [bridge.uiManager valueForKey:@"_componentDataByName"];
331  NSString *className = NSStringFromClass(moduleClass);
332
333  if ([moduleClass isSubclassOfClass:[RCTViewManager class]] && !componentDataByName[className]) {
334    RCTComponentData *componentData = [[RCTComponentData alloc] initWithManagerClass:moduleClass bridge:bridge eventDispatcher:bridge.eventDispatcher];
335    componentDataByName[className] = componentData;
336  }
337}
338
339- (void)assignExportedMethodsKeys:(NSMutableArray<NSMutableDictionary<const NSString *, id> *> *)exportedMethods forModuleName:(const NSString *)moduleName
340{
341  if (!_exportedMethodsKeys[moduleName]) {
342    _exportedMethodsKeys[moduleName] = [NSMutableDictionary dictionary];
343  }
344
345  if (!_exportedMethodsReverseKeys[moduleName]) {
346    _exportedMethodsReverseKeys[moduleName] = [NSMutableDictionary dictionary];
347  }
348
349  for (int i = 0; i < [exportedMethods count]; i++) {
350    NSMutableDictionary<const NSString *, id> *methodInfo = exportedMethods[i];
351
352    if (!methodInfo[(NSString *)methodInfoNameKey] || ![methodInfo[methodInfoNameKey] isKindOfClass:[NSString class]]) {
353      NSString *reason = [NSString stringWithFormat:@"Method info of a method of module %@ has no method name.", moduleName];
354      @throw [NSException exceptionWithName:@"Empty method name in method info" reason:reason userInfo:nil];
355    }
356
357    NSString *methodName = methodInfo[(NSString *)methodInfoNameKey];
358    NSNumber *previousMethodKey = _exportedMethodsKeys[moduleName][methodName];
359    if (previousMethodKey) {
360      methodInfo[methodInfoKeyKey] = previousMethodKey;
361    } else {
362      NSNumber *newKey = @([[_exportedMethodsKeys[moduleName] allValues] count]);
363      methodInfo[methodInfoKeyKey] = newKey;
364      _exportedMethodsKeys[moduleName][methodName] = newKey;
365      _exportedMethodsReverseKeys[moduleName][newKey] = methodName;
366    }
367  }
368}
369
370@end
371