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