@samitouri / QOS-React-2 / commits / dd5365878d

[DevTools] remove backend dependency from the global hook (#26563)

## Summary - #26234 is reverted and replaced with a better approach - introduce a new global devtools variable to decouple the global hook's dependency on backend/console.js, and add it to react-devtools-inline and react-devtools-standalone With this PR, I want to introduce a new principle to hook.js: we should always be alert when editing this file and avoid importing from other files. In the past, we try to inline a lot of the implementation because we use `.toString()` to inject this function from the extension (we still have some old comments left). Although it is no longer inlined that way, it has became now more important to keep it clean as it is a de facto global API people are using (9.9K files contains it on Github search as of today). **File size change for extension:** Before: 379K installHook.js After: 21K installHook.js 363K renderer.js

Mengdi Chen committed Apr 7, 2023 at 03:35 UTC dd5365878da2fe88a34dcdbb07d8297a78841da4
12 files changed +85 -40
packages/react-devtools-core/src/backend.js
+4
@@ -11,6 +11,7 @@ import Agent from 'react-devtools-shared/src/backend/agent';
11 import Bridge from 'react-devtools-shared/src/bridge';
12 import {installHook} from 'react-devtools-shared/src/hook';
13 import {initBackend} from 'react-devtools-shared/src/backend';
14 +import {installConsoleFunctionsToWindow} from 'react-devtools-shared/src/backend/console';
15 import {__DEBUG__} from 'react-devtools-shared/src/constants';
16 import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
17 import {getDefaultComponentFilters} from 'react-devtools-shared/src/utils';
@@ -38,6 +39,9 @@ type ConnectOptions = {
39 ...
40 };
41
42 +// Install a global variable to allow patching console early (during injection).
43 +// This provides React Native developers with components stacks even if they don't run DevTools.
44 +installConsoleFunctionsToWindow();
45 installHook(window);
46
47 const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
packages/react-devtools-extensions/chrome/manifest.json
+1
@@ -31,6 +31,7 @@
31 "panel.html",
32 "build/react_devtools_backend.js",
33 "build/proxy.js",
34 + "build/renderer.js",
35 "build/installHook.js"
36 ],
37 "matches": [
packages/react-devtools-extensions/edge/manifest.json
+1
@@ -31,6 +31,7 @@
31 "panel.html",
32 "build/react_devtools_backend.js",
33 "build/proxy.js",
34 + "build/renderer.js",
35 "build/installHook.js"
36 ],
37 "matches": [
packages/react-devtools-extensions/firefox/manifest.json
+1
@@ -32,6 +32,7 @@
32 "panel.html",
33 "build/react_devtools_backend.js",
34 "build/proxy.js",
35 + "build/renderer.js",
36 "build/installHook.js"
37 ],
38 "background": {
packages/react-devtools-extensions/src/background.js
+7
@@ -22,6 +22,13 @@ if (!IS_FIREFOX) {
22 runAt: 'document_start',
23 world: chrome.scripting.ExecutionWorld.MAIN,
24 },
25 + {
26 + id: 'renderer',
27 + matches: ['<all_urls>'],
28 + js: ['build/renderer.js'],
29 + runAt: 'document_start',
30 + world: chrome.scripting.ExecutionWorld.MAIN,
31 + },
32 ],
33 function () {
34 // When the content scripts are already registered, an error will be thrown.
packages/react-devtools-extensions/src/contentScripts/prepareInjection.js
+10 -2
@@ -1,6 +1,8 @@
1 /* global chrome */
2
3 import nullthrows from 'nullthrows';
4 +import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from 'react-devtools-shared/src/constants';
5 +import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
6 import {IS_FIREFOX} from '../utils';
7
8 // We run scripts on the page via the service worker (backgroud.js) for
@@ -109,9 +111,15 @@ window.addEventListener('pageshow', function ({target}) {
111 chrome.runtime.sendMessage(lastDetectionResult);
112 });
113
112 -// Inject a __REACT_DEVTOOLS_GLOBAL_HOOK__ global for React to interact with.
113 -// Only do this for HTML documents though, to avoid e.g. breaking syntax highlighting for XML docs.
114 if (IS_FIREFOX) {
115 + // If we have just reloaded to profile, we need to inject the renderer interface before the app loads.
116 + if (
117 + sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true'
118 + ) {
119 + injectScriptSync(chrome.runtime.getURL('build/renderer.js'));
120 + }
121 + // Inject a __REACT_DEVTOOLS_GLOBAL_HOOK__ global for React to interact with.
122 + // Only do this for HTML documents though, to avoid e.g. breaking syntax highlighting for XML docs.
123 switch (document.contentType) {
124 case 'text/html':
125 case 'application/xhtml+xml': {
packages/react-devtools-extensions/src/contentScripts/renderer.js new
+33
@@ -0,0 +1,33 @@
1 +/**
2 + * In order to support reload-and-profile functionality, the renderer needs to be injected before any other scripts.
3 + * Since it is a complex file (with imports) we can't just toString() it like we do with the hook itself,
4 + * So this entry point (one of the web_accessible_resources) provides a way to eagerly inject it.
5 + * The hook will look for the presence of a global __REACT_DEVTOOLS_ATTACH__ and attach an injected renderer early.
6 + * The normal case (not a reload-and-profile) will not make use of this entry point though.
7 + *
8 + * @flow
9 + */
10 +
11 +import {attach} from 'react-devtools-shared/src/backend/renderer';
12 +import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from 'react-devtools-shared/src/constants';
13 +import {sessionStorageGetItem} from 'react-devtools-shared/src/storage';
14 +
15 +if (
16 + sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true' &&
17 + !window.hasOwnProperty('__REACT_DEVTOOLS_ATTACH__')
18 +) {
19 + Object.defineProperty(
20 + window,
21 + '__REACT_DEVTOOLS_ATTACH__',
22 + ({
23 + enumerable: false,
24 + // This property needs to be configurable to allow third-party integrations
25 + // to attach their own renderer. Note that using third-party integrations
26 + // is not officially supported. Use at your own risk.
27 + configurable: true,
28 + get() {
29 + return attach;
30 + },
31 + }: Object),
32 + );
33 +}
packages/react-devtools-extensions/webpack.config.js
+1
@@ -55,6 +55,7 @@ module.exports = {
55 panel: './src/panel.js',
56 proxy: './src/contentScripts/proxy.js',
57 prepareInjection: './src/contentScripts/prepareInjection.js',
58 + renderer: './src/contentScripts/renderer.js',
59 installHook: './src/contentScripts/installHook.js',
60 },
61 output: {
packages/react-devtools-inline/src/backend.js
+4
@@ -3,6 +3,7 @@
3 import Agent from 'react-devtools-shared/src/backend/agent';
4 import Bridge from 'react-devtools-shared/src/bridge';
5 import {initBackend} from 'react-devtools-shared/src/backend';
6 +import {installConsoleFunctionsToWindow} from 'react-devtools-shared/src/backend/console';
7 import {installHook} from 'react-devtools-shared/src/hook';
8 import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor';
9
@@ -119,5 +120,8 @@ export function createBridge(contentWindow: any, wall?: Wall): BackendBridge {
120 }
121
122 export function initialize(contentWindow: any): void {
123 + // Install a global variable to allow patching console early (during injection).
124 + // This provides React Native developers with components stacks even if they don't run DevTools.
125 + installConsoleFunctionsToWindow();
126 installHook(contentWindow);
127 }
packages/react-devtools-shared/src/backend/console.js
+7
@@ -413,3 +413,10 @@ export function writeConsolePatchSettingsToWindow(
413 settings.hideConsoleLogsInStrictMode;
414 window.__REACT_DEVTOOLS_BROWSER_THEME__ = settings.browserTheme;
415 }
416 +
417 +export function installConsoleFunctionsToWindow(): void {
418 + window.__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__ = {
419 + patchConsoleUsingWindowValues,
420 + registerRendererWithConsole: registerRenderer,
421 + };
422 +}
packages/react-devtools-shared/src/backend/index.js
+1 -2
@@ -76,8 +76,7 @@ export function initBackend(
76 }
77
78 // Notify the DevTools frontend about new renderers.
79 - // This includes any that were attached early
80 - // (when SESSION_STORAGE_RELOAD_AND_PROFILE_KEY is set to true).
79 + // This includes any that were attached early (via __REACT_DEVTOOLS_ATTACH__).
80 if (rendererInterface != null) {
81 hook.emit('renderer-attached', {
82 id,
packages/react-devtools-shared/src/hook.js
+15 -36
@@ -1,8 +1,8 @@
1 /**
2 * Install the hook on window, which is an event emitter.
3 - * Note because Chrome content scripts cannot directly modify the window object,
4 - * we are evaling this function by inserting a script tag.
5 - * That's why we have to inline the whole event emitter implementation,
3 + * Note: this global hook __REACT_DEVTOOLS_GLOBAL_HOOK__ is a de facto public API.
4 + * It's especially important to avoid creating direct dependency on the DevTools Backend.
5 + * That's why we still inline the whole event emitter implementation,
6 * the string format implementation, and part of the console implementation here.
7 *
8 * @flow
@@ -17,14 +17,6 @@ import type {
17 RendererInterface,
18 } from './backend/types';
19
20 -import {
21 - patchConsoleUsingWindowValues,
22 - registerRenderer as registerRendererWithConsole,
23 -} from './backend/console';
24 -import {attach} from './backend/renderer';
25 -import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from './constants';
26 -import {sessionStorageGetItem} from './storage';
27 -
20 declare var window: any;
21
22 export function installHook(target: any): DevToolsHook | null {
@@ -340,37 +332,24 @@ export function installHook(target: any): DevToolsHook | null {
332 // * Disabling or marking logs during a double render in Strict Mode
333 // * Disable logging during re-renders to inspect hooks (see inspectHooksOfFiber)
334 //
343 - // For React Native, we intentionally patch early (during injection).
344 - // This provides React Native developers with components stacks even if they don't run DevTools.
345 - //
346 - // This won't work for DOM though, since this entire file is eval'ed and inserted as a script tag.
347 - // In that case, we'll only patch parts of the console that are needed during the first render
348 - // and patch everything else later (when the frontend attaches).
349 - //
350 - // Don't patch in test environments because we don't want to interfere with Jest's own console overrides.
351 - //
352 - // Note that because this function is inlined, this conditional check must only use static booleans.
353 - // Otherwise the extension will throw with an undefined error.
354 - // (See comments in the try/catch below for more context on inlining.)
355 - if (!__TEST__ && !__EXTENSION__) {
356 - try {
357 - // The installHook() function is injected by being stringified in the browser,
358 - // so imports outside of this function do not get included.
359 - //
360 - // Normally we could check "typeof patchConsole === 'function'",
361 - // but Webpack wraps imports with an object (e.g. _backend_console__WEBPACK_IMPORTED_MODULE_0__)
362 - // and the object itself will be undefined as well for the reasons mentioned above,
363 - // so we use try/catch instead.
335 + // Allow patching console early (during injection) to
336 + // provide developers with components stacks even if they don't run DevTools.
337 + if (target.hasOwnProperty('__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__')) {
338 + const {registerRendererWithConsole, patchConsoleUsingWindowValues} =
339 + target.__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__;
340 + if (
341 + typeof registerRendererWithConsole === 'function' &&
342 + typeof patchConsoleUsingWindowValues === 'function'
343 + ) {
344 registerRendererWithConsole(renderer);
345 patchConsoleUsingWindowValues();
366 - } catch (error) {}
346 + }
347 }
348
349 // If we have just reloaded to profile, we need to inject the renderer interface before the app loads.
350 // Otherwise the renderer won't yet exist and we can skip this step.
371 - if (
372 - sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true'
373 - ) {
351 + const attach = target.__REACT_DEVTOOLS_ATTACH__;
352 + if (typeof attach === 'function') {
353 const rendererInterface = attach(hook, id, renderer, target);
354 hook.rendererInterfaces.set(id, rendererInterface);
355 }