Skip to content

Commit

Permalink
[DevTools] use backend manager to support multiple backends in extens…
Browse files Browse the repository at this point in the history
…ion (facebook#26615)

In the extension, currently we do the following:
1. check whether there's at least one React renderer on the page
2. if yes, load the backend to the page
3. initialize the backend 

To support multiple versions of backends, we are changing it to:
1. check the versions of React renders on the page
2. load corresponding React DevTools backends that are shipped with the
extension; if they are not contained (usually prod builds of
prereleases), show a UI to allow users to load them from UI
3. initialize each of the backends

To enable this workflow, a backend will ignore React renderers that does
not match its version

This PR adds a new file "backendManager" in the extension for this
purpose.


------
I've tested it on Chrome, Edge and Firefox extensions
  • Loading branch information
mondaychen authored and AndyPengc12 committed Apr 15, 2024
1 parent 62637a7 commit 976cc42
Show file tree
Hide file tree
Showing 17 changed files with 308 additions and 138 deletions.
5 changes: 1 addition & 4 deletions packages/react-devtools-extensions/chrome/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@
"resources": [
"main.html",
"panel.html",
"build/react_devtools_backend.js",
"build/proxy.js",
"build/renderer.js",
"build/installHook.js"
"build/*.js"
],
"matches": [
"<all_urls>"
Expand Down
5 changes: 1 addition & 4 deletions packages/react-devtools-extensions/edge/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,7 @@
"resources": [
"main.html",
"panel.html",
"build/react_devtools_backend.js",
"build/proxy.js",
"build/renderer.js",
"build/installHook.js"
"build/*.js"
],
"matches": [
"<all_urls>"
Expand Down
5 changes: 1 addition & 4 deletions packages/react-devtools-extensions/firefox/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@
"web_accessible_resources": [
"main.html",
"panel.html",
"build/react_devtools_backend.js",
"build/proxy.js",
"build/renderer.js",
"build/installHook.js"
"build/*.js"
],
"background": {
"scripts": [
Expand Down
120 changes: 22 additions & 98 deletions packages/react-devtools-extensions/src/backend.js
Original file line number Diff line number Diff line change
@@ -1,109 +1,33 @@
// Do not use imports or top-level requires here!
// Running module factories is intentionally delayed until we know the hook exists.
// This is to avoid issues like: https://github.com/facebook/react-devtools/issues/1039
/**
* 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.
*
* @flow
*/

// @flow strict-local
import type {DevToolsHook} from 'react-devtools-shared/src/backend/types';

'use strict';
import Agent from 'react-devtools-shared/src/backend/agent';
import Bridge from 'react-devtools-shared/src/bridge';
import {initBackend} from 'react-devtools-shared/src/backend';
import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';

let welcomeHasInitialized = false;
import {COMPACT_VERSION_NAME} from './utils';

// $FlowFixMe[missing-local-annot]
function welcome(event: $FlowFixMe) {
if (
event.source !== window ||
event.data.source !== 'react-devtools-content-script'
) {
return;
}

// In some circumstances, this method is called more than once for a single welcome message.
// The exact circumstances of this are unclear, though it seems related to 3rd party event batching code.
//
// Regardless, call this method multiple times can cause DevTools to add duplicate elements to the Store
// (and throw an error) or worse yet, choke up entirely and freeze the browser.
//
// The simplest solution is to ignore the duplicate events.
// To be clear, this SHOULD NOT BE NECESSARY, since we remove the event handler below.
//
// See https://github.com/facebook/react/issues/24162
if (welcomeHasInitialized) {
console.warn(
'React DevTools detected duplicate welcome "message" events from the content script.',
);
return;
}

welcomeHasInitialized = true;

window.removeEventListener('message', welcome);

setup(window.__REACT_DEVTOOLS_GLOBAL_HOOK__);
}

window.addEventListener('message', welcome);
setup(window.__REACT_DEVTOOLS_GLOBAL_HOOK__);

function setup(hook: any) {
function setup(hook: ?DevToolsHook) {
if (hook == null) {
// DevTools didn't get injected into this page (maybe b'c of the contentType).
return;
}
const Agent = require('react-devtools-shared/src/backend/agent').default;
const Bridge = require('react-devtools-shared/src/bridge').default;
const {initBackend} = require('react-devtools-shared/src/backend');
const setupNativeStyleEditor =
require('react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor').default;

const bridge = new Bridge<$FlowFixMe, $FlowFixMe>({
listen(fn) {
const listener = (event: $FlowFixMe) => {
if (
event.source !== window ||
!event.data ||
event.data.source !== 'react-devtools-content-script' ||
!event.data.payload
) {
return;
}
fn(event.data.payload);
};
window.addEventListener('message', listener);
return () => {
window.removeEventListener('message', listener);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
window.postMessage(
{
source: 'react-devtools-bridge',
payload: {event, payload},
},
'*',
transferable,
);
},
});

const agent = new Agent(bridge);
agent.addListener('shutdown', () => {
// If we received 'shutdown' from `agent`, we assume the `bridge` is already shutting down,
// and that caused the 'shutdown' event on the `agent`, so we don't need to call `bridge.shutdown()` here.
hook.emit('shutdown');
hook.backends.set(COMPACT_VERSION_NAME, {
Agent,
Bridge,
initBackend,
setupNativeStyleEditor,
});

initBackend(hook, agent, window);

// Let the frontend know that the backend has attached listeners and is ready for messages.
// This covers the case of syncing saved values after reloading/navigating while DevTools remain open.
bridge.send('extensionBackendInitialized');

// Setup React Native style editor if a renderer like react-native-web has injected it.
if (hook.resolveRNStyle) {
setupNativeStyleEditor(
bridge,
agent,
hook.resolveRNStyle,
hook.nativeStyleEditorValidAttributes,
);
}
hook.emit('devtools-backend-installed', COMPACT_VERSION_NAME);
}
164 changes: 164 additions & 0 deletions packages/react-devtools-extensions/src/backendManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/**
* 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.
*
* @flow
*/

import type {
DevToolsHook,
ReactRenderer,
} from 'react-devtools-shared/src/backend/types';
import {hasAssignedBackend} from 'react-devtools-shared/src/backend/utils';
import {COMPACT_VERSION_NAME} from './utils';

let welcomeHasInitialized = false;

// $FlowFixMe[missing-local-annot]
function welcome(event: $FlowFixMe) {
if (
event.source !== window ||
event.data.source !== 'react-devtools-content-script'
) {
return;
}

// In some circumstances, this method is called more than once for a single welcome message.
// The exact circumstances of this are unclear, though it seems related to 3rd party event batching code.
//
// Regardless, call this method multiple times can cause DevTools to add duplicate elements to the Store
// (and throw an error) or worse yet, choke up entirely and freeze the browser.
//
// The simplest solution is to ignore the duplicate events.
// To be clear, this SHOULD NOT BE NECESSARY, since we remove the event handler below.
//
// See https://github.com/facebook/react/issues/24162
if (welcomeHasInitialized) {
console.warn(
'React DevTools detected duplicate welcome "message" events from the content script.',
);
return;
}

welcomeHasInitialized = true;

window.removeEventListener('message', welcome);

setup(window.__REACT_DEVTOOLS_GLOBAL_HOOK__);
}

window.addEventListener('message', welcome);

function setup(hook: ?DevToolsHook) {
// this should not happen, but Chrome can be weird sometimes
if (hook == null) {
return;
}

// register renderers that have already injected themselves.
hook.renderers.forEach(renderer => {
registerRenderer(renderer);
});
updateRequiredBackends();

// register renderers that inject themselves later.
hook.sub('renderer', ({renderer}) => {
registerRenderer(renderer);
updateRequiredBackends();
});

// listen for backend installations.
hook.sub('devtools-backend-installed', version => {
activateBackend(version, hook);
updateRequiredBackends();
});
}

const requiredBackends = new Set<string>();

function registerRenderer(renderer: ReactRenderer) {
let version = renderer.reconcilerVersion || renderer.version;
if (!hasAssignedBackend(version)) {
version = COMPACT_VERSION_NAME;
}
requiredBackends.add(version);
}

function activateBackend(version: string, hook: DevToolsHook) {
const backend = hook.backends.get(version);
if (!backend) {
throw new Error(`Could not find backend for version "${version}"`);
}
const {Agent, Bridge, initBackend, setupNativeStyleEditor} = backend;
const bridge = new Bridge({
listen(fn) {
const listener = (event: $FlowFixMe) => {
if (
event.source !== window ||
!event.data ||
event.data.source !== 'react-devtools-content-script' ||
!event.data.payload
) {
return;
}
fn(event.data.payload);
};
window.addEventListener('message', listener);
return () => {
window.removeEventListener('message', listener);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
window.postMessage(
{
source: 'react-devtools-bridge',
payload: {event, payload},
},
'*',
transferable,
);
},
});

const agent = new Agent(bridge);
agent.addListener('shutdown', () => {
// If we received 'shutdown' from `agent`, we assume the `bridge` is already shutting down,
// and that caused the 'shutdown' event on the `agent`, so we don't need to call `bridge.shutdown()` here.
hook.emit('shutdown');
});

initBackend(hook, agent, window);

// Setup React Native style editor if a renderer like react-native-web has injected it.
if (typeof setupNativeStyleEditor === 'function' && hook.resolveRNStyle) {
setupNativeStyleEditor(
bridge,
agent,
hook.resolveRNStyle,
hook.nativeStyleEditorValidAttributes,
);
}

// Let the frontend know that the backend has attached listeners and is ready for messages.
// This covers the case of syncing saved values after reloading/navigating while DevTools remain open.
bridge.send('extensionBackendInitialized');

// this backend is activated
requiredBackends.delete(version);
}

// tell the service worker which versions of backends are needed for the current page
function updateRequiredBackends() {
window.postMessage(
{
source: 'react-devtools-backend-manager',
payload: {
type: 'react-devtools-required-backends',
versions: Array.from(requiredBackends),
},
},
'*',
);
}
38 changes: 31 additions & 7 deletions packages/react-devtools-extensions/src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

'use strict';

import {IS_FIREFOX} from './utils';
import {IS_FIREFOX, EXTENSION_CONTAINED_VERSIONS} from './utils';

const ports = {};

Expand Down Expand Up @@ -179,26 +179,50 @@ chrome.runtime.onMessage.addListener((request, sender) => {
if (request.hasDetectedReact) {
setIconAndPopup(request.reactBuildType, id);
} else {
const devtools = ports[id]?.devtools;
switch (request.payload?.type) {
case 'fetch-file-with-cache-complete':
case 'fetch-file-with-cache-error':
// Forward the result of fetch-in-page requests back to the extension.
const devtools = ports[id]?.devtools;
if (devtools) {
devtools.postMessage(request);
}
devtools?.postMessage(request);
break;
// This is sent from the backend manager running on a page
case 'react-devtools-required-backends':
const backendsToDownload = [];
request.payload.versions.forEach(version => {
if (EXTENSION_CONTAINED_VERSIONS.includes(version)) {
if (!IS_FIREFOX) {
// equivalent logic for Firefox is in prepareInjection.js
chrome.scripting.executeScript({
target: {tabId: id},
files: [`/build/react_devtools_backend_${version}.js`],
world: chrome.scripting.ExecutionWorld.MAIN,
});
}
} else {
backendsToDownload.push(version);
}
});
// Request the necessary backends in the extension DevTools UI
// TODO: handle this message in main.js to build the UI
devtools?.postMessage({
payload: {
type: 'react-devtools-additional-backends',
versions: backendsToDownload,
},
});
break;
}
}
} else if (request.payload?.tabId) {
const tabId = request.payload?.tabId;
// This is sent from the devtools page when it is ready for injecting the backend
if (request.payload.type === 'react-devtools-inject-backend') {
if (request.payload.type === 'react-devtools-inject-backend-manager') {
if (!IS_FIREFOX) {
// equivalent logic for Firefox is in prepareInjection.js
chrome.scripting.executeScript({
target: {tabId},
files: ['/build/react_devtools_backend.js'],
files: ['/build/backendManager.js'],
world: chrome.scripting.ExecutionWorld.MAIN,
});
}
Expand Down
Loading

0 comments on commit 976cc42

Please sign in to comment.