Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/react-native/Libraries/Utilities/HMRClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 => {
Expand Down
14 changes: 14 additions & 0 deletions packages/react-native/React/Base/RCTConstants.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
18 changes: 18 additions & 0 deletions packages/react-native/React/Base/RCTConstants.m
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

#import "RCTConstants.h"

#import <stdatomic.h>

NSString *const RCTPlatformName = @"ios";

NSString *const RCTUserInterfaceStyleDidChangeNotification = @"RCTUserInterfaceStyleDidChangeNotification";
Expand All @@ -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
*/
Expand Down
7 changes: 7 additions & 0 deletions packages/react-native/React/Base/RCTJavaScriptLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions packages/react-native/React/Base/RCTJavaScriptLoader.mm
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ @interface RCTSource () {
NSUInteger _length;
NSInteger _filesChangedCount;
NSURL *_downloadedBundleFileURL;
NSString *_revisionId;
}

@end
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions packages/react-native/ReactAndroid/api/ReactAndroid.api
Original file line number Diff line number Diff line change
Expand Up @@ -699,14 +699,18 @@ public abstract class com/facebook/react/bridge/JSBundleLoader {
public fun <init> ()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;
}
Expand Down Expand Up @@ -1823,6 +1827,7 @@ public final class com/facebook/react/devsupport/BundleDownloader$BundleInfo {
public fun <init> ()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;
}
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1220,6 +1220,7 @@ public class ReactHostImpl(
JSBundleLoader.createCachedBundleFromNetworkLoader(
bundleURL,
asyncDevSupportManager.downloadedJSBundleFile,
asyncDevSupportManager.downloadedJSBundleRevisionId,
)
taskCompletionSource.setResult(bundleLoader)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ internal class ReactInstance(
loadSynchronously: Boolean,
) {
context.sourceURL = sourceURL
ReactJavaScriptLoads.willExecute(sourceURL, fileName, bundleLoader.revisionId)
loadJSBundleFromFile(fileName, sourceURL)
}

Expand All @@ -325,6 +326,7 @@ internal class ReactInstance(
loadSynchronously: Boolean,
) {
context.sourceURL = assetURL
ReactJavaScriptLoads.willExecute(assetURL, null, null)
loadJSBundleFromAssets(assetManager, assetURL)
}

Expand Down Expand Up @@ -476,6 +478,7 @@ internal class ReactInstance(
}

fun registerSegment(segmentId: Int, path: String) {
ReactJavaScriptLoads.willExecute(path, path, null)
registerSegmentNative(segmentId, path)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<Listener>()

@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)
}
}
}
}
Loading
Loading