RCTJavaScriptLoader.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RCTJavaScriptLoader.h"
  8. #import <sys/stat.h>
  9. #import <cxxreact/JSBundleType.h>
  10. #import "RCTBridge.h"
  11. #import "RCTConvert.h"
  12. #import "RCTMultipartDataTask.h"
  13. #import "RCTPerformanceLogger.h"
  14. #import "RCTUtils.h"
  15. NSString *const RCTJavaScriptLoaderErrorDomain = @"RCTJavaScriptLoaderErrorDomain";
  16. static const int32_t JSNoBytecodeFileFormatVersion = -1;
  17. @interface RCTSource()
  18. {
  19. @public
  20. NSURL *_url;
  21. NSData *_data;
  22. NSUInteger _length;
  23. NSInteger _filesChangedCount;
  24. }
  25. @end
  26. @implementation RCTSource
  27. static RCTSource *RCTSourceCreate(NSURL *url, NSData *data, int64_t length) NS_RETURNS_RETAINED
  28. {
  29. RCTSource *source = [RCTSource new];
  30. source->_url = url;
  31. source->_data = data;
  32. source->_length = length;
  33. source->_filesChangedCount = RCTSourceFilesChangedCountNotBuiltByBundler;
  34. return source;
  35. }
  36. @end
  37. @implementation RCTLoadingProgress
  38. - (NSString *)description
  39. {
  40. NSMutableString *desc = [NSMutableString new];
  41. [desc appendString:_status ?: @"Loading"];
  42. if ([_total integerValue] > 0) {
  43. [desc appendFormat:@" %ld%% (%@/%@)", (long)(100 * [_done integerValue] / [_total integerValue]), _done, _total];
  44. }
  45. [desc appendString:@"\u2026"];
  46. return desc;
  47. }
  48. @end
  49. @implementation RCTJavaScriptLoader
  50. RCT_NOT_IMPLEMENTED(- (instancetype)init)
  51. + (void)loadBundleAtURL:(NSURL *)scriptURL onProgress:(RCTSourceLoadProgressBlock)onProgress onComplete:(RCTSourceLoadBlock)onComplete
  52. {
  53. int64_t sourceLength;
  54. NSError *error;
  55. NSData *data = [self attemptSynchronousLoadOfBundleAtURL:scriptURL
  56. runtimeBCVersion:JSNoBytecodeFileFormatVersion
  57. sourceLength:&sourceLength
  58. error:&error];
  59. if (data) {
  60. onComplete(nil, RCTSourceCreate(scriptURL, data, sourceLength));
  61. return;
  62. }
  63. const BOOL isCannotLoadSyncError =
  64. [error.domain isEqualToString:RCTJavaScriptLoaderErrorDomain]
  65. && error.code == RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously;
  66. if (isCannotLoadSyncError) {
  67. attemptAsynchronousLoadOfBundleAtURL(scriptURL, onProgress, onComplete);
  68. } else {
  69. onComplete(error, nil);
  70. }
  71. }
  72. + (NSData *)attemptSynchronousLoadOfBundleAtURL:(NSURL *)scriptURL
  73. runtimeBCVersion:(int32_t)runtimeBCVersion
  74. sourceLength:(int64_t *)sourceLength
  75. error:(NSError **)error
  76. {
  77. NSString *unsanitizedScriptURLString = scriptURL.absoluteString;
  78. // Sanitize the script URL
  79. scriptURL = sanitizeURL(scriptURL);
  80. if (!scriptURL) {
  81. if (error) {
  82. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  83. code:RCTJavaScriptLoaderErrorNoScriptURL
  84. userInfo:@{NSLocalizedDescriptionKey:
  85. [NSString stringWithFormat:@"No script URL provided. Make sure the packager is "
  86. @"running or you have embedded a JS bundle in your application bundle.\n\n"
  87. @"unsanitizedScriptURLString = %@", unsanitizedScriptURLString]}];
  88. }
  89. return nil;
  90. }
  91. // Load local script file
  92. if (!scriptURL.fileURL) {
  93. if (error) {
  94. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  95. code:RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously
  96. userInfo:@{NSLocalizedDescriptionKey:
  97. [NSString stringWithFormat:@"Cannot load %@ URLs synchronously",
  98. scriptURL.scheme]}];
  99. }
  100. return nil;
  101. }
  102. // Load the first 4 bytes to check if the bundle is regular or RAM ("Random Access Modules" bundle).
  103. // The RAM bundle has a magic number in the 4 first bytes `(0xFB0BD1E5)`.
  104. // The benefit of RAM bundle over a regular bundle is that we can lazily inject
  105. // modules into JSC as they're required.
  106. FILE *bundle = fopen(scriptURL.path.UTF8String, "r");
  107. if (!bundle) {
  108. if (error) {
  109. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  110. code:RCTJavaScriptLoaderErrorFailedOpeningFile
  111. userInfo:@{NSLocalizedDescriptionKey:
  112. [NSString stringWithFormat:@"Error opening bundle %@", scriptURL.path]}];
  113. }
  114. return nil;
  115. }
  116. facebook::react::BundleHeader header;
  117. size_t readResult = fread(&header, sizeof(header), 1, bundle);
  118. fclose(bundle);
  119. if (readResult != 1) {
  120. if (error) {
  121. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  122. code:RCTJavaScriptLoaderErrorFailedReadingFile
  123. userInfo:@{NSLocalizedDescriptionKey:
  124. [NSString stringWithFormat:@"Error reading bundle %@", scriptURL.path]}];
  125. }
  126. return nil;
  127. }
  128. facebook::react::ScriptTag tag = facebook::react::parseTypeFromHeader(header);
  129. switch (tag) {
  130. case facebook::react::ScriptTag::RAMBundle:
  131. break;
  132. case facebook::react::ScriptTag::String: {
  133. #if RCT_ENABLE_INSPECTOR
  134. NSData *source = [NSData dataWithContentsOfFile:scriptURL.path
  135. options:NSDataReadingMappedIfSafe
  136. error:error];
  137. if (sourceLength && source != nil) {
  138. *sourceLength = source.length;
  139. }
  140. return source;
  141. #else
  142. if (error) {
  143. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  144. code:RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously
  145. userInfo:@{NSLocalizedDescriptionKey:
  146. @"Cannot load text/javascript files synchronously"}];
  147. }
  148. return nil;
  149. #endif
  150. }
  151. case facebook::react::ScriptTag::BCBundle:
  152. if (runtimeBCVersion == JSNoBytecodeFileFormatVersion || runtimeBCVersion < 0) {
  153. if (error) {
  154. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  155. code:RCTJavaScriptLoaderErrorBCNotSupported
  156. userInfo:@{NSLocalizedDescriptionKey:
  157. @"Bytecode bundles are not supported by this runtime."}];
  158. }
  159. return nil;
  160. }
  161. else if ((uint32_t)runtimeBCVersion != header.version) {
  162. if (error) {
  163. NSString *errDesc =
  164. [NSString stringWithFormat:@"BC Version Mismatch. Expect: %d, Actual: %u",
  165. runtimeBCVersion, header.version];
  166. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  167. code:RCTJavaScriptLoaderErrorBCVersion
  168. userInfo:@{NSLocalizedDescriptionKey: errDesc}];
  169. }
  170. return nil;
  171. }
  172. break;
  173. }
  174. struct stat statInfo;
  175. if (stat(scriptURL.path.UTF8String, &statInfo) != 0) {
  176. if (error) {
  177. *error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  178. code:RCTJavaScriptLoaderErrorFailedStatingFile
  179. userInfo:@{NSLocalizedDescriptionKey:
  180. [NSString stringWithFormat:@"Error stating bundle %@", scriptURL.path]}];
  181. }
  182. return nil;
  183. }
  184. if (sourceLength) {
  185. *sourceLength = statInfo.st_size;
  186. }
  187. return [NSData dataWithBytes:&header length:sizeof(header)];
  188. }
  189. static void parseHeaders(NSDictionary *headers, RCTSource *source) {
  190. source->_filesChangedCount = [headers[@"X-Metro-Files-Changed-Count"] integerValue];
  191. }
  192. static void attemptAsynchronousLoadOfBundleAtURL(NSURL *scriptURL, RCTSourceLoadProgressBlock onProgress, RCTSourceLoadBlock onComplete)
  193. {
  194. scriptURL = sanitizeURL(scriptURL);
  195. if (scriptURL.fileURL) {
  196. // Reading in a large bundle can be slow. Dispatch to the background queue to do it.
  197. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  198. NSError *error = nil;
  199. NSData *source = [NSData dataWithContentsOfFile:scriptURL.path
  200. options:NSDataReadingMappedIfSafe
  201. error:&error];
  202. onComplete(error, RCTSourceCreate(scriptURL, source, source.length));
  203. });
  204. return;
  205. }
  206. RCTMultipartDataTask *task = [[RCTMultipartDataTask alloc] initWithURL:scriptURL partHandler:^(NSInteger statusCode, NSDictionary *headers, NSData *data, NSError *error, BOOL done) {
  207. if (!done) {
  208. if (onProgress) {
  209. onProgress(progressEventFromData(data));
  210. }
  211. return;
  212. }
  213. // Handle general request errors
  214. if (error) {
  215. if ([error.domain isEqualToString:NSURLErrorDomain]) {
  216. error = [NSError errorWithDomain:RCTJavaScriptLoaderErrorDomain
  217. code:RCTJavaScriptLoaderErrorURLLoadFailed
  218. userInfo:
  219. @{
  220. NSLocalizedDescriptionKey:
  221. [@"Could not connect to development server.\n\n"
  222. "Ensure the following:\n"
  223. "- Node server is running and available on the same network - run 'npm start' from react-native root\n"
  224. "- Node server URL is correctly set in AppDelegate\n"
  225. "- WiFi is enabled and connected to the same network as the Node Server\n\n"
  226. "URL: " stringByAppendingString:scriptURL.absoluteString],
  227. NSLocalizedFailureReasonErrorKey: error.localizedDescription,
  228. NSUnderlyingErrorKey: error,
  229. }];
  230. }
  231. onComplete(error, nil);
  232. return;
  233. }
  234. // For multipart responses packager sets X-Http-Status header in case HTTP status code
  235. // is different from 200 OK
  236. NSString *statusCodeHeader = headers[@"X-Http-Status"];
  237. if (statusCodeHeader) {
  238. statusCode = [statusCodeHeader integerValue];
  239. }
  240. if (statusCode != 200) {
  241. error = [NSError errorWithDomain:@"JSServer"
  242. code:statusCode
  243. userInfo:userInfoForRawResponse([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding])];
  244. onComplete(error, nil);
  245. return;
  246. }
  247. // Validate that the packager actually returned javascript.
  248. NSString *contentType = headers[@"Content-Type"];
  249. NSString *mimeType = [[contentType componentsSeparatedByString:@";"] firstObject];
  250. if (![mimeType isEqualToString:@"application/javascript"] &&
  251. ![mimeType isEqualToString:@"text/javascript"]) {
  252. NSString *description = [NSString stringWithFormat:@"Expected MIME-Type to be 'application/javascript' or 'text/javascript', but got '%@'.", mimeType];
  253. error = [NSError errorWithDomain:@"JSServer"
  254. code:NSURLErrorCannotParseResponse
  255. userInfo:@{
  256. NSLocalizedDescriptionKey: description,
  257. @"headers": headers,
  258. @"data": data
  259. }];
  260. onComplete(error, nil);
  261. return;
  262. }
  263. RCTSource *source = RCTSourceCreate(scriptURL, data, data.length);
  264. parseHeaders(headers, source);
  265. onComplete(nil, source);
  266. } progressHandler:^(NSDictionary *headers, NSNumber *loaded, NSNumber *total) {
  267. // Only care about download progress events for the javascript bundle part.
  268. if ([headers[@"Content-Type"] isEqualToString:@"application/javascript"]) {
  269. onProgress(progressEventFromDownloadProgress(loaded, total));
  270. }
  271. }];
  272. [task startTask];
  273. }
  274. static NSURL *sanitizeURL(NSURL *url)
  275. {
  276. // Why we do this is lost to time. We probably shouldn't; passing a valid URL is the caller's responsibility not ours.
  277. return [RCTConvert NSURL:url.absoluteString];
  278. }
  279. static RCTLoadingProgress *progressEventFromData(NSData *rawData)
  280. {
  281. NSString *text = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];
  282. id info = RCTJSONParse(text, nil);
  283. if (!info || ![info isKindOfClass:[NSDictionary class]]) {
  284. return nil;
  285. }
  286. RCTLoadingProgress *progress = [RCTLoadingProgress new];
  287. progress.status = info[@"status"];
  288. progress.done = info[@"done"];
  289. progress.total = info[@"total"];
  290. return progress;
  291. }
  292. static RCTLoadingProgress *progressEventFromDownloadProgress(NSNumber *total, NSNumber *done)
  293. {
  294. RCTLoadingProgress *progress = [RCTLoadingProgress new];
  295. progress.status = @"Downloading JavaScript bundle";
  296. // Progress values are in bytes transform them to kilobytes for smaller numbers.
  297. progress.done = done != nil ? @([done integerValue] / 1024) : nil;
  298. progress.total = total != nil ? @([total integerValue] / 1024) : nil;
  299. return progress;
  300. }
  301. static NSDictionary *userInfoForRawResponse(NSString *rawText)
  302. {
  303. NSDictionary *parsedResponse = RCTJSONParse(rawText, nil);
  304. if (![parsedResponse isKindOfClass:[NSDictionary class]]) {
  305. return @{NSLocalizedDescriptionKey: rawText};
  306. }
  307. NSArray *errors = parsedResponse[@"errors"];
  308. if (![errors isKindOfClass:[NSArray class]]) {
  309. return @{NSLocalizedDescriptionKey: rawText};
  310. }
  311. NSMutableArray<NSDictionary *> *fakeStack = [NSMutableArray new];
  312. for (NSDictionary *err in errors) {
  313. [fakeStack addObject: @{
  314. @"methodName": err[@"description"] ?: @"",
  315. @"file": err[@"filename"] ?: @"",
  316. @"lineNumber": err[@"lineNumber"] ?: @0
  317. }];
  318. }
  319. return @{NSLocalizedDescriptionKey: parsedResponse[@"message"] ?: @"No message provided", @"stack": [fakeStack copy]};
  320. }
  321. @end