From 3cf5483d25fc35ee0472b199730721533f24d097 Mon Sep 17 00:00:00 2001 From: Rob Herhold Date: Thu, 12 Nov 2026 15:58:26 -0800 Subject: [PATCH] Announce the JavaScript about to run with its URL and dev server revision Summary: Observers cannot tell which JavaScript runs in bridgeless mode, or which dev server revision it was built from. On iOS, `RCTJavaScriptDidLoadNotification` arrives on the main queue only after a bundle finishes evaluating and names it only through the bridge's current bundle URL, so a bundle that throws goes unseen, a reload in between is attributed to the new URL, and segments are never announced. On Android, the performance markers name a bundle only by its file's basename and a segment only by its ID. The dev server labels every bundle response with the revision of the module graph it was built from (`X-Metro-Delta-ID`) and every hot update with a `revisionId`, but React Native drops both. iOS: - `RCTInstance` posts `RCTJavaScriptWillStartExecutingNotification` synchronously right before a bundle runs (on the JS thread) and before a segment is registered (on the registering thread). `userInfo` carries the `bridge`, the bundle or segment file `url`, and the bundle's `revisionId` when the dev server sent one. `RCTJavaScriptDidLoadNotification` now carries the `url` too. `RCTConstants.h` states when each notification is posted, on which thread and with which keys, and that will-execute observers must not use UIKit or wait on the main thread. The macOS `RCTInstance` (`runtime/platform/macos`) is unchanged. - `RCTInstance` calls `RCTMarkJavaScriptStartedExecuting()` right before each of those posts, and `RCTHasJavaScriptStartedExecuting()` reads it, so an observer that registers after JavaScript started can tell that it missed some instead of assuming none ran. - `RCTJavaScriptLoader` keeps the `X-Metro-Delta-ID` header of a bundle it downloads as `RCTSource.revisionId` (nil for bundles read from disk or served without the header). Android: - `ReactJavaScriptLoads` (`UnstableReactNativeAPI`) calls its listeners right before `ReactInstance` runs a bundle and before it registers a segment file, on the thread that loads it, with the script's source URL, the file read (null for an APK asset) and the bundle's dev server revision. `ReactJavaScriptLoads.hasStartedExecuting()` is the late-listener check. A listener that throws is logged and does not stop the load or the other listeners. - `BundleDownloader.BundleInfo.revisionId` keeps the `X-Metro-Delta-ID` of a downloaded bundle, `DevSupportManagerBase.downloadedJSBundleRevisionId` remembers it for the bundle last downloaded, and `ReactHostImpl` passes it to `JSBundleLoader.createCachedBundleFromNetworkLoader`, whose loader exposes it as `JSBundleLoader.revisionId`. Both platforms: - `HMRClient` calls `global.__HMR_UPDATE_REPORTER__?.onUpdate({revisionId})` for every update the server sends, after the client has applied it, or stashed it while Fast Refresh is off. An update that throws while it runs is not reported. Nothing changes when no one observes the notification, adds a listener or installs the reporter. Changelog: [iOS][Added] - Post `RCTJavaScriptWillStartExecutingNotification` with the bundle or segment `url` and the dev server `revisionId` before JavaScript runs in bridgeless mode, add both to `RCTJavaScriptDidLoadNotification`, and expose a dev server bundle's revision as `RCTSource.revisionId` [iOS][Added] - Add `RCTHasJavaScriptStartedExecuting()`, which tells an observer that registers late whether JavaScript already started executing [Android][Added] - Add `ReactJavaScriptLoads`, which announces each bundle and segment the bridgeless runtime is about to run with its source URL, file and dev server revision, and expose a downloaded bundle's dev server revision as `JSBundleLoader.revisionId` [General][Added] - Report each hot update's revision to an optional `global.__HMR_UPDATE_REPORTER__` Differential Revision: D131359967 --- .../Libraries/Utilities/HMRClient.js | 13 +- .../react-native/React/Base/RCTConstants.h | 14 +++ .../react-native/React/Base/RCTConstants.m | 18 +++ .../React/Base/RCTJavaScriptLoader.h | 7 ++ .../React/Base/RCTJavaScriptLoader.mm | 5 + .../ReactAndroid/api/ReactAndroid.api | 6 + .../facebook/react/bridge/JSBundleLoader.kt | 12 +- .../react/devsupport/BundleDownloader.kt | 7 ++ .../react/devsupport/DevSupportManagerBase.kt | 9 ++ .../facebook/react/runtime/ReactHostImpl.kt | 1 + .../facebook/react/runtime/ReactInstance.kt | 3 + .../react/runtime/ReactJavaScriptLoads.kt | 65 ++++++++++ .../react/runtime/ReactJavaScriptLoadsTest.kt | 75 ++++++++++++ .../runtime/iostests/RCTInstanceTests.mm | 112 ++++++++++++++++++ .../platform/ios/ReactCommon/RCTInstance.mm | 42 ++++++- .../api-snapshots/ReactAppleDebugCxx.api | 1 + .../api-snapshots/ReactAppleFrameworksCxx.api | 1 + .../api-snapshots/ReactAppleNewarchCxx.api | 1 + .../api-snapshots/ReactAppleReleaseCxx.api | 1 + 19 files changed, 385 insertions(+), 8 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactJavaScriptLoads.kt create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactJavaScriptLoadsTest.kt diff --git a/packages/react-native/Libraries/Utilities/HMRClient.js b/packages/react-native/Libraries/Utilities/HMRClient.js index bf3e7826ddb8..04dd68f316b3 100644 --- a/packages/react-native/Libraries/Utilities/HMRClient.js +++ b/packages/react-native/Libraries/Utilities/HMRClient.js @@ -20,6 +20,13 @@ const invariant = require('invariant'); const MetroHMRClient = require('metro-runtime/src/modules/HMRClient'); const prettyFormat = require('pretty-format'); +declare var global: { + __HMR_UPDATE_REPORTER__?: { + onUpdate: (update: Readonly<{revisionId: ?string, ...}>) => void, + }, + ... +}; + const pendingEntryPoints = []; let hmrClient = null; let hmrUnavailableReason: string | null = null; @@ -235,11 +242,15 @@ Error: ${e.message}`; } }); - client.on('update', ({isInitialUpdate}) => { + client.on('update', ({isInitialUpdate, revisionId}) => { + // Runs after the client applied the update, or stashed it until Fast + // Refresh is enabled. An update that throws while it runs is not + // reported. if (client.isEnabled() && !isInitialUpdate) { dismissRedbox(); LogBox.clearAllLogs(); } + global.__HMR_UPDATE_REPORTER__?.onUpdate({revisionId}); }); client.on('update-done', body => { diff --git a/packages/react-native/React/Base/RCTConstants.h b/packages/react-native/React/Base/RCTConstants.h index 185f57f4881f..ae272ad35a40 100644 --- a/packages/react-native/React/Base/RCTConstants.h +++ b/packages/react-native/React/Base/RCTConstants.h @@ -23,11 +23,25 @@ RCT_EXTERN NSString *const RCTJavaScriptWillStartLoadingNotification; /** * This notification fires when the bridge starts executing the JS bundle. + * On iOS, `RCTInstance` posts it synchronously right before a bundle runs, on the JS thread, and right before a + * segment is registered, on the registering thread. `userInfo` holds the `bridge`, the bundle or segment file `url` + * and, for a bundle a dev server labeled, its `revisionId` (see `RCTSource`). Observers must not use UIKit or wait on + * the main thread. */ RCT_EXTERN NSString *const RCTJavaScriptWillStartExecutingNotification; +/** + * Whether `RCTInstance` in this process has started executing a bundle or registering a segment. It marks this right + * before it posts `RCTJavaScriptWillStartExecutingNotification`, so an observer that registers later can tell that + * JavaScript ran before it could observe it. + */ +RCT_EXTERN BOOL RCTHasJavaScriptStartedExecuting(void); +RCT_EXTERN void RCTMarkJavaScriptStartedExecuting(void); + /** * This notification fires when the bridge has finished loading the JS bundle. + * On iOS, `RCTInstance` posts it on the main thread after the bundle has run, with the `bridge` and the bundle's + * `url` in `userInfo`. */ RCT_EXTERN NSString *const RCTJavaScriptDidLoadNotification; diff --git a/packages/react-native/React/Base/RCTConstants.m b/packages/react-native/React/Base/RCTConstants.m index 3c2acc59c084..80387ab9688b 100644 --- a/packages/react-native/React/Base/RCTConstants.m +++ b/packages/react-native/React/Base/RCTConstants.m @@ -7,6 +7,8 @@ #import "RCTConstants.h" +#import + NSString *const RCTPlatformName = @"ios"; NSString *const RCTUserInterfaceStyleDidChangeNotification = @"RCTUserInterfaceStyleDidChangeNotification"; @@ -25,6 +27,22 @@ NSString *const RCTNotifyEventDispatcherObserversOfEvent_DEPRECATED = @"RCTNotifyEventDispatcherObserversOfEvent_DEPRECATED"; +static atomic_bool *RCTJavaScriptStartedExecuting(void) +{ + static atomic_bool started = false; + return &started; +} + +BOOL RCTHasJavaScriptStartedExecuting(void) +{ + return atomic_load(RCTJavaScriptStartedExecuting()); +} + +void RCTMarkJavaScriptStartedExecuting(void) +{ + atomic_store(RCTJavaScriptStartedExecuting(), true); +} + /* * W3C Pointer Events */ diff --git a/packages/react-native/React/Base/RCTJavaScriptLoader.h b/packages/react-native/React/Base/RCTJavaScriptLoader.h index 370af209a8f7..b42e6cd986e6 100755 --- a/packages/react-native/React/Base/RCTJavaScriptLoader.h +++ b/packages/react-native/React/Base/RCTJavaScriptLoader.h @@ -76,6 +76,13 @@ NS_ENUM(NSInteger){ */ @property (strong, nonatomic, readonly) NSURL *downloadedBundleFileURL; +/** + * The bundler's identifier for the revision of the module graph this bundle was + * built from, taken from the `X-Metro-Delta-ID` response header. nil when the + * bundle was not served by a bundler that sends one (e.g. read from disk). + */ +@property (copy, nonatomic, readonly) NSString *revisionId; + @end typedef void (^RCTSourceLoadProgressBlock)(RCTLoadingProgress *progressData); diff --git a/packages/react-native/React/Base/RCTJavaScriptLoader.mm b/packages/react-native/React/Base/RCTJavaScriptLoader.mm index b8f353cd9cab..c73e82e7a18a 100755 --- a/packages/react-native/React/Base/RCTJavaScriptLoader.mm +++ b/packages/react-native/React/Base/RCTJavaScriptLoader.mm @@ -27,6 +27,7 @@ @interface RCTSource () { NSUInteger _length; NSInteger _filesChangedCount; NSURL *_downloadedBundleFileURL; + NSString *_revisionId; } @end @@ -223,6 +224,10 @@ + (NSData *)attemptSynchronousLoadOfBundleAtURL:(NSURL *)scriptURL static void parseHeaders(NSDictionary *headers, RCTSource *source) { source->_filesChangedCount = [headers[@"X-Metro-Files-Changed-Count"] integerValue]; + id revisionId = headers[@"X-Metro-Delta-ID"]; + if ([revisionId isKindOfClass:[NSString class]] && [revisionId length] > 0) { + source->_revisionId = [revisionId copy]; + } } static NSURL *persistDownloadedBundle(NSData *data, NSError **error) diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 9f62f0c9b496..bde0f8337831 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -699,14 +699,18 @@ public abstract class com/facebook/react/bridge/JSBundleLoader { public fun ()V public static final fun createAssetLoader (Landroid/content/Context;Ljava/lang/String;Z)Lcom/facebook/react/bridge/JSBundleLoader; public static final fun createCachedBundleFromNetworkLoader (Ljava/lang/String;Ljava/lang/String;)Lcom/facebook/react/bridge/JSBundleLoader; + public static final fun createCachedBundleFromNetworkLoader (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lcom/facebook/react/bridge/JSBundleLoader; public static final fun createFileLoader (Ljava/lang/String;)Lcom/facebook/react/bridge/JSBundleLoader; public static final fun createFileLoader (Ljava/lang/String;Ljava/lang/String;Z)Lcom/facebook/react/bridge/JSBundleLoader; + public fun getRevisionId ()Ljava/lang/String; public abstract fun loadScript (Lcom/facebook/react/bridge/JSBundleLoaderDelegate;)Ljava/lang/String; } public final class com/facebook/react/bridge/JSBundleLoader$Companion { public final fun createAssetLoader (Landroid/content/Context;Ljava/lang/String;Z)Lcom/facebook/react/bridge/JSBundleLoader; public final fun createCachedBundleFromNetworkLoader (Ljava/lang/String;Ljava/lang/String;)Lcom/facebook/react/bridge/JSBundleLoader; + public final fun createCachedBundleFromNetworkLoader (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lcom/facebook/react/bridge/JSBundleLoader; + public static synthetic fun createCachedBundleFromNetworkLoader$default (Lcom/facebook/react/bridge/JSBundleLoader$Companion;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lcom/facebook/react/bridge/JSBundleLoader; public final fun createFileLoader (Ljava/lang/String;)Lcom/facebook/react/bridge/JSBundleLoader; public final fun createFileLoader (Ljava/lang/String;Ljava/lang/String;Z)Lcom/facebook/react/bridge/JSBundleLoader; } @@ -1823,6 +1827,7 @@ public final class com/facebook/react/devsupport/BundleDownloader$BundleInfo { public fun ()V public static final fun fromJSONString (Ljava/lang/String;)Lcom/facebook/react/devsupport/BundleDownloader$BundleInfo; public final fun getFilesChangedCount ()I + public final fun getRevisionId ()Ljava/lang/String; public final fun getUrl ()Ljava/lang/String; public final fun toJSONString ()Ljava/lang/String; } @@ -1900,6 +1905,7 @@ public abstract class com/facebook/react/devsupport/DevSupportManagerBase : com/ public final fun getDevSettings ()Lcom/facebook/react/modules/debug/interfaces/DeveloperSettings; public final fun getDevSupportEnabled ()Z public fun getDownloadedJSBundleFile ()Ljava/lang/String; + public final fun getDownloadedJSBundleRevisionId ()Ljava/lang/String; public final fun getJSAppBundleName ()Ljava/lang/String; public fun getKeyboardShortcutsEnabled ()Z public final fun getLastErrorCookie ()I diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.kt index aeec3eeba7b9..905928d22657 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/JSBundleLoader.kt @@ -16,6 +16,10 @@ public abstract class JSBundleLoader { /** Loads the script, returning the URL of the source it loaded. */ public abstract fun loadScript(delegate: JSBundleLoaderDelegate): String + /** The dev server's label for the revision it built the bundle from, null when there is none. */ + public open val revisionId: String? + get() = null + public companion object { /** * This loader is recommended one for release version of your app. In that case local JS @@ -61,14 +65,20 @@ public abstract class JSBundleLoader { * bundle to be prefetched and stored in local file. We do that to avoid passing large strings * between java and native code and avoid allocating memory in java to fit whole JS bundle in * it. Providing correct [sourceURL] of downloaded bundle is required for JS stacktraces to work - * correctly and allows for source maps to correctly symbolize those. + * correctly and allows for source maps to correctly symbolize those. [revisionId] is the dev + * server's label for the revision it built the bundle from (`X-Metro-Delta-ID`), null when it + * sent none; the loader exposes it as [JSBundleLoader.revisionId]. */ @JvmStatic + @JvmOverloads public fun createCachedBundleFromNetworkLoader( sourceURL: String, cachedFileLocation: String, + revisionId: String? = null, ): JSBundleLoader = object : JSBundleLoader() { + override val revisionId: String? = revisionId + override fun loadScript(delegate: JSBundleLoaderDelegate): String { return try { delegate.loadScriptFromFile(cachedFileLocation, sourceURL, false) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt index 61f559a869c2..fa37ab19199c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt @@ -42,12 +42,17 @@ public class BundleDownloader public constructor(private val client: OkHttpClien public var filesChangedCount: Int = 0 internal set + /** The dev server's label for the revision it built the bundle from (`X-Metro-Delta-ID`). */ + public var revisionId: String? = null + internal set + public fun toJSONString(): String? = try { JSONObject() .apply { put("url", _url) put("filesChangedCount", filesChangedCount) + put("revisionId", revisionId) } .toString() } catch (e: JSONException) { @@ -66,6 +71,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien BundleInfo().apply { _url = obj.getString("url") filesChangedCount = obj.getInt("filesChangedCount") + revisionId = obj.optString("revisionId").ifEmpty { null } } } catch (e: JSONException) { FLog.e(TAG, "Invalid bundle info: ", e) @@ -335,6 +341,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien private fun populateBundleInfo(url: String, headers: Headers, bundleInfo: BundleInfo) { bundleInfo._url = url + bundleInfo.revisionId = headers["X-Metro-Delta-ID"] val filesChangedCountStr = headers["X-Metro-Files-Changed-Count"] if (filesChangedCountStr != null) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.kt index 80d7d7678985..3696668d7d2a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.kt @@ -156,6 +156,13 @@ public abstract class DevSupportManagerBase( override val downloadedJSBundleFile: String get() = jsBundleDownloadedFile.absolutePath + /** + * The dev server's revision label of the bundle last downloaded into [downloadedJSBundleFile]; + * null while a download is in progress or after one failed. + */ + public var downloadedJSBundleRevisionId: String? = null + private set + public val devServerHelper: DevServerHelper = DevServerHelper(devSettings, applicationContext, devSettings.packagerConnectionSettings) @@ -778,9 +785,11 @@ public abstract class DevSupportManagerBase( val bundleInfo = BundleDownloader.BundleInfo() + downloadedJSBundleRevisionId = null devServerHelper.downloadBundleFromURL( object : DevBundleDownloadListener { override fun onSuccess() { + downloadedJSBundleRevisionId = bundleInfo.revisionId hideDevLoadingView() devBundleDownloadListener?.onSuccess() ReactMarker.logMarker(ReactMarkerConstants.DOWNLOAD_END, bundleInfo.toJSONString()) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt index f54557bf6906..7755fa381962 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt @@ -1220,6 +1220,7 @@ public class ReactHostImpl( JSBundleLoader.createCachedBundleFromNetworkLoader( bundleURL, asyncDevSupportManager.downloadedJSBundleFile, + asyncDevSupportManager.downloadedJSBundleRevisionId, ) taskCompletionSource.setResult(bundleLoader) } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.kt index de3416e75f46..20b985007d68 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactInstance.kt @@ -316,6 +316,7 @@ internal class ReactInstance( loadSynchronously: Boolean, ) { context.sourceURL = sourceURL + ReactJavaScriptLoads.willExecute(sourceURL, fileName, bundleLoader.revisionId) loadJSBundleFromFile(fileName, sourceURL) } @@ -325,6 +326,7 @@ internal class ReactInstance( loadSynchronously: Boolean, ) { context.sourceURL = assetURL + ReactJavaScriptLoads.willExecute(assetURL, null, null) loadJSBundleFromAssets(assetManager, assetURL) } @@ -476,6 +478,7 @@ internal class ReactInstance( } fun registerSegment(segmentId: Int, path: String) { + ReactJavaScriptLoads.willExecute(path, path, null) registerSegmentNative(segmentId, path) } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactJavaScriptLoads.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactJavaScriptLoads.kt new file mode 100644 index 000000000000..6de573bd9be8 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactJavaScriptLoads.kt @@ -0,0 +1,65 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.runtime + +import com.facebook.common.logging.FLog +import com.facebook.react.common.annotations.UnstableReactNativeAPI +import java.util.concurrent.CopyOnWriteArrayList + +/** + * Announces each bundle and segment file the bridgeless runtime is about to run, so an observer can + * tell which JavaScript ran and where it came from. + */ +@UnstableReactNativeAPI +public object ReactJavaScriptLoads { + + @UnstableReactNativeAPI + public fun interface Listener { + /** + * Called before React Native runs the script, on the thread that loads it. [sourceURL] names + * the script: the dev server URL for a bundle a dev server served, `assets://` for one read + * from the APK's assets, or the file path. [path] is the file read, null for an asset. + * [revisionId] is the dev server's label for the revision it built the bundle from, null when + * it sent none. Listeners must not block. One that throws is logged and does not stop the load. + */ + public fun onWillExecute(sourceURL: String, path: String?, revisionId: String?) + } + + private const val TAG = "ReactJavaScriptLoads" + + private val listeners = CopyOnWriteArrayList() + + @Volatile private var started = false + + @JvmStatic + public fun addListener(listener: Listener) { + listeners.addIfAbsent(listener) + } + + @JvmStatic + public fun removeListener(listener: Listener) { + listeners.remove(listener) + } + + /** + * Whether this process has started running a bundle or registering a segment, so a listener added + * later can tell that it missed some. + */ + @JvmStatic public fun hasStartedExecuting(): Boolean = started + + internal fun willExecute(sourceURL: String, path: String?, revisionId: String?) { + started = true + for (listener in listeners) { + try { + listener.onWillExecute(sourceURL, path, revisionId) + } catch (e: Exception) { + FLog.e(TAG, "A JavaScript load listener threw", e) + } + } + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactJavaScriptLoadsTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactJavaScriptLoadsTest.kt new file mode 100644 index 000000000000..456b62243f32 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/runtime/ReactJavaScriptLoadsTest.kt @@ -0,0 +1,75 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +@file:OptIn(UnstableReactNativeAPI::class) + +package com.facebook.react.runtime + +import com.facebook.react.bridge.JSBundleLoader +import com.facebook.react.bridge.JSBundleLoaderDelegate +import com.facebook.react.common.annotations.UnstableReactNativeAPI +import org.assertj.core.api.Assertions.assertThat +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class ReactJavaScriptLoadsTest { + private val loads = mutableListOf>() + private val listener = + ReactJavaScriptLoads.Listener { sourceURL, path, revisionId -> + loads.add(listOf(sourceURL, path, revisionId)) + } + + @After + fun tearDown() { + ReactJavaScriptLoads.removeListener(listener) + } + + @Test + fun announcesEachLoadToListenersAndRemembersThatJavaScriptStarted() { + ReactJavaScriptLoads.addListener(listener) + ReactJavaScriptLoads.addListener(listener) + + ReactJavaScriptLoads.willExecute("http://localhost:8081/index.bundle", "/data/b.js", "rev1") + ReactJavaScriptLoads.removeListener(listener) + ReactJavaScriptLoads.willExecute("assets://index.android.bundle", null, null) + + assertThat(loads) + .containsExactly(listOf("http://localhost:8081/index.bundle", "/data/b.js", "rev1")) + assertThat(ReactJavaScriptLoads.hasStartedExecuting()).isTrue() + } + + @Test + fun aThrowingListenerDoesNotStopTheOthers() { + val throwing = ReactJavaScriptLoads.Listener { _, _, _ -> throw IllegalStateException("boom") } + ReactJavaScriptLoads.addListener(throwing) + ReactJavaScriptLoads.addListener(listener) + + ReactJavaScriptLoads.willExecute("assets://index.android.bundle", null, null) + ReactJavaScriptLoads.removeListener(throwing) + + assertThat(loads).containsExactly(listOf("assets://index.android.bundle", null, null)) + } + + @Test + fun cachedNetworkLoaderCarriesTheDevServerRevision() { + val loader = + JSBundleLoader.createCachedBundleFromNetworkLoader( + "http://localhost:8081/index.bundle", + "/data/b.js", + "rev1", + ) + + assertThat(loader.revisionId).isEqualTo("rev1") + assertThat(loader.loadScript(mock())) + .isEqualTo("http://localhost:8081/index.bundle") + assertThat(JSBundleLoader.createFileLoader("/data/b.js").revisionId).isNull() + } +} diff --git a/packages/react-native/ReactCommon/react/runtime/iostests/RCTInstanceTests.mm b/packages/react-native/ReactCommon/react/runtime/iostests/RCTInstanceTests.mm index 6702584d1af3..9593761a0d18 100644 --- a/packages/react-native/ReactCommon/react/runtime/iostests/RCTInstanceTests.mm +++ b/packages/react-native/ReactCommon/react/runtime/iostests/RCTInstanceTests.mm @@ -10,6 +10,7 @@ #import #import #import +#import #import #import #import @@ -242,6 +243,117 @@ - (void)testBundleLoadAwaitsMainQueueModuleSetup @"FakeEagerModule -init must have fully returned before the JS bundle finishes loading"); } +- (void)testPostsTheBundleURLAndRevisionBeforeTheBundleRunsAndAfterItLoads +{ + OCMStub([_mockDelegate unstableModulesRequiringMainQueueSetup]).andReturn(@[]); + NSURL *bundleURL = [NSURL URLWithString:@"file:///empty.bundle"]; + RCTSource *emptySource = OCMClassMock([RCTSource class]); + OCMStub([emptySource url]).andReturn(bundleURL); + OCMStub([emptySource revisionId]).andReturn(@"rev-1"); + OCMStub([emptySource data]).andReturn([NSData data]); + OCMStub([_mockDelegate loadBundleAtURL:[OCMArg any] onProgress:[OCMArg any] onComplete:[OCMArg any]]) + .andDo(^(NSInvocation *invocation) { + __unsafe_unretained RCTSourceLoadBlock onComplete; + [invocation getArgument:&onComplete atIndex:4]; + onComplete(nil, emptySource); + }); + + NSMutableArray *order = [NSMutableArray new]; + __block NSDictionary *willExecuteUserInfo = nil; + __block BOOL startedBeforeWillExecute = NO; + __block NSDictionary *didLoadUserInfo = nil; + XCTestExpectation *willExecute = [self expectationWithDescription:RCTJavaScriptWillStartExecutingNotification]; + XCTestExpectation *didLoad = [self expectationWithDescription:RCTJavaScriptDidLoadNotification]; + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + id willExecuteObserver = [center addObserverForName:RCTJavaScriptWillStartExecutingNotification + object:nil + queue:nil + usingBlock:^(NSNotification *notification) { + @synchronized(order) { + [order addObject:@"willExecute"]; + } + willExecuteUserInfo = notification.userInfo; + startedBeforeWillExecute = RCTHasJavaScriptStartedExecuting(); + [willExecute fulfill]; + }]; + _bundleLoadObserver = [center addObserverForName:@"RCTInstanceDidLoadBundle" + object:nil + queue:nil + usingBlock:^(NSNotification *_) { + @synchronized(order) { + [order addObject:@"didLoadBundle"]; + } + }]; + id didLoadObserver = [center addObserverForName:RCTJavaScriptDidLoadNotification + object:nil + queue:nil + usingBlock:^(NSNotification *notification) { + didLoadUserInfo = notification.userInfo; + [didLoad fulfill]; + }]; + + RCTInstance *instance = [self makeInstance]; + [self waitForExpectations:@[ willExecute, didLoad ] timeout:10.0]; + [instance invalidate]; + [center removeObserver:willExecuteObserver]; + [center removeObserver:didLoadObserver]; + + XCTAssertEqualObjects(willExecuteUserInfo[@"url"], bundleURL); + XCTAssertEqualObjects(willExecuteUserInfo[@"revisionId"], @"rev-1"); + XCTAssertNotNil(willExecuteUserInfo[@"bridge"]); + XCTAssertTrue(startedBeforeWillExecute); + XCTAssertEqualObjects(didLoadUserInfo[@"url"], bundleURL); + XCTAssertNotNil(didLoadUserInfo[@"bridge"]); + @synchronized(order) { + XCTAssertEqualObjects(order, (@[ @"willExecute", @"didLoadBundle" ])); + } +} + +- (void)testPostsTheSegmentURLBeforeTheSegmentIsRegistered +{ + OCMStub([_mockDelegate unstableModulesRequiringMainQueueSetup]).andReturn(@[]); + RCTSource *emptySource = OCMClassMock([RCTSource class]); + OCMStub([emptySource url]).andReturn([NSURL URLWithString:@"file:///empty.bundle"]); + OCMStub([emptySource data]).andReturn([NSData data]); + OCMStub([_mockDelegate loadBundleAtURL:[OCMArg any] onProgress:[OCMArg any] onComplete:[OCMArg any]]) + .andDo(^(NSInvocation *invocation) { + __unsafe_unretained RCTSourceLoadBlock onComplete; + [invocation getArgument:&onComplete atIndex:4]; + onComplete(nil, emptySource); + }); + XCTestExpectation *didLoad = [self expectationWithDescription:RCTJavaScriptDidLoadNotification]; + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + id didLoadObserver = [center addObserverForName:RCTJavaScriptDidLoadNotification + object:nil + queue:nil + usingBlock:^(NSNotification *_) { + [didLoad fulfill]; + }]; + RCTInstance *instance = [self makeInstance]; + [self waitForExpectations:@[ didLoad ] timeout:10.0]; + [center removeObserver:didLoadObserver]; + + NSMutableArray *willExecuteUserInfos = [NSMutableArray new]; + id willExecuteObserver = [center addObserverForName:RCTJavaScriptWillStartExecutingNotification + object:nil + queue:nil + usingBlock:^(NSNotification *notification) { + @synchronized(willExecuteUserInfos) { + [willExecuteUserInfos addObject:notification.userInfo ?: @{}]; + } + }]; + [instance registerSegmentWithId:@7 path:@"/segments/missing-7.js"]; + [center removeObserver:willExecuteObserver]; + [instance invalidate]; + + @synchronized(willExecuteUserInfos) { + XCTAssertEqual(willExecuteUserInfos.count, 1u); + XCTAssertEqualObjects(willExecuteUserInfos.firstObject[@"url"], [NSURL fileURLWithPath:@"/segments/missing-7.js"]); + XCTAssertNil(willExecuteUserInfos.firstObject[@"revisionId"]); + XCTAssertNotNil(willExecuteUserInfos.firstObject[@"bridge"]); + } +} + - (void)testInvalidateDoesNotDeadlockWhenSuspendCallsIntoJS { OCMStub([_mockDelegate unstableModulesRequiringMainQueueSetup]).andReturn(@[]); diff --git a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm index fc18847f27af..8e164b2122b9 100644 --- a/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm +++ b/packages/react-native/ReactCommon/react/runtime/platform/ios/ReactCommon/RCTInstance.mm @@ -60,6 +60,16 @@ using namespace facebook; using namespace facebook::react; +static NSDictionary * +RCTJavaScriptLoadUserInfo(RCTBridgeProxy *_Nullable bridgeProxy, NSURL *_Nullable url, NSString *_Nullable revisionId) +{ + NSMutableDictionary *userInfo = [NSMutableDictionary new]; + userInfo[@"bridge"] = bridgeProxy; + userInfo[@"url"] = url; + userInfo[@"revisionId"] = revisionId; + return userInfo; +} + @interface RCTInstance () @end @@ -227,6 +237,11 @@ - (void)invalidate - (void)registerSegmentWithId:(NSNumber *)segmentId path:(NSString *)path { if (_valid) { + RCTMarkJavaScriptStartedExecuting(); + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTJavaScriptWillStartExecutingNotification + object:self + userInfo:RCTJavaScriptLoadUserInfo(_bridgeProxy, path ? [NSURL fileURLWithPath:path] : nil, nil)]; _reactInstance->registerSegment(static_cast([segmentId unsignedIntValue]), path.UTF8String); } } @@ -606,13 +621,27 @@ - (void)_loadScriptFromSource:(RCTSource *)source auto script = std::make_unique(source.data); const auto *url = deriveSourceURL(source.url).UTF8String; - auto beforeLoad = [waitUntilModuleSetupComplete = self->_waitUntilModuleSetupComplete](jsi::Runtime &_) { + NSURL *sourceURL = source.url; + NSString *revisionId = source.revisionId; + __weak __typeof(self) weakSelf = self; + auto beforeLoad = [waitUntilModuleSetupComplete = self->_waitUntilModuleSetupComplete, + weakSelf, + sourceURL, + revisionId](jsi::Runtime &) { if (waitUntilModuleSetupComplete) { waitUntilModuleSetupComplete(); } + // Posted synchronously on the JS thread right before the bundle runs, so observers learn of every bundle that + // starts executing, including one that throws before afterLoad. + __strong __typeof(weakSelf) strongSelf = weakSelf; + RCTMarkJavaScriptStartedExecuting(); + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTJavaScriptWillStartExecutingNotification + object:strongSelf + userInfo:RCTJavaScriptLoadUserInfo( + strongSelf ? strongSelf->_bridgeProxy : nil, sourceURL, revisionId)]; }; - __weak __typeof(self) weakSelf = self; - auto afterLoad = [weakSelf](jsi::Runtime &) { + auto afterLoad = [weakSelf, sourceURL](jsi::Runtime &) { [[NSNotificationCenter defaultCenter] postNotificationName:@"RCTInstanceDidLoadBundle" object:nil]; __strong __typeof(weakSelf) strongSelf = weakSelf; if (strongSelf) { @@ -620,9 +649,10 @@ - (void)_loadScriptFromSource:(RCTSource *)source // afterLoad runs on the JS thread; post on main like the legacy bridge so // RCTJavaScriptDidLoadNotification observers aren't invoked off-main. RCTExecuteOnMainQueue(^{ - [[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidLoadNotification - object:strongSelf - userInfo:bridgeProxy ? @{@"bridge" : bridgeProxy} : @{}]; + [[NSNotificationCenter defaultCenter] + postNotificationName:RCTJavaScriptDidLoadNotification + object:strongSelf + userInfo:RCTJavaScriptLoadUserInfo(bridgeProxy, sourceURL, nil)]; }); } }; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 65b1426db47e..fbb11ef915c5 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -1726,6 +1726,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index ec76e48de457..0cbd148c1add 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -1769,6 +1769,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index c8c92eb83ed1..89e81a3ff482 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -1725,6 +1725,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 3ebc82e69ba0..01c27539b951 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -1726,6 +1726,7 @@ interface RCTShadowView : public NSObject { interface RCTSource : public NSObject { public @property (assign, readonly) NSInteger filesChangedCount; public @property (assign, readonly) NSUInteger length; + public @property (copy, readonly) NSString* revisionId; public @property (strong, readonly) NSData* data; public @property (strong, readonly) NSURL* downloadedBundleFileURL; public @property (strong, readonly) NSURL* url;