// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
// changes to one module should be reflected in the others.

// TODO: Rename this module and the corresponding Fiber one to "Thenable"
// instead of "Wakeable". Or some other more appropriate name.

import type {
  Thenable,
  PendingThenable,
  FulfilledThenable,
  RejectedThenable,
} from 'shared/ReactTypes';

import {enableAsyncDebugInfo} from 'shared/ReactFeatureFlags';

import noop from 'shared/noop';

export type ThenableSt

uspense Exception: This is not a real error! It's an implementation " +
    'detail of `use` to interrupt the current render. You must either ' +
    'rethrow it immediately, or move the `use` call outside of the ' +
    '`try/catch` block. Capturing witho

ate = Array<Thenable<any>>;

// An error that is thrown (e.g. by `use`) to trigger Suspense. If we
// detect this is caught by userspace, we'll log a warning in development.
export const SuspenseException: mixed = new Error(
  "S


export type Destination = ReadableStreamController;

export type PrecomputedChunk = Uint8Array;
export opaque type Chunk = Uint8Array;
export type BinaryChunk = Uint8Array;

const channel = new MessageChannel();
const taskQueue = [];
channel.port1.onmessage = () => {
  const task = taskQueue.shift();
  if (task) {
    task();
  }
};

export function scheduleWork(callback: () => void) {
  taskQueue.push(callback);
  channel.port2.postMessage(null);
}

function handleErrorInNextTick(error: any) {
  setTimeout

se.resolve(null).then(callback).catch(handleErrorInNextTick);
      };

export function flushBuffered(destination: Destination) {
  // WHATWG Streams do not yet have a way to flush the underlying
  // transform streams. https://github.com/whatwg/streams/is

(() => {
    throw error;
  });
}

const LocalPromise = Promise;

export const scheduleMicrotask: (callback: () => void) => void =
  typeof queueMicrotask === 'function'
    ? queueMicrotask
    : callback => {
        LocalPromi


ight (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
 */

let hasConfirmedEval = false;
export function checkEvalAvailabilityOnceDev(): void {
  if (__DEV__) {
    if (!hasConfirmedEval) {
      hasConfirmedEval = true;
      try {
        // eslint-disable-next-line no-eval
        (0, eval)('null');
      } catch {
        console.error(
          'eval() is not supported i

) in development mode for various debugging features ' +
            'like reconstructing callstacks from a different environment.\n' +
            'React will never use eval() in production mode',
        );
      }
    }
  } else {
    // These errors sh

n this environment. ' +
            'This can happen if you started the Node.js process with --disallow-code-generation-from-strings, ' +
            'or if `eval` was patched by other means. ' +
            'React requires eval(


import type {ReactNodeList} from 'shared/ReactTypes';
import type {LazyComponent} from 'react/src/ReactLazy';
import type {ErrorInfo} from 'react-server/src/ReactFizzServer';

import ReactVersion from 'shared/ReactVersion';

import ReactSharedInternalsServer from 'react-server/src/ReactSharedInternalsServer';
import ReactSharedInternalsClient from 'shared/ReactSharedInternals';

import {
  createRequest as createFlightRequest,
  startWork as startFlightWork,
  startFlowing as startFlightFlowing,
  abort as

Chunk,
  close as closeFlight,
} from 'react-client/src/ReactFlightClient';

import {
  createRequest as createFizzRequest,
  startWork as startFizzWork,
  startFlowing as startFizzFlowing,
  abort as abortFizz,
} from 'react-server/src/ReactFizzServer';

abortFlight,
} from 'react-server/src/ReactFlightServer';

import {
  createResponse as createFlightResponse,
  createStreamState as createFlightStreamState,
  getRoot as getFlightRoot,
  processStringChunk as processFlightString


ct-core
 */

'use strict';

let React;
let ReactMarkup;

function normalizeCodeLocInfo(str) {
  return (
    str &&
    String(str).replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) {
      return '\n    in ' + name + ' (at **)';
    })
  );
}

if (!__EXPERIMENTAL__) {
  it('should not be built in stable', () => {
    try {
      require('react-markup');
    } catch (x) {
      return;
    }
    throw new Error('Expected react-markup not to exist in stable.');
  });
} else {
  describe('ReactMarkup

Component() {
        return
hello world
;
      }

      const html = await ReactMarkup.experimental_renderToHTML(<Component />);
      expect(html).toBe('
hello world
');
    });

    it('should be able to render a large string', asyn

', () => {
    beforeEach(() => {
      jest.resetModules();
      React = require('react');
      ReactMarkup = require('react-markup');
    });

    it('should be able to render a simple component', async () => {
      function


ct-core
 */

'use strict';

global.TextDecoder = require('util').TextDecoder;
global.TextEncoder = require('util').TextEncoder;

let React;
let ReactMarkup;

function normalizeCodeLocInfo(str) {
  return (
    str &&
    String(str).replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) {
      return '\n    in ' + name + ' (at **)';
    })
  );
}

if (!__EXPERIMENTAL__) {
  it('should not be built in stable', () => {
    try {
      require('react-markup');
    } catch (x) {
      return;
    }
    thr

ct', () => require('react/react.react-server'));
      if (__EXPERIMENTAL__) {
        jest.mock('react-markup', () =>
          require('react-markup/react-markup.react-server'),
        );
      }

      React = require('react');
      if (__EXPERIMENTAL

ow new Error('Expected react-markup not to exist in stable.');
  });
} else {
  describe('ReactMarkup', () => {
    beforeEach(() => {
      jest.resetModules();
      // We run in the react-server condition.
      jest.mock('rea


ing,
  url: string,
};

type TransformSourceFunction = (
  Source,
  TransformSourceContext,
  TransformSourceFunction,
) => Promise<{source: Source}>;

type LoadContext = {
  conditions: Array<string>,
  format: string | null | void,
  importAssertions: Object,
};

type LoadFunction = (
  string,
  LoadContext,
  LoadFunction,
) => Promise<{format: string, shortCircuit?: boolean, source: Source}>;

type Source = string | ArrayBuffer | Uint8Array;

let warnedAboutConditionsFlag = false;

let stashedGetSourc

  // We stash this in case we end up needing to resolve export * statements later.
  stashedResolve = defaultResolve;

  if (!context.conditions.includes('react-server')) {
    context = {
      ...context,
      conditions: [...context.conditions, 'react

e: null | GetSourceFunction = null;
let stashedResolve: null | ResolveFunction = null;

export async function resolve(
  specifier: string,
  context: ResolveContext,
  defaultResolve: ResolveFunction,
): Promise<{url: string}> {


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {ReactClientValue} from 'react-server/src/ReactFlightServer';

export type ServerReference<T: Function> = T & {
  $$typeof: symbol,
  $$id: string,
  $$bound: null | Array<ReactClientValue>,
  $$location?: Error,
};

// eslint-disable-next-line no-unused-vars
export type ClientReference<T> = {
  $$typeof: symbol,
  $$id: string,
};

const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference

ference: Object): boolean {
  return reference.$$typeof === SERVER_REFERENCE_TAG;
}

export function registerClientReference<T>(
  proxyImplementation: any,
  id: string,
  exportName: string,
): ClientReference<T> {
  return Object.defineProperties(proxyI

');
const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');

export function isClientReference(reference: Object): boolean {
  return reference.$$typeof === CLIENT_REFERENCE_TAG;
}

export function isServerReference(re


/ReactFlightServerConfigESMBundler';
import type {ServerManifest} from 'react-client/src/ReactFlightClientConfig';
import type {Busboy} from 'busboy';
import type {Writable} from 'stream';
import type {Thenable} from 'shared/ReactTypes';

import type {Duplex} from 'stream';

import {Readable} from 'stream';

import {
  createRequest,
  createPrerenderRequest,
  startWork,
  startFlowing,
  startFlowingDebug,
  stopFlowing,
  abort,
  resolveDebugMessage,
  closeDebugChannel,
} from 'react-server/src/ReactFl

ction,
  decodeFormState,
} from 'react-server/src/ReactFlightActionServer';

export {
  registerServerReference,
  registerClientReference,
} from '../ReactFlightESMReferences';

import {
  createStringDecoder,
  readPartialStringChunk,
  readFinalStringC

ightServer';

import {
  createResponse,
  reportGlobalError,
  close,
  resolveField,
  resolveFileInfo,
  resolveFileChunk,
  resolveFileComplete,
  getRoot,
} from 'react-server/src/ReactFlightReplyServer';

import {
  decodeA


 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 {ReactClientValue} from 'react-server/src/ReactFlightServer';

import type {
  ClientReference,
  ServerReference,
} from '../ReactFlightESMReferences';

export type {ClientReference, ServerReference};

export type ClientManifest = string; // base URL on the file system

export type ServerReferenceId = string;

export t

tion getClientReferenceKey(
  reference: ClientReference<any>,
): ClientReferenceKey {
  return reference.$$id;
}

export function resolveClientReferenceMetadata<T>(
  config: ClientManifest,
  clientReference: ClientReference<T>,
): ClientReferenceMetadat

ype ClientReferenceMetadata = [
  string, // module path
  string, // export name
];

export type ClientReferenceKey = string;

export {
  isClientReference,
  isServerReference,
} from '../ReactFlightESMReferences';

export func


import type {
  Thenable,
  FulfilledThenable,
  RejectedThenable,
  ReactDebugInfo,
  ReactIOInfo,
  ReactAsyncInfo,
} from 'shared/ReactTypes';

import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig';

export type ServerConsumerModuleMap = string; // Module root path

export type ServerManifest = string; // Module root path

export type ServerReferenceId = string;

import {prepareDestinationForModuleImpl} from 'react-client/src/ReactFlightClientConfig';

export opaque type ClientRefer

s to defined here in this file instead of just
// being exported directly from the WebpackDestination... file is because the
// ClientReferenceMetadata is opaque and we can't unwrap it there.
// This should get inlined and we could also just implement an u

enceMetadata = [
  string, // module path
  string, // export name
];

// eslint-disable-next-line no-unused-vars
export opaque type ClientReference<T> = {
  specifier: string,
  name: string,
};

// The reason this function need


(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 {preinitModuleForSSR} from 'react-client/src/ReactFlightClientConfig';

export type ModuleLoading =
  | null
  | string
  | {
      prefix: string,
      crossOrigin?: string,
    };

export function prepareDestinationForModuleImpl(
  moduleLoading: ModuleLoading,
  // Chunks are double-indexed [..., idx, filenamex,

,
) {
  if (typeof moduleLoading === 'string') {
    preinitModuleForSSR(moduleLoading + mod, nonce, undefined);
  } else if (moduleLoading !== null) {
    preinitModuleForSSR(
      moduleLoading.prefix + mod,
      nonce,
      moduleLoading.crossOrigin,

idy, filenamey, ...]
  mod: string,
  nonce: ?string


import type {Thenable} from 'shared/ReactTypes.js';

import type {
  DebugChannel,
  DebugChannelCallback,
  FindSourceMapURLCallback,
  Response as FlightResponse,
} from 'react-client/src/ReactFlightClient';

import type {ReactServerValue} from 'react-client/src/ReactFlightReplyClient';

import {
  createResponse,
  createStreamState,
  getRoot,
  reportGlobalError,
  processBinaryChunk,
  processStringChunk,
  close,
  injectIntoDevTools,
} from 'react-client/src/ReactFlightClient';

import {processReply

ightTemporaryReferences';

export {createTemporaryReferenceSet} from 'react-client/src/ReactFlightTemporaryReferences';

export type {TemporaryReferenceSet};

type CallServerCallback = <A, T>(string, args: A) => Promise<T>;

export type Options = {
  modul

} from 'react-client/src/ReactFlightReplyClient';

export {
  createServerReference,
  registerServerReference,
} from 'react-client/src/ReactFlightReplyClient';

import type {TemporaryReferenceSet} from 'react-client/src/ReactFl


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Thenable, ReactCustomFormAction} from 'shared/ReactTypes.js';

import type {
  DebugChannel,
  FindSourceMapURLCallback,
  Response,
} from 'react-client/src/ReactFlightClient';

import type {Readable} from 'stream';

import {
  createResponse,
  createStreamState,
  getRoot,
  reportGlobalError,
  processStringChunk,
  processBinaryChunk,
  close,
} from 'react-client/src/ReactFlightClient';

Error(
    'Server Functions cannot be called during initial render. ' +
      'This would create a fetch waterfall. Try to use a Server Component ' +
      'to pass data to Client Components instead.',
  );
}

export function createServerReference<A: Iter

import {createServerReference as createServerReferenceImpl} from 'react-client/src/ReactFlightReplyClient';

export {registerServerReference} from 'react-client/src/ReactFlightReplyClient';

function noServerCall() {
  throw new


ensureDir, move, remove, pathExistsSync} = require('fs-extra');
const {join, resolve, basename} = require('path');
const {getGitCommit} = require('./utils');

// These files are copied along with Webpack-bundled files
// to produce the final web extension
const STATIC_FILES = ['icons', 'popups', 'main.html', 'panel.html'];

/**
 * Ensures that a local build of the dependencies exist either by downloading
 * or running a local build via one of the `react-build-fordevtools*` scripts.
 */
const ensureLocalBuil

-channels.js
  const currentBuildDir = resolve(
    __dirname,
    '..',
    '..',
    'build',
    'oss-experimental',
  );

  if (pathExistsSync(buildDir)) {
    return; // all good.
  }

  if (pathExistsSync(currentBuildDir)) {
    await ensureDir(build

d = async () => {
  const buildDir = resolve(__dirname, '..', '..', 'build');
  const nodeModulesDir = join(buildDir, 'node_modules');

  // TODO: remove this check whenever the CI pipeline is complete.
  // See build-all-release


nv node

'use strict';

const {exec, execSync} = require('child_process');
const {readFileSync, writeFileSync} = require('fs');
const {join} = require('path');
const shell = require('shelljs');
const main = async buildId => {
  const root = join(__dirname, buildId);
  const buildPath = join(root, 'build');

  execSync(`node ${join(root, './build')}`, {
    cwd: __dirname,
    env: {
      ...process.env,
      NODE_ENV: 'production',
    },
    stdio: 'inherit',
  });
  shell.cp(join(root, 'now.json'), join

 date = new Date();
  date = `${date.toLocaleDateString()} – ${date.toLocaleTimeString()}`;

  const installationInstructions =
    buildId === 'chrome'
      ? readFileSync(join(__dirname, 'deploy.chrome.html'))
      : readFileSync(join(__dirname, 'deplo

(buildPath, 'now.json'));
  const file = readFileSync(join(root, 'now.json'));
  const json = JSON.parse(file);
  const alias = json.alias[0];

  const commit = execSync('git rev-parse HEAD').toString().trim().slice(0, 7);

  let


 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.
 */

const {execSync} = require('child_process');
const {existsSync, readFileSync} = require('fs');
const {resolve} = require('path');

const GITHUB_URL = 'https://github.com/facebook/react';

function getGitCommit() {
  try {
    return execSync('git show -s --no-show-signature --format=%h')
      .toString()
      .trim();
  } catch (error) {

IT_SHA file
    const commitShaPath = resolve(__dirname, '..', '..', 'build', 'COMMIT_SHA');
    if (!existsSync(commitShaPath)) {
      throw new Error(
        'Could not find build/COMMIT_SHA file. Did you run scripts/release/download-experimental-build

 // Mozilla runs this command from a git archive.
    // In that context, there is no Git context.
    // Using the commit hash specified to download-experimental-build.js script as a fallback.

    // Try to read from build/COMM


quire('./utils');
const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils');
const SourceMapIgnoreListPlugin = require('react-devtools-shared/SourceMapIgnoreListPlugin');
const {StatsWriterPlugin} = require('webpack-stats-plugin');

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  console.error('NODE_ENV not set');
  process.exit(1);
}

const builtModulesDir = resolve(
  __dirname,
  '..',
  '..',
  'build',
  'oss-experimental',
);

const __DEV__ = NODE_ENV === 'development';

cons

nst IS_FIREFOX = process.env.IS_FIREFOX === 'true';
const IS_EDGE = process.env.IS_EDGE === 'true';
const IS_INTERNAL_VERSION = process.env.FEATURE_FLAG_TARGET === 'extension-fb';

const featureFlagTarget = process.env.FEATURE_FLAG_TARGET || 'extension-oss

t DEVTOOLS_VERSION = getVersionString(process.env.DEVTOOLS_VERSION);

const EDITOR_URL = process.env.EDITOR_URL || null;
const LOGGING_URL = process.env.LOGGING_URL || null;

const IS_CHROME = process.env.IS_CHROME === 'true';
co


/bin/env node

'use strict';

const chalk = require('chalk');
const {execSync} = require('child_process');
const {existsSync} = require('fs');
const {isAbsolute, join, relative} = require('path');
const {argv} = require('yargs');
const build = require('../build');

const main = async () => {
  const {crx, keyPath} = argv;

  if (crx) {
    if (!keyPath || !existsSync(keyPath)) {
      console.error('Must specify a key file (.pem) to build CRX');
      process.exit(1);
    }
  }

  await build('chrome');

e,
      '..',
      '..',
      '..',
      'node_modules',
      '.bin',
      'crx'
    );

    execSync(
      `${crxPath} pack ./unpacked -o ReactDevTools.crx -p ${safeKeyPath}`,
      {
        cwd,
      }
    );
  }

  console.log(chalk.green('\nTh

if (crx) {
    const cwd = join(__dirname, 'build');

    let safeKeyPath = keyPath;
    if (!isAbsolute(keyPath)) {
      safeKeyPath = join(relative(cwd, process.cwd()), keyPath);
    }

    const crxPath = join(
      __dirnam


usr/bin/env node

'use strict';

const chalk = require('chalk');
const {execSync} = require('child_process');
const {join} = require('path');
const {argv} = require('yargs');

const build = require('../build');

const main = async () => {
  const {crx} = argv;

  await build('edge');

  const cwd = join(__dirname, 'build');
  if (crx) {
    const crxPath = join(__dirname, '..', 'node_modules', '.bin', 'crx');

    execSync(`${crxPath} pack ./unpacked -o ReactDevTools.crx`, {
      cwd,
    });
  }

  consol

veloper mode"'));
  console.log(chalk.yellow('Click "LOAD UNPACKED"'));
  console.log(chalk.yellow('Select extension folder - ' + cwd + '\\unpacked'));

  console.log(chalk.green('\nYou can test this build by running:'));
  console.log(chalk.gray('\n# From

e.log(chalk.green('\nThe Microsoft Edge extension has been built!'));

  console.log(chalk.green('\nTo load this extension:'));
  console.log(chalk.yellow('Navigate to edge://extensions/'));
  console.log(chalk.yellow('Enable "De


!/usr/bin/env node

'use strict';

const open = require('open');
const os = require('os');
const osName = require('os-name');
const {resolve} = require('path');
const {argv} = require('yargs');

const EXTENSION_PATH = resolve('./edge/build/unpacked');
const START_URL = argv.url || 'https://react.dev/';

const extargs = `--load-extension=${EXTENSION_PATH}`;

const osname = osName(os.platform());
let appname;

if (osname && osname.toLocaleLowerCase().startsWith('windows')) {
  appname = 'msedge';
} else if (o

e.toLocaleLowerCase().startsWith('mac')) {
  appname = 'Microsoft Edge';
} else if (osname && osname.toLocaleLowerCase().startsWith('linux')) {
  //Coming soon
}

if (appname) {
  (async () => {
    await open(START_URL, {app: [appname, extargs]});
  })();


* 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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-esm';

export * from 'react-client/src/ReactFlightClientStreamConfigNode';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigNo

from 'react-server-dom-esm/src/client/ReactFlightClientConfigBundlerESM';
export * from 'react-server-dom-esm/src/client/ReactFlightClientConfigTargetESMServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWit


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

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

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';

import {COMPACT_VERSION_NAME} fro

OOK__);

function setup(hook: ?DevToolsHook) {
  if (hook == null) {
    return;
  }

  hook.backends.set(COMPACT_VERSION_NAME, {
    Agent,
    Bridge,
    initBackend,
    setupNativeStyleEditor,
  });

  hook.emit('devtools-backend-installed', COMPACT_V

m './utils';

setup(window.__REACT_DEVTOOLS_GLOBAL_H


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export type EvalScriptIds =
  | 'checkIfReactPresentInInspectedWindow'
  | 'reload'
  | 'setBrowserSelectionFromReact'
  | 'setReactSelectionFromBrowser'
  | 'viewAttributeSource'
  | 'viewElementSource';

/*
 .fn for fallback in Content Script context
 .code for chrome.devtools.inspectedWindow.eval()
*/
type EvalScriptEntry = {
  fn: (...args: any[]) => any,
  code: (...args: any[]) => string,
};

/*
  Can

tInInspectedWindow: {
    fn: () =>
      window.__REACT_DEVTOOLS_GLOBAL_HOOK__ &&
      window.__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.size > 0,
    code: () =>
      'window.__REACT_DEVTOOLS_GLOBAL_HOOK__ &&' +
      'window.__REACT_DEVTOOLS_GLOBAL_HOOK

 not access `Developer Tools Console API` (e.g., inspect(), $0) in this context.
  So some fallback functions are no-op or throw error.
*/
export const evalScripts: {[key: EvalScriptIds]: EvalScriptEntry} = {
  checkIfReactPresen


*/

import type {BrowserTheme} from 'react-devtools-shared/src/devtools/views/DevTools';

export function getBrowserTheme(): BrowserTheme {
  if (__IS_CHROME__) {
    // chrome.devtools.panels added in Chrome 18.
    // chrome.devtools.panels.themeName added in Chrome 54.
    return chrome.devtools.panels.themeName === 'dark' ? 'dark' : 'light';
  } else {
    // chrome.devtools.panels.themeName added in Firefox 55.
    // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/devtools.panels/themeNa

) {
      switch (chrome.devtools.panels.themeName) {
        case 'dark':
          return 'dark';
        default:
          return 'light';
      }
    }
  }
}

export const COMPACT_VERSION_NAME = 'compact';
export const EXTENSION_CONTAINED_VERSIONS = [

me
    if (chrome.devtools && chrome.devtools.panels


 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 {exec} from 'child-process-promise';
import {readFileSync} from 'fs';
import path from 'path';
import {rimrafSync} from 'rimraf';

describe('ignoreList source map extension', () => {
  jest.setTimeout(60 * 1000);

  const pathToExtensionsPackage = path.resolve(__dirname, '..', '..');
  const pathToChromeExtensionBuild = path

ync(pathToChromeExtensionBuild);
  });

  describe('for dev builds', () => {
    it('should not ignore list anything', async () => {
      await exec('yarn build:chrome:local', {
        cwd: pathToExtensionsPackage,
      });

      const sourceMapJSON =

.join(
    pathToExtensionsPackage,
    'chrome/build',
  );
  const pathToSourceMap = path.resolve(
    pathToChromeExtensionBuild,
    'unpacked/build/react_devtools_backend_compact.js.map',
  );

  afterAll(() => {
    rimrafS


ight (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
 */

export function cloneStyleTags(): Array<HTMLLinkElement | HTMLStyleElement> {
  const tags: Array<HTMLLinkElement | HTMLStyleElement> = [];

  // eslint-disable-next-line no-for-of-loops/no-for-of-loops
  for (const linkTag of document.getElementsByTagName('link')) {
    if (linkTag.rel === 'stylesheet') {
      const

eValue);
      }

      tags.push(newLinkTag);
    }
  }

  // eslint-disable-next-line no-for-of-loops/no-for-of-loops
  for (const styleTag of document.getElementsByTagName('style')) {
    const newStyleTag = document.createElement('style');

    // esli

newLinkTag = document.createElement('link');

      // eslint-disable-next-line no-for-of-loops/no-for-of-loops
      for (const attribute of linkTag.attributes) {
        newLinkTag.setAttribute(attribute.nodeName, attribute.nod


InInspectedWindow} from './evalInInspectedWindow';

export function setBrowserSelectionFromReact() {
  // This is currently only called on demand when you press "view DOM".
  // In the future, if Chrome adds an inspect() that doesn't switch tabs,
  // we could make this happen automatically when you select another component.
  evalInInspectedWindow(
    'setBrowserSelectionFromReact',
    [],
    (didSelectionChange, evalError) => {
      if (evalError) {
        console.error(evalError);
      }
    },
  )

    'setReactSelectionFromBrowser',
    [],
    (didSelectionChange, evalError) => {
      if (evalError) {
        console.error(evalError);
      } else if (didSelectionChange) {
        if (!bridge) {
          console.error(
            'Browser eleme

;
}

export function setReactSelectionFromBrowser(bridge) {
  // When the user chooses a different node in the browser Elements tab,
  // copy it over to the hook object so that we can sync the selection.
  evalInInspectedWindow(


iates.
 *
 * 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 {EvalScriptIds} from '../evalScripts';

import {evalScripts} from '../evalScripts';

type ExceptionInfo = {
  code: ?string,
  description: ?string,
  isError: boolean,
  isException: boolean,
  value: any,
};

const EVAL_TIMEOUT = 1000 * 10;

let evalRequestId = 0;
const evalRequestCallbacks = new Map<
  number,
  (value: {result: any, error: a

al script with id "${scriptId}" exists.`);
  }
  const code = evalScripts[scriptId].code.apply(null, args);
  const tabId = chrome.devtools.inspectedWindow.tabId;
  const requestId = evalRequestId++;
  chrome.runtime.sendMessage({
    source: 'devtools-pag

ny}) => void,
>();

function fallbackEvalInInspectedWindow(
  scriptId: EvalScriptIds,
  args: any[],
  callback: (value: any, exceptionInfo: ?ExceptionInfo) => void,
) {
  if (!evalScripts[scriptId]) {
    throw new Error(`No ev


BUG__} from 'react-devtools-shared/src/constants';

let debugIDCounter = 0;

const debugLog = (...args) => {
  if (__DEBUG__) {
    console.log(...args);
  }
};

const fetchFromNetworkCache = (url, resolve, reject) => {
  // Debug ID allows us to avoid re-logging (potentially long) URL strings below,
  // while also still associating (potentially) interleaved logs with the original request.
  let debugID = null;

  if (__DEBUG__) {
    debugID = debugIDCounter++;
    debugLog(`[main] fetchFromNetworkCache($

     debugLog(
        `[main] fetchFromNetworkCache(${debugID}) Found matching URL in HAR`,
        url,
      );

      if (entry.getContent != null) {
        entry.getContent(content => {
          if (content) {
            debugLog(
              `[m

{debugID})`, url);
  }

  chrome.devtools.network.getHAR(harLog => {
    for (let i = 0; i < harLog.entries.length; i++) {
      const entry = harLog.entries[i];
      if (url !== entry.request.url) {
        continue;
      }


-devtools-shared/src/storage';
import DevTools from 'react-devtools-shared/src/devtools/views/DevTools';
import {
  LOCAL_STORAGE_SUPPORTS_PROFILING_KEY,
  LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY,
} from 'react-devtools-shared/src/constants';
import {logEvent} from 'react-devtools-shared/src/Logger';
import {
  getAlwaysOpenInEditor,
  getOpenInEditorURL,
  normalizeUrlIfValid,
} from 'react-devtools-shared/src/utils';
import {checkConditions} from 'react-devtools-shared/src/devtools/views/Editor/utils';
im

ection';

import {evalInInspectedWindow} from './evalInInspectedWindow';
import {startReactPolling} from './reactPolling';
import {cloneStyleTags} from './cloneStyleTags';
import fetchFileWithCaching from './fetchFileWithCaching';
import injectBackendManag

port * as parseHookNames from 'react-devtools-shared/src/hooks/parseHookNames';

import {
  setBrowserSelectionFromReact,
  setReactSelectionFromBrowser,
} from './elementSelection';
import {viewAttributeSource} from './sourceSel


tedWindow';

class CouldNotFindReactOnThePageError extends Error {
  constructor() {
    super("Could not find React, or it hasn't been loaded yet");

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CouldNotFindReactOnThePageError);
    }

    this.name = 'CouldNotFindReactOnThePageError';
  }
}

export function startReactPolling(
  onReactFound,
  attemptsThreshold,
  onCouldNotFindReactAfterRea

er case
  function checkIfReactPresentInInspectedWindow(onSuccess, onError) {
    evalInInspectedWindow(
      'checkIfReactPresentInInspectedWindow',
      [],
      (pageHasReact, exceptionInfo) => {
        if (status === 'aborted') {
          onError(

chingAttemptsThreshold,
) {
  let status = 'idle';

  function abort() {
    status = 'aborted';
  }

  // This function will call onSuccess only if React was found and polling is not aborted, onError will be called for every oth


t contentScriptsToInject = [
  {
    id: '@react-devtools/proxy',
    js: ['build/proxy.js'],
    matches: ['<all_urls>'],
    persistAcrossSessions: true,
    runAt: 'document_start',
    world: chrome.scripting.ExecutionWorld.ISOLATED,
  },
  {
    id: '@react-devtools/file-fetcher',
    js: ['build/fileFetcher.js'],
    matches: ['<all_urls>'],
    persistAcrossSessions: true,
    runAt: 'document_end',
    world: chrome.scripting.ExecutionWorld.ISOLATED,
  },
  {
    id: '@react-devtools/fallback-eval-c

',
    js: ['build/installHook.js'],
    matches: ['<all_urls>'],
    persistAcrossSessions: true,
    runAt: 'document_start',
    world: chrome.scripting.ExecutionWorld.MAIN,
  },
  {
    id: '@react-devtools/hook-settings-injector',
    js: ['build/hook

ontext',
    js: ['build/fallbackEvalContext.js'],
    matches: ['<all_urls>'],
    persistAcrossSessions: true,
    runAt: 'document_start',
    world: chrome.scripting.ExecutionWorld.MAIN,
  },
  {
    id: '@react-devtools/hook


ta 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
 */
/* global chrome */

export function executeScriptInIsolatedWorld({
  target,
  files,
}: {
  files: any,
  target: any,
}): Promise<void> {
  return chrome.scripting.executeScript({
    target,
    files,
    world: chrome.scripting.ExecutionWorld.ISOLATED,
  });
}

export function executeScriptInMainWorld({
  target,
  files,

  // It's nice to have this required to make active choices.
  injectImmediately: boolean,
}): Promise<void> {
  return chrome.scripting.executeScript({
    target,
    files,
    injectImmediately,
    world: chrome.scripting.ExecutionWorld.MAIN,
  });
}

injectImmediately,
}: {
  files: any,
  target: any,


* global chrome, ExtensionRuntimePort */

'use strict';

import './dynamicallyInjectContentScripts';
import './tabsManager';

import {
  handleDevToolsPageMessage,
  handleBackendManagerMessage,
  handleReactDevToolsHookMessage,
  handleFetchResourceContentScriptMessage,
} from './messageHandlers';

const ports: {
  // TODO: Check why we convert tab IDs to strings, and if we can avoid it
  [tabId: string]: {
    extension: ExtensionRuntimePort | null,
    proxy: ExtensionRuntimePort | null,
    disconnectPi

,
      disconnectPipe: null,
    };
  }
}

function registerExtensionPort(port: ExtensionRuntimePort, tabId: number) {
  // $FlowFixMe[incompatible-type]
  ports[tabId].extension = port;

  port.onDisconnect.addListener(() => {
    // This should delete d

pe: Function | null,
  },
} = {};

function registerTab(tabId: number) {
  // $FlowFixMe[incompatible-type]
  if (!ports[tabId]) {
    // $FlowFixMe[incompatible-type]
    ports[tabId] = {
      extension: null,
      proxy: null


nIconAndPopup from './setExtensionIconAndPopup';
import {executeScriptInMainWorld} from './executeScript';

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

export function handleReactDevToolsHookMessage(message, sender) {
  const {payload} = message;

  switch (payload?.type) {
    case 'react-renderer-attached': {
      setExtensionIconAndPopup(payload.reactBuildType, sender.tab.id);

      break;
    }
  }
}

export function handleBackendManagerMessage(message, sender) {
  const {payload} = messag

ately: true,
            target: {tabId: sender.tab.id},
            files: [`/build/react_devtools_backend_${version}.js`],
          });
        }
      });

      break;
    }
  }
}

export function handleDevToolsPageMessage(message) {
  const {payload}

e;

  switch (payload?.type) {
    case 'require-backends': {
      payload.versions.forEach(version => {
        if (EXTENSION_CONTAINED_VERSIONS.includes(version)) {
          executeScriptInMainWorld({
            injectImmedi


 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
 */

declare const __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void;

export function injectInternals(internals: Object): boolean {
  if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
    // No DevTools
    return false;
  }
  const hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
  if (hook.isDisabled) {
    // This is

{
    // DevTools exists, even though it doesn't support Flight.
    return true;
  }
  try {
    hook.inject(internals);
  } catch (err) {
    // Catch all errors because it is unsafe to throw during initialization.
    if (__DEV__) {
      console.error(

n't a real property on the hook, but it can be set to opt out
    // of DevTools integration and associated warnings and logs.
    // https://github.com/facebook/react/issues/3877
    return true;
  }
  if (!hook.supportsFlight)


=
  new WeakMap();

// Serializable values
export type ReactServerValue =
  // References are passed by their value
  | ServerReference<any>
  // The rest are passed as is. Sub-types can be passed in but lose their
  // subtype, so the receiver can only accept once of these.
  | string
  | boolean
  | number
  | null
  | void
  | bigint
  | $AsyncIterable<ReactServerValue, ReactServerValue, void>
  | $AsyncIterator<ReactServerValue, ReactServerValue, void>
  | Iterable<ReactServerValue>
  | Iterator<ReactSe

erObject = {+[key: string]: ReactServerValue};

const __PROTO__ = '__proto__';

function serializeByValueID(id: number): string {
  return '$' + id.toString(16);
}

function serializePromiseID(id: number): string {
  return '$@' + id.toString(16);
}

funct

rverValue>
  | Array<ReactServerValue>
  | Map<ReactServerValue, ReactServerValue>
  | Set<ReactServerValue>
  | FormData
  | Date
  | ReactServerObject
  | Promise<ReactServerValue>; // Thenable<ReactServerValue>

type ReactServ


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails react-core
 * @jest-environment node
 */

'use strict';

if (typeof Blob === 'undefined') {
  global.Blob = require('buffer').Blob;
}
if (typeof File === 'undefined' || typeof FormData === 'undefined') {
  global.File = require('undici').File;
  global.FormData = require('undici').FormData;
}

let act;
let React;
let ReactNoop;
let ReactNoopFlightServer;
let R

+;
    });
    Object.defineProperty(performance, 'timeOrigin', {
      value: time,
      configurable: true,
    });
    Object.defineProperty(performance, 'now', {
      value: now,
      configurable: true,
    });

    jest.resetModules();
    jest.mo

eactNoopFlightClient;
let getDebugInfo;

describe('ReactFlight', () => {
  beforeEach(() => {
    // Mock performance.now for timing tests
    let time = 10;
    const now = jest.fn().mockImplementation(() => {
      return time+


* 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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-esm';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigBrowser';
export * from 'react-client/src/ReactClientDebugConfigBr

 * from 'react-server-dom-esm/src/client/ReactFlightClientConfigBundlerESM';
export * from 'react-server-dom-esm/src/client/ReactFlightClientConfigTargetESMBrowser';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const use


yright (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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-flight-server-fb';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigBrowser';
export * from 'react-client/src/ReactClientDebugConfigBrows

from 'react-flight-server-fb/src/client/ReactFlightClientConfigBundlerFB';
export * from 'react-flight-server-fb/src/client/ReactFlightClientConfigTargetFBBrowser';
export * from 'react-flight-server-fb/src/client/ReactFlightClientConfigDOMFB';
export cons


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-webpack';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigBrowser';
export * from 'react-client/src/ReactClientDebugConfigBrowser';
export * from 'react-server-dom-webpack/src/client/ReactFlightClientConfigBun

k/src/client/ReactFlightClientConfigBundlerWebpackBrowser';
export * from 'react-server-dom-webpack/src/client/ReactFlightClientConfigTargetWebpackBrowser';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWithSSR

dlerWebpack';
export * from 'react-server-dom-webpac


 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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-bun';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigPlain';
export * from 'react-client/src/ReactClientDebugConfigPlain

type ServerReferenceId = string;
export opaque type ClientReferenceMetadata = mixed;
export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars
export const resolveClientReference: any = null;
export const resolveServerReference:

';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';

export opaque type ModuleLoading = mixed;
export opaque type ServerConsumerModuleMap = mixed;
export opaque type ServerManifest = mixed;
export opaque


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-webpack';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigPlain';
export * from 'react-server-dom-webpack/src/client/ReactFlightClientConfigBundle

rc/client/ReactFlightClientConfigBundlerWebpackServer';
export * from 'react-server-dom-webpack/src/client/ReactFlightClientConfigTargetWebpackServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWithSSR = tru

rWebpack';
export * from 'react-server-dom-webpack/s


 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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'not-used';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigBrowser';
export * from 'react-client/src/ReactClientDebugConfigBrowser';

expo

ientReferenceMetadata = mixed;
export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars
export const resolveClientReference: any = null;
export const resolveServerReference: any = null;
export const preloadModule: any = null;
ex

rt type Response = any;
export opaque type ModuleLoading = mixed;
export opaque type ServerConsumerModuleMap = mixed;
export opaque type ServerManifest = mixed;
export opaque type ServerReferenceId = string;
export opaque type Cl


yright (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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-parcel';

export * from 'react-client/src/ReactFlightClientStreamConfigNode';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigNode

om 'react-server-dom-parcel/src/client/ReactFlightClientConfigBundlerParcel';
export * from 'react-server-dom-parcel/src/client/ReactFlightClientConfigTargetParcelServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export con


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-turbopack';

export * from 'react-client/src/ReactFlightClientStreamConfigNode';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigNode';
export * from 'react-server-dom-turbopack/src/client/ReactFlightClientConfigBu

bopack/src/client/ReactFlightClientConfigBundlerTurbopackServer';
export * from 'react-server-dom-turbopack/src/client/ReactFlightClientConfigTargetTurbopackServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const use

ndlerTurbopack';
export * from 'react-server-dom-tur


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-markup';

import type {Thenable} from 'shared/ReactTypes';

export * from 'react-markup/src/ReactMarkupLegacyClientStreamConfig.js';
export * from 'react-client/src/ReactClientConsoleConfigPlain';
export * from 'react-client/src/ReactClientDebugConfigPl

ue type ClientReference<T> = null; // eslint-disable-line no-unused-vars

export function prepareDestinationForModule(
  moduleLoading: ModuleLoading,
  nonce: ?string,
  metadata: ClientReferenceMetadata,
) {
  throw new Error(
    'renderToHTML should no

ain';

export type ModuleLoading = null;
export type ServerConsumerModuleMap = null;
export opaque type ServerManifest = null;
export type ServerReferenceId = string;
export opaque type ClientReferenceMetadata = null;
export opaq


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

// This is a host config that's used for the internal `react-noop-renderer` package.
//
// Its API lets you pass the host config as an argument.
// However, inside the `react-server` we treat host config as a module.
// This file is a shim between two worlds.
//
// It works because the `react-server` bundle is wrapped in something like:
//
// module.exports

 ModuleLoading = mixed;
export opaque type ServerConsumerModuleMap = mixed;
export opaque type ServerManifest = mixed;
export opaque type ServerReferenceId = string;
export opaque type ClientReferenceMetadata = mixed;
export opaque type ClientReference<T>

 = function ($$$config) {
//   /* renderer code */
// }
//
// So `$$$config` looks like a global variable, but it's
// really an argument to a top-level wrapping function.

declare const $$$config: $FlowFixMe;

export opaque type


 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
 */

// Keep in sync with ReactServerConsoleConfig
// This flips color using ANSI, then sets a color styling, then resets.
const badgeFormat = '\x1b[0m\x1b[7m%c%s\x1b[0m%c';
// Same badge styling as DevTools.
const badgeStyle =
  // We use a fixed background if light-dark is not supported, otherwise
  // we use a transparent background.

const bind = Function.prototype.bind;

export function bindToConsole(
  methodName: string,
  args: Array<any>,
  badgeName: string,
): () => any {
  let offset = 0;
  switch (methodName) {
    case 'dir':
    case 'dirxml':
    case 'groupEnd':
    case '

  'background: #e6e6e6;' +
  'background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));' +
  'color: #000000;' +
  'color: light-dark(#000000, #ffffff);' +
  'border-radius: 2px';
const resetStyle = '';
const pad = ' ';


ight (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
 */

let hasConfirmedEval = false;
export function checkEvalAvailabilityOnceDev(): void {
  if (__DEV__) {
    if (!hasConfirmedEval) {
      hasConfirmedEval = true;
      try {
        // eslint-disable-next-line no-eval
        (0, eval)('null');
      } catch {
        console.error(
          'eval() is not supported i

us debugging features ' +
            'like reconstructing callstacks from a different environment.\n' +
            'React will never use eval() in production mode',
        );
      }
    }
  } else {
    // These errors should never make it into a build

n this environment. ' +
            'If this page was served with a `Content-Security-Policy` header, ' +
            'make sure that `unsafe-eval` is included. ' +
            'React requires eval() in development mode for vario


, // DEV-only
  then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type HaltedChunk<T> = {
  status: 'halted',
  value: null,
  reason: null,
  _children: Array<SomeChunk<any>> | ProfilingResult, // Profiling-only
  _debugChunk: null, // DEV-only
  _debugInfo: ReactDebugInfo, // DEV-only
  then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type SomeChunk<T> =
  | PendingChunk<T>
  | BlockedChunk<T>
  | ResolvedModelChunk<T>
  | ResolvedModuleChunk<T>
  | InitializedChunk<T>
  | E

& enableComponentPerformanceTrack) {
    this._children = [];
  }
  if (__DEV__) {
    this._debugChunk = null;
    this._debugInfo = [];
  }
}
// We subclass Promise.prototype so that we get other methods like .catch
ReactPromise.prototype = (Object.creat

rroredChunk<T>
  | HaltedChunk<T>;

// $FlowFixMe[missing-this-annot]
function ReactPromise(status: any, value: any, reason: any) {
  this.status = status;
  this.value = value;
  this.reason = reason;
  if (enableProfilerTimer &


e.measure === 'function';

const IO_TRACK = 'Server Requests ⚛';
const COMPONENTS_TRACK = 'Server Components ⚛';

export function markAllTracksInOrder() {
  if (supportsUserTiming) {
    // Ensure we create the Server Component track groups earlier than the Client Scheduler
    // and Client Components. We can always add the 0 time slot even if it's in the past.
    // That's still considered for ordering.
    console.timeStamp(
      'Server Requests Track',
      0.001,
      0.001,
      IO_TRACK,

ary',
  'Parallel',
  'Parallel\u200b', // Padded with zero-width space to give each track a unique name.
  'Parallel\u200b\u200b',
  'Parallel\u200b\u200b\u200b',
  'Parallel\u200b\u200b\u200b\u200b',
  'Parallel\u200b\u200b\u200b\u200b\u200b',
  'Paralle

undefined,
      'primary-light',
    );
    console.timeStamp(
      'Server Components Track',
      0.001,
      0.001,
      'Primary',
      COMPONENTS_TRACK,
      'primary-light',
    );
  }
}

const trackNames = [
  'Prim


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-turbopack';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigBrowser';
export * from 'react-client/src/ReactClientDebugConfigBrowser';
export * from 'react-server-dom-turbopack/src/client/ReactFlightClientConfi

turbopack/src/client/ReactFlightClientConfigBundlerTurbopackBrowser';
export * from 'react-server-dom-turbopack/src/client/ReactFlightClientConfigTargetTurbopackBrowser';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export cons

gBundlerTurbopack';
export * from 'react-server-dom-


a 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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-flight-server-fb';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigNode';
export * from

-server-fb/src/client/ReactFlightClientConfigBundlerFB';
export * from 'react-flight-server-fb/src/client/ReactFlightClientConfigTargetFBBrowser';
export * from 'react-flight-server-fb/src/client/ReactFlightClientConfigDOMFB';
export const usedWithSSR = fa


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */
export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-webpack';

export * from 'react-client/src/ReactFlightClientStreamConfigNode';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigNode';
export * from 'react-server-dom-webpack/src/client/ReactFlightClientConfigBundler

c/client/ReactFlightClientConfigBundlerWebpackServer';
export * from 'react-server-dom-webpack/src/client/ReactFlightClientConfigTargetWebpackServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWithSSR = true

Webpack';
export * from 'react-server-dom-webpack/sr


import type {ReactNodeList} from 'shared/ReactTypes';

import type {
  RenderState,
  ResumableState,
  PreambleState,
  HoistableState,
  FormatContext,
} from 'react-dom-bindings/src/server/ReactFizzConfigDOM';

import {
  pushStartInstance as pushStartInstanceImpl,
  writePreambleStart as writePreambleStartImpl,
} from 'react-dom-bindings/src/server/ReactFizzConfigDOM';

import type {
  Destination,
  Chunk,
  PrecomputedChunk,
} from 'react-server/src/ReactServerStreamConfig';

import type {FormStatus}

 render.
export const isPrimaryRenderer = false;

// Disable Client Hooks
export const supportsClientAPIs = false;

import {stringToChunk} from 'react-server/src/ReactServerStreamConfig';

export type {
  RenderState,
  ResumableState,
  HoistableState,

from 'react-dom-bindings/src/shared/ReactDOMFormActions';

import {NotPending} from 'react-dom-bindings/src/shared/ReactDOMFormActions';

import hasOwnProperty from 'shared/hasOwnProperty';

// Allow embedding inside another Fizz


 * 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
 */

let hasConfirmedEval = false;
export function checkEvalAvailabilityOnceDev(): void {
  if (__DEV__) {
    if (!hasConfirmedEval) {
      hasConfirmedEval = true;
      try {
        // eslint-disable-next-line no-eval
        (0, eval)('null');
      } catch {
        console.error(
          'eval() is not su

er use eval() in production mode',
        );
      }
    }
  } else {
    // These errors should never make it into a build so we don't need to encode them in codes.json
    // eslint-disable-next-line react-internal/prod-error-codes
    throw new Error(

pported in this environment. ' +
            'React requires eval() in development mode for various debugging features ' +
            'like reconstructing callstacks from a different environment.\n' +
            'React will nev


        expect(this.state.hasError).toBe(false);
      }
      render() {
        if (this.state.hasError) {
          return this.state.error.message;
        }
        return this.props.children;
      }
    };
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  function clientReference(value) {
    return Object.defineProperties(
      function () {
        throw new Error('Cannot call a client function from the server.');
      },
      {
        $$typeof: {value: Symbol.for('react.client.re

: (
          <div>
            <Bar text="a" />, <Bar text="b" />
          </div>
        ),
      };
    }
    const transport = ReactNoopFlightServer.render({
      foo: <Foo />,
    });
    const model = await ReactNoopFlightClient.read(transport);

ference')},
        value: {value: value},
      },
    );
  }

  it('can render a Server Component', async () => {
    function Bar({text}) {
      return text.toUpperCase();
    }
    function Foo() {
      return {
        bar


iates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

// This is a host config that's used for the `react-server` package on npm.
// It is only used by third-party renderers.
//
// Its API lets you pass the host config as an argument.
// However, inside the `react-server` we treat host config as a module.
// This file is a shim between two worlds.
//
// It works because the `react-server` bundle is wrapped in

fig: any;

export opaque type ModuleLoading = mixed;
export opaque type ServerConsumerModuleMap = mixed;
export opaque type ServerManifest = mixed;
export opaque type ServerReferenceId = string;
export opaque type ClientReferenceMetadata = mixed;
export op

something like:
//
// module.exports = function ($$$config) {
//   /* renderer code */
// }
//
// So `$$$config` looks like a global variable, but it's
// really an argument to a top-level wrapping function.

declare const $$$con


/**
 * 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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-parcel';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigBrowser';
export * from 'react-client/src/ReactClientDebug

el/src/client/ReactFlightClientConfigBundlerParcel';
export * from 'react-server-dom-parcel/src/client/ReactFlightClientConfigTargetParcelBrowser';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWithSSR = false;

ConfigBrowser';
export * from 'react-server-dom-parc


/**
 * 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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-unbundled';

export * from 'react-client/src/ReactFlightClientStreamConfigNode';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDe

ndled/src/client/ReactFlightClientConfigBundlerNode';
export * from 'react-server-dom-unbundled/src/client/ReactFlightClientConfigTargetNodeServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWithSSR = true;

bugConfigNode';
export * from 'react-server-dom-unbu


ight (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
 */

// Keep in sync with ReactServerConsoleConfig
const badgeFormat = '[%s]';
const pad = ' ';

const bind = Function.prototype.bind;

export function bindToConsole(
  methodName: string,
  args: Array<any>,
  badgeName: string,
): () => any {
  let offset = 0;
  switch (methodName) {
    case 'dir':
    case 'dirxml':

able-line react-internal/no-production-logging
    }
    case 'assert': {
      // assert takes formatting options as the second argument.
      offset = 1;
    }
  }

  const newArgs = args.slice(0);
  if (typeof newArgs[offset] === 'string') {
    newArg

 case 'groupEnd':
    case 'table': {
      // These methods cannot be colorized because they don't take a formatting string.
      // $FlowFixMe
      return bind.apply(console[methodName], [console].concat(args)); // eslint-dis


yright (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
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-parcel';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigPlain

om 'react-server-dom-parcel/src/client/ReactFlightClientConfigBundlerParcel';
export * from 'react-server-dom-parcel/src/client/ReactFlightClientConfigTargetParcelServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export con


iates.
 *
 * 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 {ReactNodeList} from 'shared/ReactTypes';
import type {ErrorInfo} from 'react-server/src/ReactFizzServer';

import ReactVersion from 'shared/ReactVersion';

import {
  createRequest as createFizzRequest,
  startWork as startFizzWork,
  startFlowing as startFizzFlowing,
  abort as abortFizz,
} from 'react-server/src/ReactFizzServer';

import {

 => ?string,
};

export function experimental_renderToHTML(
  children: ReactNodeList,
  options?: MarkupOptions,
): Promise<string> {
  return new Promise((resolve, reject) => {
    let buffer = '';
    const fizzDestination = {
      push(chunk: string |

createResumableState,
  createRenderState,
  createRootFormatContext,
} from './ReactFizzConfigMarkup';

type MarkupOptions = {
  identifierPrefix?: string,
  signal?: AbortSignal,
  onError?: (error: mixed, errorInfo: ErrorInfo)


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {default as rendererVersion} from 'shared/ReactVersion';
export const rendererPackageName = 'react-server-dom-turbopack';

export * from 'react-client/src/ReactFlightClientStreamConfigWeb';
export * from 'react-client/src/ReactClientConsoleConfigServer';
export * from 'react-client/src/ReactClientDebugConfigPlain';
export * from 'react-server-dom-turbopack/src/client/ReactFlightClientConfigBu

bopack/src/client/ReactFlightClientConfigBundlerTurbopackServer';
export * from 'react-server-dom-turbopack/src/client/ReactFlightClientConfigTargetTurbopackServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const use

ndlerTurbopack';
export * from 'react-server-dom-tur


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {ReactNodeList} from 'shared/ReactTypes';

import type {Request} from 'react-server/src/ReactFizzServer';

import type {Destination} from 'react-server/src/ReactServerStreamConfig';
import type {BootstrapScriptDescriptor} from 'react-dom-bindings/src/server/ReactFizzConfigDOM';

import {
  createRequest,
  startWork,
  performWork,
  startFlowing,
  abort,
} from 'react-server/src/ReactFizzServe

: Array<string>,
  bootstrapModules: Array<string>,
  progressiveChunkSize?: number,
  onError: (error: mixed) => void,
  unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor,
};

opaque type Stream = {
  destination: Destination,
  request: Re

r';

import {
  createResumableState,
  createRenderState,
  createRootFormatContext,
} from 'react-server/src/ReactFizzConfig';

type Options = {
  identifierPrefix?: string,
  bootstrapScriptContent?: string,
  bootstrapScripts


ight (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 * as React from 'react';
import {useContext} from 'react';
import {createPortal} from 'react-dom';
import SearchInput from 'react-devtools-shared/src/devtools/views/SearchInput';
import {TimelineContext} from './TimelineContext';
import {TimelineSearchContext} from './TimelineSearchContext';

type Props = {};

e

ntext,
  );

  if (searchInputContainerRef.current === null) {
    return null;
  }

  const search = (text: string) =>
    dispatch({type: 'SET_SEARCH_TEXT', payload: text});
  const goToNextResult = () => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'});
  c

xport default function TimelineSearchInput(props: Props): React.Node {
  const {searchInputContainerRef} = useContext(TimelineContext);
  const {dispatch, searchIndex, searchResults, searchText} = useContext(
    TimelineSearchCo


ight (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 {createResource} from 'react-devtools-shared/src/devtools/cache';
import {importFile} from './import-worker';

import type {Resource} from 'react-devtools-shared/src/devtools/cache';
import type {TimelineData} from './types';
import type {ImportWorkerOutputData} from './import-worker/index';

export type DataRes

(resolve, reject) => {
        const promise = ((importFile(
          file,
        ): any): Promise<ImportWorkerOutputData>);
        promise.then(data => {
          switch (data.status) {
            case 'SUCCESS':
              resolve(data.processed

ource = Resource<void, File, TimelineData | Error>;

export default function createDataResourceFromImportedFile(
  file: File,
): DataResource {
  return createResource(
    () => {
      return new Promise<TimelineData | Error>(


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {
  Thenable,
  FulfilledThenable,
  RejectedThenable,
} from 'shared/ReactTypes';
import type {TimelineData} from './types';

import * as React from 'react';

import {importFile as importFileWorker} from './import-worker';

// This is intentionally a module-level Map, rather than a React-managed one.
// Otherwise, refreshing the inspected element cache would also clear this cache.
// Profiler f

      // eslint-disable-next-line react-hooks-published/rules-of-hooks
      return React.use(record);
    } catch (x) {
      if (record.status === 'rejected') {
        return (record.reason: any);
      }
      throw x;
    }
  }
  if (record.status ==

ile contents are static anyway.
const fileNameToProfilerDataMap: Map<
  string,
  Thenable<TimelineData>,
> = new Map();

function readRecord<T>(record: Thenable<T>): T | Error {
  if (typeof React.use === 'function') {
    try {


mport type {StackFrame as ErrorStackFrame} from 'error-stack-parser';
import type {ScrollState} from './view-base/utils/scrollState';

// Source: https://github.com/facebook/flow/issues/4002#issuecomment-323612798
// eslint-disable-next-line no-unused-vars
type Return_<R, F: (...args: Array<any>) => R> = R;
/** Get return type of a function. */
export type Return<T> = Return_<mixed, T>;

// Project types
export type {ErrorStackFrame};

export type Milliseconds = number;

export type ReactLane = number;

exp

ning: string | null,
};

type BaseReactScheduleEvent = {
  ...BaseReactEvent,
  +lanes: ReactLane[],
};
export type ReactScheduleRenderEvent = {
  ...BaseReactScheduleEvent,
  +type: 'schedule-render',
};
export type ReactScheduleStateUpdateEvent = {
  ...

ort type NativeEvent = {
  +depth: number,
  +duration: Milliseconds,
  +timestamp: Milliseconds,
  +type: string,
  warning: string | null,
};

type BaseReactEvent = {
  +componentName?: string,
  +timestamp: Milliseconds,
  war


import type {ReactComponentMeasure, TimelineData, ViewState} from '../types';
import type {
  Interaction,
  IntrinsicSize,
  MouseMoveInteraction,
  Rect,
  ViewRefs,
} from '../view-base';

import {
  durationToWidth,
  positioningScaleFactor,
  positionToTimestamp,
  timestampToPosition,
} from './utils/positioning';
import {drawText} from './utils/text';
import {formatDuration} from '../utils/formatting';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} fro

 Map<string, boolean>;
  _cachedSearchRegExp: RegExp | null = null;
  _hoveredComponentMeasure: ReactComponentMeasure | null = null;
  _intrinsicSize: IntrinsicSize;
  _profilerData: TimelineData;
  _viewState: ViewState;

  onHover: ((event: ReactComponen

m '../view-base';
import {BORDER_SIZE, COLORS, NATIVE_EVENT_HEIGHT} from './constants';

const ROW_WITH_BORDER_HEIGHT = NATIVE_EVENT_HEIGHT + BORDER_SIZE;

export class ComponentMeasuresView extends View {
  _cachedSearchMatches:


s,
} from '../view-base';

import {
  BackgroundColorView,
  Surface,
  View,
  layeredLayout,
  rectContainsPoint,
  intersectionOfRects,
  rectIntersectsRect,
  verticallyStackedLayout,
} from '../view-base';
import {isInternalModule} from './utils/moduleFilters';
import {
  durationToWidth,
  positioningScaleFactor,
  timestampToPosition,
} from './utils/positioning';
import {drawText} from './utils/text';
import {
  COLORS,
  FLAMECHART_FRAME_HEIGHT,
  COLOR_HOVER_DIM_DELTA,
  BORDER_SIZE,
} from './con

d79707a693351b806b8710b2f6b7d399
const colorGenerator = new ColorGenerator(
  {min: 30, max: 330},
  {min: 50, max: 80, count: 3},
  85,
);
colorGenerator.setColorForID('', {h: 43.6, s: 45.8, l: 90.6, a: 100});

function defaultHslaColorForStackFrame({scri

stants';
import {ColorGenerator, dimmedColor, hslaColorToString} from './utils/colors';

// Source: https://source.chromium.org/chromium/chromium/src/+/master:out/Debug/gen/devtools/timeline/TimelineUIUtils.js;l=2109;drc=fb32e928


import type {NativeEvent, TimelineData} from '../types';
import type {
  Interaction,
  IntrinsicSize,
  MouseMoveInteraction,
  Rect,
  ViewRefs,
} from '../view-base';

import {
  durationToWidth,
  positioningScaleFactor,
  positionToTimestamp,
  timestampToPosition,
} from './utils/positioning';
import {drawText} from './utils/text';
import {formatDuration} from '../utils/formatting';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';
imp

;
  _hoveredEvent: NativeEvent | null = null;
  _intrinsicSize: IntrinsicSize;
  _maxDepth: number = 0;
  _profilerData: TimelineData;

  onHover: ((event: NativeEvent | null) => void) | null = null;

  constructor(surface: Surface, frame: Rect, profilerDa

ort {COLORS, NATIVE_EVENT_HEIGHT, BORDER_SIZE} from './constants';

const ROW_WITH_BORDER_HEIGHT = NATIVE_EVENT_HEIGHT + BORDER_SIZE;

export class NativeEventsView extends View {
  _depthToNativeEvent: Map<number, NativeEvent[]>


import type {NetworkMeasure, TimelineData} from '../types';
import type {
  Interaction,
  IntrinsicSize,
  MouseMoveInteraction,
  Rect,
  ViewRefs,
} from '../view-base';

import {
  durationToWidth,
  positioningScaleFactor,
  positionToTimestamp,
  timestampToPosition,
} from './utils/positioning';
import {drawText} from './utils/text';
import {formatDuration} from '../utils/formatting';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';

/;

export class NetworkMeasuresView extends View {
  _depthToNetworkMeasure: Map<number, NetworkMeasure[]>;
  _hoveredNetworkMeasure: NetworkMeasure | null = null;
  _intrinsicSize: IntrinsicSize;
  _maxDepth: number = 0;
  _profilerData: TimelineData;

import {BORDER_SIZE, COLORS, SUSPENSE_EVENT_HEIGHT} from './constants';

const HEIGHT = SUSPENSE_EVENT_HEIGHT; // TODO Constant name
const ROW_WITH_BORDER_HEIGHT = HEIGHT + BORDER_SIZE;

const BASE_URL_REGEX = /([^:]+:\/\/[^\/]+)


} from '../utils/formatting';
import {drawText} from './utils/text';
import {
  durationToWidth,
  positioningScaleFactor,
  positionToTimestamp,
  timestampToPosition,
} from './utils/positioning';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';

import {COLORS, BORDER_SIZE, REACT_MEASURE_HEIGHT} from './constants';

const REACT_LANE_HEIGHT = REACT_MEASURE_HEIGHT + BORDER_SIZE;
const MAX_ROWS_TO_SHOW_INITIALLY = 5;

export class ReactMeas

ull;

  constructor(surface: Surface, frame: Rect, profilerData: TimelineData) {
    super(surface, frame);
    this._profilerData = profilerData;
    this._performPreflightComputations();
  }

  _performPreflightComputations() {
    this._lanesToRender =

uresView extends View {
  _intrinsicSize: IntrinsicSize;
  _lanesToRender: ReactLane[];
  _profilerData: TimelineData;
  _hoveredMeasure: ReactMeasure | null = null;

  onHover: ((measure: ReactMeasure | null) => void) | null = n


import type {SchedulingEvent, TimelineData} from '../types';
import type {
  ClickInteraction,
  Interaction,
  MouseMoveInteraction,
  Rect,
  Size,
  ViewRefs,
} from '../view-base';

import {
  positioningScaleFactor,
  timestampToPosition,
  positionToTimestamp,
  widthToDuration,
} from './utils/positioning';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';
import {
  COLORS,
  TOP_ROW_PADDING,
  REACT_EVENT_DIAMETER,
  BORDER_SIZE,
}

vent: SchedulingEvent | null = null;
  onHover: ((event: SchedulingEvent | null) => void) | null = null;
  onClick:
    | ((event: SchedulingEvent | null, eventIndex: number | null) => void)
    | null = null;

  constructor(surface: Surface, frame: Rect,

from './constants';

const EVENT_ROW_HEIGHT_FIXED =
  TOP_ROW_PADDING + REACT_EVENT_DIAMETER + TOP_ROW_PADDING;

export class SchedulingEventsView extends View {
  _profilerData: TimelineData;
  _intrinsicSize: Size;

  _hoveredE


import type {Snapshot, TimelineData} from '../types';
import type {
  Interaction,
  Point,
  Rect,
  Size,
  Surface,
  ViewRefs,
} from '../view-base';

import {positioningScaleFactor, timestampToPosition} from './utils/positioning';
import {
  intersectionOfRects,
  rectContainsPoint,
  rectEqualToRect,
  View,
} from '../view-base';
import {BORDER_SIZE, COLORS, SNAPSHOT_SCRUBBER_SIZE} from './constants';

type OnHover = (node: Snapshot | null) => void;

export class SnapshotsView extends View {
  _hover

this._intrinsicSize = {
      width: profilerData.duration,
      height: profilerData.snapshotHeight,
    };
    this._profilerData = profilerData;
  }

  desiredSize(): Size {
    return this._intrinsicSize;
  }

  draw(context: CanvasRenderingContext2D)

Location: Point | null = null;
  _intrinsicSize: Size;
  _profilerData: TimelineData;

  onHover: OnHover | null = null;

  constructor(surface: Surface, frame: Rect, profilerData: TimelineData) {
    super(surface, frame);


sitioningScaleFactor,
  positionToTimestamp,
  timestampToPosition,
  widthToDuration,
} from './utils/positioning';
import {drawText} from './utils/text';
import {formatDuration} from '../utils/formatting';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';
import {
  BORDER_SIZE,
  COLORS,
  PENDING_SUSPENSE_EVENT_SIZE,
  SUSPENSE_EVENT_HEIGHT,
} from './constants';

const ROW_WITH_BORDER_HEIGHT = SUSPENSE_EVENT_HEIGHT + BORDER_SIZE;
const

mber = 0;
  _profilerData: TimelineData;

  onHover: ((event: SuspenseEvent | null) => void) | null = null;

  constructor(surface: Surface, frame: Rect, profilerData: TimelineData) {
    super(surface, frame);

    this._profilerData = profilerData;

MAX_ROWS_TO_SHOW_INITIALLY = 3;

export class SuspenseEventsView extends View {
  _depthToSuspenseEvent: Map<number, SuspenseEvent[]>;
  _hoveredEvent: SuspenseEvent | null = null;
  _intrinsicSize: IntrinsicSize;
  _maxDepth: nu


import type {ThrownError, TimelineData} from '../types';
import type {
  Interaction,
  MouseMoveInteraction,
  Rect,
  Size,
  ViewRefs,
} from '../view-base';

import {
  positioningScaleFactor,
  timestampToPosition,
  positionToTimestamp,
  widthToDuration,
} from './utils/positioning';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';
import {
  COLORS,
  TOP_ROW_PADDING,
  REACT_EVENT_DIAMETER,
  BORDER_SIZE,
} from './constants';

con

ll;
  onHover: ((event: ThrownError | null) => void) | null = null;

  constructor(surface: Surface, frame: Rect, profilerData: TimelineData) {
    super(surface, frame);
    this._profilerData = profilerData;

    this._intrinsicSize = {
      width: this

st EVENT_ROW_HEIGHT_FIXED =
  TOP_ROW_PADDING + REACT_EVENT_DIAMETER + TOP_ROW_PADDING;

export class ThrownErrorsView extends View {
  _profilerData: TimelineData;
  _intrinsicSize: Size;
  _hoveredEvent: ThrownError | null = nu


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Rect, Size} from '../view-base';

import {
  durationToWidth,
  positioningScaleFactor,
  positionToTimestamp,
  timestampToPosition,
} from './utils/positioning';
import {
  View,
  Surface,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';
import {
  COLORS,
  INTERVAL_TIMES,
  LABEL_SIZE,
  FONT_SIZE,
  MARKER_HEIGHT,
  MARKER_TEXT_PADDING,
  MARKER_TICK_HEIGHT,
  MIN_INTER

mber;
  _intrinsicSize: Size;

  constructor(surface: Surface, frame: Rect, totalDuration: number) {
    super(surface, frame);
    this._totalDuration = totalDuration;
    this._intrinsicSize = {
      width: this._totalDuration,
      height: HEADER_HEIG

VAL_SIZE_PX,
  BORDER_SIZE,
} from './constants';

const HEADER_HEIGHT_FIXED = MARKER_HEIGHT + BORDER_SIZE;
const LABEL_FIXED_WIDTH = LABEL_SIZE + BORDER_SIZE;

export class TimeAxisMarkersView extends View {
  _totalDuration: nu


import type {UserTimingMark} from '../types';
import type {
  Interaction,
  MouseMoveInteraction,
  Rect,
  Size,
  ViewRefs,
} from '../view-base';

import {
  positioningScaleFactor,
  timestampToPosition,
  positionToTimestamp,
  widthToDuration,
} from './utils/positioning';
import {
  View,
  Surface,
  rectContainsPoint,
  rectIntersectsRect,
  intersectionOfRects,
} from '../view-base';
import {
  COLORS,
  TOP_ROW_PADDING,
  USER_TIMING_MARK_SIZE,
  BORDER_SIZE,
} from './constants';

const ROW_HEI

r: ((mark: UserTimingMark | null) => void) | null = null;

  constructor(
    surface: Surface,
    frame: Rect,
    marks: UserTimingMark[],
    duration: number,
  ) {
    super(surface, frame);
    this._marks = marks;

    this._intrinsicSize = {

GHT_FIXED =
  TOP_ROW_PADDING + USER_TIMING_MARK_SIZE + TOP_ROW_PADDING;

export class UserTimingMarksView extends View {
  _marks: UserTimingMark[];
  _intrinsicSize: Size;

  _hoveredMark: UserTimingMark | null = null;
  onHove


_TEXT_PADDING = 8;
export const COLOR_HOVER_DIM_DELTA = 5;
export const TOP_ROW_PADDING = 4;
export const NATIVE_EVENT_HEIGHT = 14;
export const SUSPENSE_EVENT_HEIGHT: number = 14;
export const PENDING_SUSPENSE_EVENT_SIZE = 8;
export const REACT_EVENT_DIAMETER = 6;
export const USER_TIMING_MARK_SIZE = 8;
export const REACT_MEASURE_HEIGHT = 14;
export const BORDER_SIZE = 1 / DPR;
export const FLAMECHART_FRAME_HEIGHT = 14;
export const TEXT_PADDING = 3;
export const SNAPSHOT_SCRUBBER_SIZE = 3;

export const I

 string,
  INTERNAL_MODULE_FRAME_HOVER: string,
  INTERNAL_MODULE_FRAME_TEXT: string,
  NATIVE_EVENT: string,
  NATIVE_EVENT_HOVER: string,
  NETWORK_PRIMARY: string,
  NETWORK_PRIMARY_HOVER: string,
  NETWORK_SECONDARY: string,
  NETWORK_SECONDARY_HOVER:

NTERVAL_TIMES = [
  1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000,
];
export const MIN_INTERVAL_SIZE_PX = 70;

// TODO Replace this with "export let" vars
export let COLORS: {
  BACKGROUND: string,
  INTERNAL_MODULE_FRAME:


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

type ColorSpace = number | {min: number, max: number, count?: number};

// Docstrings from https://www.w3schools.com/css/css_colors_hsl.asp
type HslaColor = $ReadOnly<{
  /** Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue. */
  h: number,
  /** Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color. */
  s: number,
  /** Lightness is

ing({h, s, l, a}: HslaColor): string {
  return `hsl(${h}deg ${s}% ${l}% / ${a})`;
}

export function dimmedColor(color: HslaColor, dimDelta: number): HslaColor {
  return {
    ...color,
    l: color.l - dimDelta,
  };
}

// Source: https://source.chromiu

 a percentage, 0% is black, 50% is neither light or dark, 100% is white. */
  l: number,
  /** Alpha is a percentage, 0% is fully transparent, and 100 is not transparent at all. */
  a: number,
}>;

export function hslaColorToStr


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 'react-devtools-extensions/src/utils';
import {getIsReloadAndProfileSupported} from 'react-devtools-shared/src/utils';
import {
  getIfReloadedAndProfiling,
  onReloadAndProfile,
  onReloadAndProfileFlagsReset,
} from 'react-devtools-shared/src/utils';

let welcomeHasInitialized = false;
const requiredB

 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 eleme

ackends = new Set<string>();

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

  // In some circumstances, this method is


global chrome */

function fetchResource(url) {
  const reject = value => {
    chrome.runtime.sendMessage({
      source: 'react-devtools-fetch-resource-content-script',
      payload: {
        type: 'fetch-file-with-cache-error',
        url,
        value,
      },
    });
  };

  const resolve = value => {
    chrome.runtime.sendMessage({
      source: 'react-devtools-fetch-resource-content-script',
      payload: {
        type: 'fetch-file-with-cache-complete',
        url,
        value,
      },

r => reject(null));
      } else {
        reject(null);
      }
    },
    error => reject(null),
  );
}

chrome.runtime.onMessage.addListener(message => {
  if (
    message?.source === 'devtools-page' &&
    message?.payload?.type === 'fetch-file-with-c

  });
  };

  fetch(url, {cache: 'force-cache', signal: AbortSignal.timeout(60000)}).then(
    response => {
      if (response.ok) {
        response
          .text()
          .then(text => resolve(text))
          .catch(erro


m './messages';
import type {DevToolsHookSettings} from 'react-devtools-shared/src/backend/types';
import type {ComponentFilter} from 'react-devtools-shared/src/frontend/types';

import {installHook} from 'react-devtools-shared/src/hook';
import {
  getIfReloadedAndProfiling,
  getProfilingSettings,
} from 'react-devtools-shared/src/utils';
import {postMessage} from './messages';
import {createReactRendererListener} from './reactBuildType';

let resolveHookSettingsInjection: (settings: DevToolsHookSettings)

ct-devtools-settings-injector') {
    const payload = event.data.payload;
    // In case handshake message was sent prior to hookSettingsInjector execution
    // We can't guarantee order
    if (payload.handshake) {
      postMessage({
        source: 're

 => void;
let resolveComponentFiltersInjection: (filters: Array<ComponentFilter>) => void;

function messageListener(event: UnknownMessageEvent) {
  if (event.source !== window) {
    return;
  }

  if (event.data.source === 'rea


rome */

let lastSentDevToolsHookMessage;

// We want to detect when a renderer attaches, and notify the "background page"
// (which is shared between tabs and can highlight the React icon).
// Currently we are in "content script" context, so we can't listen to the hook directly
// (it will be injected directly into the page).
// So instead, the hook will use postMessage() to pass message to us here.
// And when this happens, we'll send a message to the "background page".
window.addEventListener('message',

'react-devtools-hook') {
    const {source: messageSource, payload} = data;
    const message = {source: messageSource, payload};

    lastSentDevToolsHookMessage = message;
    chrome.runtime.sendMessage(message);
  }
});

// NOTE: Firefox WebExtensions c

function onMessage({data, source}) {
  if (source !== window || !data) {
    return;
  }

  // We keep this logic here and not in `proxy.js`, because proxy content script is injected later at `document_end`
  if (data.source ===


* global chrome */

'use strict';

function injectProxy() {
  // Firefox's behaviour for injecting this content script can be unpredictable
  // While navigating the history, some content scripts might not be re-injected and still be alive
  if (!window.__REACT_DEVTOOLS_PROXY_INJECTED__) {
    window.__REACT_DEVTOOLS_PROXY_INJECTED__ = true;

    connectPort();
    sayHelloToBackendManager();

    // The backend waits to install the global hook until notified by the content script.
    // In the event of a

> {
      if (backendInitialized) {
        clearInterval(intervalID);
      } else {
        sayHelloToBackendManager();
      }
    }, 500);
  }
}

function handlePageShow() {
  if (document.prerendering) {
    // React DevTools can't handle multiple doc

page reload, the content script might be loaded before the backend manager is injected.
    // Because of this we need to poll the backend manager until it has been initialized.
    const intervalID: IntervalID = setInterval(() =


     * An array that contains all the object results that have been
     * returned by this mock function call
     */
    results: Array<{isThrow: boolean, value: TReturn}>,
  },
  /**
   * Resets all information stored in the mockFn.mock.calls and
   * mockFn.mock.instances arrays. Often this is useful when you want to clean
   * up a mock's usage data between two assertions.
   */
  mockClear(): void,
  /**
   * Resets all information stored in the mock. This is useful when you want to
   * completely re

* original implementation in others. Beware that mockFn.mockRestore only
   * works when mock was created with jest.spyOn. Thus you have to take care of
   * restoration yourself when manually assigning jest.fn().
   */
  mockRestore(): void,
  /**
   * Ac

store a mock back to its initial state.
   */
  mockReset(): void,
  /**
   * Removes the mock and restores the initial implementation. This is useful
   * when you want to mock functions in certain test cases and restore the


 strict';

const {exec} = require('child-process-promise');
const {Finder} = require('firefox-profile');
const {resolve} = require('path');
const {argv} = require('yargs');

const EXTENSION_PATH = resolve('./firefox/build/unpacked');
const START_URL = argv.url || 'https://react.dev/';

const firefoxVersion = process.env.WEB_EXT_FIREFOX;

const getFirefoxProfileName = () => {
  // Keys are pulled from https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#--firefox
  // and profile na

htly':
      return 'default-nightly';
    case 'firefoxdeveloperedition':
      return 'dev-edition-default';
    default:
      // Fall back to using the default Firefox profile for testing purposes.
      // This prevents users from having to re-login-t

mes from https://searchfox.org/mozilla-central/source/toolkit/profile/xpcshell/head.js#96
  switch (firefoxVersion) {
    case 'firefox':
      return 'default-release';
    case 'beta':
      return 'default-beta';
    case 'nig


ct-core
 */

'use strict';

let React;
let ReactDOMServer;
let Suspense;

describe('ReactDOMServerFB', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactDOMServer = require('../ReactDOMServerFB');
    Suspense = React.Suspense;
  });

  const theError = new Error('This is an error');
  function Throw() {
    throw theError;
  }
  const theInfinitePromise = new Promise(() => {});
  function InfiniteSuspend() {
    throw theInfinitePromise;
  }

  function readResult

const stream = ReactDOMServer.renderToStream(
hello world
, {
      onError(x) {
        console.error(x);
      },
    });
    const result = readResult(stream);
    expect(result).toMatchInlineSnapshot(`"<div>hello world</div>"`);
  });

  it('

(stream) {
    let result = '';
    while (!ReactDOMServer.hasFinished(stream)) {
      result += ReactDOMServer.renderNextChunk(stream);
    }
    return result;
  }

  it('should be able to render basic HTML', async () => {


ent(props) {
          useCustomEffect(() => {
            console.log(props.foo);
          }, []);
        }
      `,
      options: [{additionalHooks: 'useAnotherEffect'}],
    },
    {
      code: normalizeIndent`
        function MyComponent(props) {
          useWithoutEffectSuffix(() => {
            console.log(props.foo);
          }, []);
        }
      `,
    },
    {
      code: normalizeIndent`
        function MyComponent(props) {
          return renderHelperConfusedWithEffect(() => {

> {
          console.log(local);
        }, []);
      `,
    },
    {
      // Valid because we don't care about hooks outside of components.
      code: normalizeIndent`
        const local1 = {};
        {
          const local2 = {};
          useEffe

      console.log(props.foo);
          }, []);
        }
      `,
    },
    {
      // Valid because we don't care about hooks outside of components.
      code: normalizeIndent`
        const local = {};
        useEffect(() =


ray of the previous segments.
   *   This array includes unreachable segments.
   * @param {boolean} reachable A flag which shows this is reachable.
   */
  constructor(id, allPrevSegments, reachable) {
    /**
     * The identifier of this code path.

-------------------------------------------------------------------------

/**
 * A code path segment.
 */
class CodePathSegment {
  /**
   * @param {string} id An identifier.
   * @param {CodePathSegment[]} allPrevSegments An ar


disable-next-line
const CodePathState = require('./code-path-state');
// eslint-disable-next-line
const IdGenerator = require('./id-generator');

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

/**
 * A code path.
 */
class CodePath {
  /**
   * Creates a new instance.
   * @param {Object} options Options for the function (see below).
   * @param {string} options.id An ident

ooping.
   */
  constructor({id, origin, upper, onLooped}) {
    /**
     * The identifier of this code path.
     * Rules use it to store additional information of each rule.
     * @type {string}
     */
    this.id = id;

    /**
     * The reason that

ifier.
   * @param {string} options.origin The type of code path origin.
   * @param {CodePath|null} options.upper The code path of the upper function scope.
   * @param {Function} options.onLooped A callback function to notify l


opyright (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.
 */

'use strict';

// TODO: this doesn't make sense for an ESLint rule.
// We need to fix our build process to not create bundles for "raw" packages like this.
if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/eslint-plugin-react-hooks.production.js');
} else {
  module.exports = require('./cjs/eslint-

ode’s cjs-module-lexer to make named imports work
// https://github.com/facebook/react/issues/34801#issuecomment-3433478810
// eslint-disable-next-line ft-flow/no-unused-expressions
0 &&
  (module.exports = {
    meta: true,
    rules: true,
    configs: t

plugin-react-hooks.development.js');
}

// Hint to N


 NetworkMeasuresView,
  ReactMeasuresView,
  SchedulingEventsView,
  SnapshotsView,
  SuspenseEventsView,
  ThrownErrorsView,
  TimeAxisMarkersView,
  UserTimingMarksView,
} from './content-views';
import {COLORS} from './content-views/constants';
import {clampState, moveStateToRange} from './view-base/utils/scrollState';
import EventTooltip from './EventTooltip';
import {MAX_ZOOM_LEVEL, MIN_ZOOM_LEVEL} from './view-base/constants';
import {TimelineSearchContext} from './TimelineSearchContext';
import {Time

;

type Props = {
  profilerData: TimelineData,
  viewState: ViewState,
};

function CanvasPage({profilerData, viewState}: Props): React.Node {
  return (
    <div
      className={styles.CanvasPage}
      style={{backgroundColor: COLORS.BACKGROUND}}>

lineContext} from './TimelineContext';
import CanvasPageContextMenu from './CanvasPageContextMenu';

import type {ContextMenuRef} from 'react-devtools-shared/src/devtools/ContextMenu/types';

import styles from './CanvasPage.css'


import type {ViewState} from './types';

import * as React from 'react';
import {
  Suspense,
  useContext,
  useDeferredValue,
  useLayoutEffect,
  useRef,
  useState,
} from 'react';
import {SettingsContext} from 'react-devtools-shared/src/devtools/views/Settings/SettingsContext';
import {ProfilerContext} from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext';
import NoProfilingData from 'react-devtools-shared/src/devtools/views/Profiler/NoProfilingData';
import RecordingInProgress from

;
import {importFile} from './timelineCache';
import TimelineSearchInput from './TimelineSearchInput';
import TimelineNotSupported from './TimelineNotSupported';
import {TimelineSearchContextController} from './TimelineSearchContext';

import styles from '

'react-devtools-shared/src/devtools/views/Profiler/RecordingInProgress';
import {updateColorsToMatchTheme} from './content-views/constants';
import {TimelineContext} from './TimelineContext';
import CanvasPage from './CanvasPage'


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {ReactContext, RefObject} from 'shared/ReactTypes';

import * as React from 'react';
import {
  createContext,
  useContext,
  useMemo,
  useRef,
  useState,
  useSyncExternalStore,
} from 'react';
import {StoreContext} from 'react-devtools-shared/src/devtools/views/context';

import type {
  HorizontalScrollStateChangeCallback,
  TimelineData,
  SearchRegExpStateChangeCallback,
  ViewState,
  R

: RefObject,
  setFile: (file: File | null) => void,
  viewState: ViewState,
  selectEvent: ReactEventInfo => void,
  selectedEvent: ReactEventInfo,
};

const TimelineContext: ReactContext<Context> = createContext<Context>(
  ((null: any): Context),
);
Tim

eactEventInfo,
} from './types';

export type Context = {
  file: File | null,
  inMemoryTimelineData: Array<TimelineData> | null,
  isPerformanceTracksSupported: boolean,
  isTimelineSupported: boolean,
  searchInputContainerRef


, 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
 */
/* global chrome */

'use strict';
import type {ReactBuildType} from 'react-devtools-shared/src/backend/types';

function setExtensionIconAndPopup(
  reactBuildType: ReactBuildType,
  tabId: number,
) {
  chrome.action.setIcon({
    tabId,
    path: {
      '16': chrome.runtime.getURL(`icons/16-${reactBuildType}.png`),
      '32': chrome.runt

'48': chrome.runtime.getURL(`icons/48-${reactBuildType}.png`),
      '128': chrome.runtime.getURL(`icons/128-${reactBuildType}.png`),
    },
  });

  chrome.action.setPopup({
    tabId,
    popup: chrome.runtime.getURL(`popups/${reactBuildType}.html`),
  }


nder the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {evalScripts} from '../evalScripts';

window.addEventListener('message', event => {
  if (event.data?.source === 'react-devtools-content-script-eval') {
    const {scriptId, args, requestId} = event.data.payload;
    const response = {result: null, error: null};
    try {
      if (!evalScripts[scriptId]) {
        throw new Error(`No eval script with id "${scriptId}" exists.`);
      }

ll, args);
    } catch (err) {
      response.error = err.message;
    }
    window.postMessage(
      {
        source: 'react-devtools-content-script-eval-response',
        payload: {
          requestId,
          response,
        },
      },
      '*


hrome.storage domain from scripts which are injected in ExecutionWorld.MAIN
// This is the only purpose of this script - to send persisted settings to installHook.js content script

import type {UnknownMessageEvent} from './messages';
import type {
  DevToolsHookSettings,
  DevToolsSettings,
} from 'react-devtools-shared/src/backend/types';
import type {ComponentFilter} from 'react-devtools-shared/src/frontend/types';
import {postMessage} from './messages';

import {getDefaultComponentFilters} from 'react-d

handshake) {
      const settings: Partial<DevToolsSettings> =
        await chrome.storage.local.get();
      // If storage was empty (first installation), define default settings
      const hookSettings: DevToolsHookSettings = {
        appendComponentS

evtools-shared/src/utils';

async function messageListener(event: UnknownMessageEvent) {
  if (event.source !== window) {
    return;
  }

  if (event.data.source === 'react-devtools-hook-installer') {
    if (event.data.payload.


818d1b
// flow-typed version: 9c71eca8ef/react-test-renderer_v16.x.x/flow_>=v0.47.x

// Type definitions for react-test-renderer 16.x.x
// Ported from: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-test-renderer

'use strict';

/* eslint-disable no-unused-vars */

type ReactComponentInstance = React$Component<any>;

type ReactTestRendererJSON = {
  type: string,
  props: {[propName: string]: any},
  children: null | ReactTestRendererJSON[],
};

type ReactTestRendererTree = React

propName: string]: any},
  parent: null | ReactTestInstance,
  children: Array<ReactTestInstance | string>,

  find(predicate: (node: ReactTestInstance) => boolean): ReactTestInstance,
  findByType(type: React$ElementType): ReactTestInstance,
  findByProps

TestRendererJSON & {
  nodeType: 'component' | 'host',
  instance: ?ReactComponentInstance,
  rendered: null | ReactTestRendererTree,
};

type ReactTestInstance = {
  instance: ?ReactComponentInstance,
  type: string,
  props: {[


usr/bin/env node

'use strict';

const chalk = require('chalk');
const build = require('../build');

const main = async () => {
  await build('firefox');

  console.log(chalk.green('\nThe Firefox extension has been built!'));
  console.log(chalk.green('You can test this build by running:'));
  console.log(chalk.gray('\n# From the react-devtools root directory:'));
  console.log('yarn run test:firefox');
  console.log(
    chalk.gray('\n# You can also test against upcoming Firefox releases.')
  );
  console.

redition, nightly, beta):'
    )
  );
  console.log('WEB_EXT_FIREFOX=nightly yarn run test:firefox');
  console.log(chalk.gray('\n# You can test against older versions too:'));
  console.log(
    'WEB_EXT_FIREFOX=/Applications/Firefox Developer Edition.app

log(
    chalk.gray(
      '# First download a release from https://www.mozilla.org/en-US/firefox/channel/desktop/'
    )
  );
  console.log(
    chalk.gray(
      '# And then tell web-ext which release to use (eg firefoxdevelope