re from '../../Fixture';
import EventFragmentContainer from './EventFragmentContainer';

const React = window.React;
const {useState} = React;

function WrapperComponent(props) {
  return props.children;
}

export default function EventListenerCase() {
  const [extraChildCount, setExtraChildCount] = useState(0);

  return (
    <TestCase title="Event Registration">
      <TestCase.Steps>

          Click "Add event listener" to attach a click handler to the fragment

Cli

vent listener" and dispatch again to see no event fires
        </li>
      </TestCase.Steps>

      <TestCase.ExpectedResult>
        <p>
          Fragment refs can manage event listeners on the first level of host
          children. The event log shows

ck "Dispatch click event" to dispatch a click event

Observe the event log showing the event fired

Add a new child, dispatch again to see it still works

          Click "Remove e


re from '../../Fixture';

const React = window.React;

const {Fragment, useRef} = React;

export default function FocusCase() {
  const fragmentRef = useRef(null);

  return (
    <TestCase title="Focus Management">
      <TestCase.Steps>

Click to focus the first child

Click to focus the last child

Click to blur any focus within the fragment

      </TestCase.Steps>

      <TestCase.ExpectedResult>

          The focus method will focus the first

     Blur will call blur on the document, only if one of the children
          within the fragment is the active element.
        </p>
      </TestCase.ExpectedResult>

      <Fixture>
        <Fixture.Controls>
          <button onClick={() => fragmentRe

focusable child within the
          fragment, skipping any unfocusable children.
        </p>
        <p>
          The focusLast method is the reverse, focusing the last focusable
          child.
        </p>
        <p>


../TestCase';
import Fixture from '../../Fixture';
import PrintRectsFragmentContainer from './PrintRectsFragmentContainer';

const React = window.React;

export default function GetClientRectsCase() {
  return (
    <TestCase title="getClientRects">
      <TestCase.Steps>
        <li>
          Click the "Print Rects" button to get the client rects of the
          elements.
        </li>
      </TestCase.Steps>
      <TestCase.ExpectedResult>
        Calling getClientRects on the fragment instance will ret

 width: '300px',
                height: '250px',
                backgroundColor: 'lightblue',
                fontSize: 20,
                border: '1px solid black',
                marginBottom: '10px',
              }}>
              Lorem ipsum dolor

urn a list of a
        DOMRectList for each child node.
      </TestCase.ExpectedResult>
      <Fixture>
        <Fixture.Controls>
          <PrintRectsFragmentContainer>
            <span
              style={{


, useState} = React;

export default function GetRootNodeFragmentContainer({children}) {
  const fragmentRef = useRef(null);
  const [rootNodeInfo, setRootNodeInfo] = useState(null);

  const getRootNodeInfo = () => {
    const rootNode = fragmentRef.current.getRootNode();
    setRootNodeInfo({
      nodeName: rootNode.nodeName,
      nodeType: rootNode.nodeType,
      nodeTypeLabel: getNodeTypeLabel(rootNode.nodeType),
      isDocument: rootNode === document,
    });
  };

  const getNodeTypeLabel = nodeTy

>
      <div style={{marginBottom: '16px'}}>
        <button
          onClick={getRootNodeInfo}
          style={{
            padding: '8px 16px',
            fontSize: '14px',
            fontWeight: 'bold',
            cursor: 'pointer',
          }}>

pe => {
    const types = {
      1: 'ELEMENT_NODE',
      3: 'TEXT_NODE',
      9: 'DOCUMENT_NODE',
      11: 'DOCUMENT_FRAGMENT_NODE',
    };
    return types[nodeType] || `UNKNOWN (${nodeType})`;
  };

  return (
    <Fragment


t;
const {Fragment, useEffect, useRef, useState} = React;

function WrapperComponent(props) {
  return props.children;
}

function ObservedChild({id}) {
  return (
    <div id={id} className="observable-card">
      {id}
    </div>
  );
}

const initialItems = [
  ['A', false],
  ['B', false],
  ['C', false],
];

export default function IntersectionObserverCase() {
  const fragmentRef = useRef(null);
  const [items, setItems] = useState(initialItems);
  const addedItems = items.slice(3);
  const anyOnScreen

tems(prev => {
            const newItems = [...prev];
            entries.forEach(entry => {
              const index = newItems.findIndex(
                ([id]) => id === entry.target.id
              );
              newItems[index] = [entry.target.id

 = items.some(([, onScreen]) => onScreen);
  const observerRef = useRef(null);

  useEffect(() => {
    if (observerRef.current === null) {
      observerRef.current = new IntersectionObserver(
        entries => {
          setI


  '#3498db',
  '#2ecc71',
  '#9b59b6',
  '#f39c12',
  '#1abc9c',
];

export default function PrintRectsFragmentContainer({children}) {
  const fragmentRef = useRef(null);
  const [rects, setRects] = useState([]);

  const getRects = () => {
    const rectsResult = fragmentRef.current.getClientRects();
    setRects(Array.from(rectsResult));
  };

  const getColor = index => colors[index % colors.length];

  return (
    <Fragment>
      <div style={{marginBottom: '16px'}}>
        <button
          onClick=

th > 0 && (

            Found {rects.length} rect{rects.length !== 1 ? 's' : ''}

        )}

      <div style={{display: 'flex', gap: '20px', marginBottom: '16px'}}

{getRects}
          style={{
            padding: '8px 16px',
            fontSize: '14px',
            fontWeight: 'bold',
            cursor: 'pointer',
          }}>
          Print Rects
        </button>
        {rects.leng


../TestCase';
import Fixture from '../../Fixture';

const React = window.React;
const {Fragment, useEffect, useRef, useState} = React;

export default function ResizeObserverCase() {
  const fragmentRef = useRef(null);
  const [width, setWidth] = useState([0, 0, 0]);

  useEffect(() => {
    const resizeObserver = new window.ResizeObserver(entries => {
      if (entries.length > 0) {
        setWidth(prev => {
          const newWidth = [...prev];
          entries.forEach(entry => {
            const index

const lastFragmentRefValue = fragmentRef.current;
    return () => {
      lastFragmentRefValue.unobserveUsing(resizeObserver);
    };
  }, []);

  return (
    <TestCase title="Resize Observer">
      <TestCase.Steps>
        <li>Resize the viewport width

 = parseInt(entry.target.id, 10);
            newWidth[index] = Math.round(entry.contentRect.width);
          });
          return newWidth;
        });
      }
    });

    fragmentRef.current.observeUsing(resizeObserver);


imple';
import ScrollIntoViewTargetElement from './ScrollIntoViewTargetElement';

const React = window.React;
const {Fragment, useRef, useState, useEffect} = React;
const ReactDOM = window.ReactDOM;

function Controls({
  alignToTop,
  setAlignToTop,
  scrollVertical,
  exampleType,
  setExampleType,
}) {
  return (
    <div>
      <label>
        Example Type:
        <select
          value={exampleType}
          onChange={e => setExampleType(e.target.value)}>
          <option value="simple">Simple</opt

div>
        <label>
          Align to Top:
          <input
            type="checkbox"
            checked={alignToTop}
            onChange={e => setAlignToTop(e.target.checked)}
          />
        </label>
      </div>
      <div>
        <button on

ion>
          <option value="multiple">Multiple Scroll Containers</option>
          <option value="horizontal">Horizontal</option>
          <option value="empty">Empty Fragment</option>
        </select>
      </label>
      <


lIntoViewTargetElement from './ScrollIntoViewTargetElement';

const React = window.React;
const {Fragment, useRef, useState, useEffect} = React;
const ReactDOM = window.ReactDOM;

export default function ScrollIntoViewCaseComplex({
  caseInViewport,
  scrollContainerRef,
}) {
  const [didMount, setDidMount] = useState(false);
  // Hack to portal child into the scroll container
  // after the first render. This is to simulate a case where
  // an item is portaled into another scroll container.
  useEffect(()

        Fixed header
        </div>
      )}
      {didMount &&
        ReactDOM.createPortal(
          <ScrollIntoViewTargetElement color="red" id="FROM_PORTAL" />,
          scrollContainerRef.current
        )}
      <ScrollIntoViewTargetElement color=

 => {
    if (!didMount) {
      setDidMount(true);
    }
  }, []);
  return (
    <Fragment>
      {caseInViewport && (
        <div
          style={{position: 'fixed', top: 0, backgroundColor: 'red'}}
          id="header">


eact;
const {Fragment, useRef, useState} = React;

function GetClientRectsTextOnly() {
  return (
    <TestCase title="getClientRects - Text Only">
      <TestCase.Steps>

Click the "Print Rects" button

      </TestCase.Steps>
      <TestCase.ExpectedResult>
        The fragment contains only text nodes. getClientRects should return
        bounding rectangles for the text content using the Range API.
      </TestCase.ExpectedResult>
      <Fixture>
        <Fixture.Controls>
          <Prin

tRectsMixed() {
  return (
    <TestCase title="getClientRects - Mixed Content">
      <TestCase.Steps>

Click the "Print Rects" button

      </TestCase.Steps>
      <TestCase.ExpectedResult>
        The fragment contains both text nodes an

tRectsFragmentContainer>
            This is text content inside a fragment with no element children.
          </PrintRectsFragmentContainer>
        </Fixture.Controls>
      </Fixture>
    </TestCase>
  );
}

function GetClien


;
import EventDispatchCase from './EventDispatchCase';
import IntersectionObserverCase from './IntersectionObserverCase';
import ResizeObserverCase from './ResizeObserverCase';
import FocusCase from './FocusCase';
import GetClientRectsCase from './GetClientRectsCase';
import CompareDocumentPositionCase from './CompareDocumentPositionCase';
import ScrollIntoViewCase from './ScrollIntoViewCase';
import TextNodesCase from './TextNodesCase';

const React = window.React;

export default function FragmentRefsPage

">
      <EventListenerCase />
      <EventDispatchCase />
      <IntersectionObserverCase />
      <ResizeObserverCase />
      <FocusCase />
      <GetClientRectsCase />
      <CompareDocumentPositionCase />
      <ScrollIntoViewCase />
      <TextNodesC

() {
  return (
    <FixtureSet title="Fragment Refs


re from '../../Fixture';
const React = window.React;

class InputPlaceholderFixture extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      placeholder: 'A placeholder',
      changeCount: 0,
    };
  }

  handleChange = () => {
    this.setState(({changeCount}) => {
      return {
        changeCount: changeCount + 1,
      };
    });
  };
  handleGeneratePlaceholder = () => {
    this.setState({
      placeholder: `A placeholder: ${Math.random() * 100

(
      <Fixture>
        <input
          type="text"
          placeholder={placeholder}
          onChange={this.handleChange}
        />{' '}
        <button onClick={this.handleGeneratePlaceholder}>
          Change placeholder
        </button>

}`,
    });
  };

  handleReset = () => {
    this.setState({
      changeCount: 0,
    });
  };

  render() {
    const {placeholder, changeCount} = this.state;
    const color = changeCount === 0 ? 'green' : 'red';

    return


import Fixture from '../../Fixture';
const React = window.React;

class RadioClickFixture extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      changeCount: 0,
    };
  }

  handleChange = () => {
    this.setState(({changeCount}) => {
      return {
        changeCount: changeCount + 1,
      };
    });
  };

  handleReset = () => {
    this.setState({
      changeCount: 0,
    });
  };

  render() {
    const {changeCount} = this.state;
    const co

p style={{color}}>
          onChange
          {' calls: '}
          {changeCount}

        <button onClick={this.handleReset}>Reset count</button>
      </Fixture>
    );
  }
}

export default RadioClickFixture;

lor = changeCount === 0 ? 'green' : 'red';

    return (
      <Fixture>
        <label>
          <input defaultChecked type="radio" onChange={this.handleChange} />
          Test case radio input
        </label>{' '}
        <


 Fixture from '../../Fixture';
const React = window.React;

class RadioGroupFixture extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      changeCount: 0,
    };
  }

  handleChange = () => {
    this.setState(({changeCount}) => {
      return {
        changeCount: changeCount + 1,
      };
    });
  };

  handleReset = () => {
    this.setState({
      changeCount: 0,
    });
  };

  render() {
    const {changeCount} = this.state;
    const color =

Radio 1

          <input name="foo" type="radio" onChange={this.handleChange} />
          Radio 2
        {' '}

          onChange
          {' calls: '}

changeCount >= 3 ? 'green' : 'red';

    return (
      <Fixture>
        <label>
          <input
            defaultChecked
            name="foo"
            type="radio"
            onChange={this.handleChange}
          />


eFixture extends React.Component {
  state = {
    updated: false,
  };
  onClick = () => {
    this.setState(state => {
      return {updated: !state.updated};
    });
  };
  render() {
    const {updated} = this.state;
    const radioName = updated ? 'firstName' : 'secondName';
    return (
      <div>
        <label>
          <input
            type="radio"
            name={radioName}
            onChange={noop}
            checked={updated === true}
          />
          First Radio
        </label>

radio"
            name={radioName}
            onChange={noop}
            checked={updated === false}
          />
          Second Radio
        </label>

        <div>
          <button type="button" onClick={this.onClick}>
            Toggle

        <label>
          <input
            type="


./Fixture';
const React = window.React;

class RangeKeyboardFixture extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      keydownCount: 0,
      changeCount: 0,
    };
  }

  componentDidMount() {
    this.input.addEventListener('keydown', this.handleKeydown, false);
  }

  componentWillUnmount() {
    this.input.removeEventListener('keydown', this.handleKeydown, false);
  }

  handleChange = () => {
    this.setState(({changeCount}) => {
      return

ownCount}) => {
      return {
        keydownCount: keydownCount + 1,
      };
    });
  };

  handleReset = () => {
    this.setState({
      keydownCount: 0,
      changeCount: 0,
    });
  };

  render() {
    const {keydownCount, changeCount} = this.s

 {
        changeCount: changeCount + 1,
      };
    });
  };

  handleKeydown = e => {
    // only interesting in arrow key events
    if ([37, 38, 39, 40].indexOf(e.keyCode) < 0) {
      return;
    }

    this.setState(({keyd


Fixture from './RangeKeyboardFixture';
import RadioClickFixture from './RadioClickFixture';
import RadioGroupFixture from './RadioGroupFixture';
import RadioNameChangeFixture from './RadioNameChangeFixture';
import InputPlaceholderFixture from './InputPlaceholderFixture';
const React = window.React;

class InputChangeEvents extends React.Component {
  render() {
    return (
      <FixtureSet
        title="Input change events"
        description="Tests proper behavior of the onChange event for inputs">

change value via the keyboard arrow keys

          </TestCase.Steps>

          <TestCase.ExpectedResult>
            The onKeyDown call count should be equal to the{' '}
            onChange call count.

      <TestCase
          title="Range keyboard changes"
          description={`
            Range inputs should fire onChange events for keyboard events
          `}>
          <TestCase.Steps>
            <li>Focus range input


, ms)
    );
  }
  return null;
}

let suspendyTreeIdCounter = 0;
class SuspendyTreeChild extends React.Component {
  id = suspendyTreeIdCounter++;
  state = {
    step: 1,
    isHidden: false,
  };
  increment = () => this.setState(s => ({step: s.step + 1}));

  componentDidMount() {
    document.addEventListener('keydown', this.onKeydown);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.onKeydown);
  }

  onKeydown = event => {
    if (event.metaKey && event.key === 'Enter

        {this.props.children}
          </div>
        </Suspense>
        <button onClick={this.increment}>Hide</button>
      </>
    );
  }
}

class SuspendyTree extends React.Component {
  parentContainer = React.createRef(null);
  container = React.cr

') {
      this.increment();
    }
  };

  render() {
    return (
      <>
        <Suspense fallback={
(display: none)
}>

            <AsyncStep text={`${this.state.step} + ${this.id}`} ms={500} />


Set from '../../FixtureSet';
import TestCase from '../../TestCase';

const React = window.React;

export default class TextAreaFixtures extends React.Component {
  state = {value: ''};
  onChange = event => {
    this.setState({value: event.target.value});
  };
  render() {
    return (
      <FixtureSet title="Textareas">
        <TestCase
          title="Kitchen Sink"
          description="Verify that the controlled textarea displays its value under 'Controlled Output', and that both textareas can be ty

/fieldset>
              <fieldset>
                <legend>Uncontrolled</legend>
                <textarea defaultValue="" />
              </fieldset>
            </form>

Controlled Output:

ped in">
          <div>
            <form className="container">
              <fieldset>
                <legend>Controlled</legend>
                <textarea value={this.state.value} onChange={this.onChange} />
              <


esTestCase extends React.Component {
  state = {value: 'a@fb.com'};
  onChange = event => {
    this.setState({value: event.target.value});
  };
  render() {
    return (
      <Fixture>

{this.props.children}

          <fieldset>
            <legend>Controlled</legend>
            <input
              type="email"
              value={this.state.value}
              onChange={this.onChange}
            />

.state.value)}
            </span>
          </fieldset>

          <fieldset>
            <legend>Uncontrolled</legend>
            <input type="email" defaultValue="" />
          </fieldset>
        </div>
      </Fixture>
    );
  }
}

export default E

     {' '}
              Value: {JSON.stringify(this


Fixture from '../../Fixture';

const React = window.React;

class EmailAttributesTestCase extends React.Component {
  state = {value: 'a@fb.com'};
  onChange = event => {
    this.setState({value: event.target.value});
  };
  render() {
    return (
      <Fixture>

{this.props.children}

          <fieldset>
            <legend>Controlled</legend>
            <input
              type="email"
              pattern=".+@fb.com"
              maxlength=

te.value)}
            </span>
          </fieldset>

          <fieldset>
            <legend>Uncontrolled</legend>
            <input
              type="email"
              defaultValue=""
              pattern=".+@fb.com"
              maxlength={17}

{17}
              multiple={true}
              value={this.state.value}
              onChange={this.onChange}
            />
            <span className="hint">
              {' '}
              Value: {JSON.stringify(this.sta


extends React.Component {
  state = {value: ''};
  onChange = event => {
    this.setState({value: event.target.value});
  };
  render() {
    return (
      <Fixture>

{this.props.children}

          <fieldset>
            <legend>Controlled</legend>
            <input
              type="email"
              value={this.state.value}
              onChange={this.onChange}
            />

              {' '}

         </span>
          </fieldset>

          <fieldset>
            <legend>Uncontrolled</legend>
            <input type="email" defaultValue="" />
          </fieldset>
        </div>
      </Fixture>
    );
  }
}

export default JumpingCursorTestCa


ent, commentSource}) {
  const currentUserID = comment.viewer.id;
  const environment = RelayEnvironment.forUser(currentUserID);
  const commentID = nullthrows(comment.id);
  useEffect(() => {
    const subscription = SubscriptionCounter.subscribeOnce(
      `StoreSubscription_${commentID}`,
      () =>
        StoreSubscription.subscribe(
          environment,
          {
            comment_id: commentID,
          },
          currentUserID,
          commentSource
        )
    );
    return () => subs

}
function UseEffectWithEmptyDependencies() {
  useEffect(() => {
    const local = {};
    console.log(local);
  }, []);
}

// OK because `props` wasn't defined.
function ComponentWithNoPropsDefined() {
  useEffect(() => {
    console.log(props.foo);
  },

cription.dispose();
  }, [commentID, commentSource, currentUserID, environment]);
}

// Valid because no dependencies
function UseEffectWithNoDependencies() {
  const local = {};
  useEffect(() => {
    console.log(local);
  });


ileSync,
  existsSync,
  mkdirSync,
  readFileSync,
  rmdirSync,
} = require('fs');
const {join} = require('path');
const http = require('http');

const DEPENDENCIES = [
  ['scheduler/umd/scheduler.development.js', 'scheduler.js'],
  ['react/umd/react.development.js', 'react.js'],
  ['react-dom/umd/react-dom.development.js', 'react-dom.js'],
];

const BUILD_DIRECTORY = '../../../build/oss-experimental/';
const DEPENDENCIES_DIRECTORY = 'dependencies';

function initDependencies() {
  if (existsSync(DEPENDENC

 toPath = join(__dirname, DEPENDENCIES_DIRECTORY, to);
    console.log(`Copying ${fromPath} => ${toPath}`);
    copyFileSync(fromPath, toPath);
  });
}

function initServer() {
  const host = 'localhost';
  const port = 8000;

  const requestListener = fun

IES_DIRECTORY)) {
    rmdirSync(DEPENDENCIES_DIRECTORY, {recursive: true});
  }
  mkdirSync(DEPENDENCIES_DIRECTORY);

  DEPENDENCIES.forEach(([from, to]) => {
    const fromPath = join(__dirname, BUILD_DIRECTORY, from);
    const


dled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Ensure environment variables are read.
require('../config/env');

const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = requir

tils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');

const measureFileSizesBeforeBuild =
  FileSizeReporter.measureFileSizesBeforeBuild;

e('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-u


dable} from 'stream';
import {ClientContext, ClientReadContext} from './ClientContext.js';
import Container from './Container.js';

import {Counter} from './Counter.js';
import {Counter as Counter2} from './Counter2.js';
import AsyncModule from './cjs/Counter3.js';
const Counter3 = await(AsyncModule);

import ShowMore from './ShowMore.js';
import Button from './Button.js';
import Form from './Form.js';
import {Dynamic} from './Dynamic.js';
import {Client} from './Client.js';
import {Navigate} from './Naviga

/ServerState.js';
import {sdkMethod} from './library.js';

const promisedText = new Promise(resolve =>
  setTimeout(() => resolve('deferred text'), 50)
);

function Foo({children}) {
  return <div>{children}</div>;
}

async function delayedError(text, ms)

te.js';

import {Note} from './cjs/Note.js';

import {GenerateImage} from './GenerateImage.js';

import LargeContent from './LargeContent.js';

import {like, greet, increment} from './actions.js';

import {getServerState} from '.


'use client';

import * as React from 'react';
import Container from './Container.js';

export function Navigate() {
  /** Repro for https://issues.chromium.org/u/1/issues/419746417 */
  function provokeChromeCrash() {
    React.startTransition(async () => {
      console.log('Default transition triggered');

      await new Promise(resolve => {
        setTimeout(
          () => {
            history.pushState(
              {},
              '',
              `?chrome-crash-419746417=${performance.now()}

console.log('Default transition completed');
          resolve();
        }, 1000);
      });
    });
  }

  return (
    <Container>

Navigation fixture

      <button onClick={provokeChromeCrash}>Provoke Chrome Crash (fixed)</button>
    </C

`
            );
          },
          // This needs to happen before React's default transition indicator
          // is displayed but after it's scheduled.
          100 + -50
        );

        setTimeout(() => {


/core';

const babelOptions = {
  babelrc: false,
  ignore: [/\/(build|node_modules)\//],
  plugins: [
    '@babel/plugin-syntax-import-meta',
    ['@babel/plugin-transform-react-jsx', {runtime: 'automatic'}],
  ],
};

export async function load(url, context, defaultLoad) {
  const {format} = context;
  const result = await defaultLoad(url, context, defaultLoad);
  if (result.format === 'module') {
    const opt = Object.assign({filename: url}, babelOptions);
    const newResult = await babel.transformAsync

 };
    }
    return {source: newResult.code, format: 'module'};
  }
  return defaultLoad(url, context, defaultLoad);
}

async function babelTransformSource(source, context, defaultTransformSource) {
  const {format} = context;
  if (format === 'module') {

(result.source, opt);
    if (!newResult) {
      if (typeof result.source === 'string') {
        return result;
      }
      return {
        source: Buffer.from(result.source).toString('utf8'),
        format: 'module',


env.
process.env.BABEL_ENV = process.env.NODE_ENV;

const babelRegister = require('@babel/register');
babelRegister({
  babelrc: false,
  ignore: [
    /\/(build|node_modules)\//,
    function (file) {
      if ((path.dirname(file) + '/').startsWith(__dirname + '/')) {
        // Ignore everything in this folder
        // because it's a mix of CJS and ESM
        // and working with raw code is easier.
        return true;
      }
      return false;
    },
  ],
  presets: ['@babel/preset-react'],
});

//

e('http');
const React = require('react');

const {renderToPipeableStream} = require('react-dom/server');
const {createFromNodeStream} = require('react-server-dom-unbundled/client');
const {PassThrough} = require('stream');

const app = express();

app.use

Ensure environment variables are read.
require('../config/env');

const fs = require('fs').promises;
const compress = require('compression');
const chalk = require('chalk');
const express = require('express');
const http = requir


);

// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  throw new Error(
    'The NODE_ENV environment variable is required but was not specified.'
  );
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
  `${paths.dotenv}.${NODE_ENV}.local`,
  // Don't include `.env.local` for `test` environment
  // since normally you expect tests t

 using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.  Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
d

o produce the same
  // results for everyone
  NODE_ENV !== 'test' && `${paths.dotenv}.local`,
  `${paths.dotenv}.${NODE_ENV}`,
  paths.dotenv,
].filter(Boolean);

// Load environment variables from .env* files. Suppress warnings


fs = require('fs');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <s

.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
  process.env.NODE_ENV === 'development',
  require(resolveApp('package.json')).homepage,
  process.env.PUBLIC_URL
);

const buildPath = process.env.BUILD_PATH || 'build';

const mo

cript> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d


lyfills';
import loadReact, {isLocal} from './react-loader';

if (isLocal()) {
  Promise.all([
    import('react'),
    import('react-dom'),
    import('react-dom/client'),
  ])
    .then(([React, ReactDOM, ReactDOMClient]) => {
      if (
        React === undefined ||
        ReactDOM === undefined ||
        ReactDOMClient === undefined
      ) {
        throw new Error(
          'Unable to load React. Build experimental and then run `yarn dev` again'
        );
      }
      window.React = React;

    window.React.createElement(App.default)
      );
    });
} else {
  loadReact()
    .then(() => import('./components/App'))
    .then(App => {
      const {React, ReactDOM} = window;
      if (
        typeof window.ReactDOMClient !== 'undefined' &&

 window.ReactDOM = ReactDOM;
      window.ReactDOMClient = ReactDOMClient;
    })
    .then(() => import('./components/App'))
    .then(App => {
      window.ReactDOMClient.createRoot(document.getElementById('root')).render(


function parseQuery(qstr) {
  var query = {};
  var a = qstr.slice(1).split('&');

  for (var i = 0; i < a.length; i++) {
    var b = a[i].split('=');
    query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
  }
  return query;
}

function loadScript(src) {
  let firstScript = document.getElementsByTagName('script')[0];
  let scriptNode;

  return new Promise((resolve, reject) => {
    scriptNode = document.createElement('script');
    scriptNode.async = 1;
    scriptNode.src = src;

    scri

 firstScript = document.getElementsByTagName('script')[0];

  let imports = '';
  SymbolSrcPairs.map(([symbol, src]) => {
    imports += `import ${symbol} from "${src}";\n`;
    imports += `window.${symbol} = ${symbol};\n`;
  });

  return new Promise((res

ptNode.onload = () => resolve();
    scriptNode.onerror = () => reject(new Error(`failed to load: ${src}`));

    firstScript.parentNode.insertBefore(scriptNode, firstScript);
  });
}

function loadModules(SymbolSrcPairs) {
  let


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

let React;
let DOMAct;
let TestRenderer;
let TestAct;

global.__DEV__ = process.env.NODE_ENV !== 'production';

describe('unmocked scheduler', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    DOMAct = React.act;
    TestRenderer = require('react-test-renderer');
    TestAct = TestRenderer.act;
  });

  it(

}
    // in legacy mode, this tests whether an act only flushes its own effects
    TestAct(() => {
      DOMAct(() => {
        TestRenderer.create(<Effecty />);
      });
      expect(log).toEqual([]);
    });
    expect(log).toEqual(['called']);

    lo

'flushes work only outside the outermost act() corresponding to its own renderer', () => {
    let log = [];
    function Effecty() {
      React.useEffect(() => {
        log.push('called');
      }, []);
      return null;


d2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
var REACT_SUSPENSE_TYPE = 0xead1;
var REACT_SUSPENSE_LIST_TYPE = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_BLOCK_TYPE = 0xead9;
var REACT_SERVER_BLOCK_TYPE = 0xeada;
var REACT_FUNDAMENTAL_TYPE = 0xead5;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY_HID

r('react.fragment');
  REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
  REACT_PROFILER_TYPE = symbolFor('react.profiler');
  REACT_PROVIDER_TYPE = symbolFor('react.provider');
  REACT_CONTEXT_TYPE = symbolFor('react.context');
  REACT_FORWARD_REF

DEN_TYPE = 0xeae3;

if (typeof Symbol === 'function' && Symbol.for) {
  var symbolFor = Symbol.for;
  REACT_ELEMENT_TYPE = symbolFor('react.element');
  REACT_PORTAL_TYPE = symbolFor('react.portal');
  exports.Fragment = symbolFo


ion

          This page has repeating sections purposefully to create very large
          trees that stress the rendering and streaming capabilities of Fizz

Another Section

this section has a list

item one

item two

item three

item four

item five

it isn't a very interesting list

Smiley Section

here is a list of smiley emojis

😀

😃

😄

😁

😆


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

import {Writable} from 'stream';
import * as React from 'react';
import {renderToPipeableStream} from 'react-dom/server';
import App from '../src/App';
import {ABORT_DELAY} from './delays';

// In a real setup, you'd read it from webpack build stats.
let assets = {
  'main.js': '/main.js',
  'main.css': '/main.css',
};

function HtmlWritable(options) {
  Writable.ca

function _write(chunk, encoding, callback) {
  this.chunks.push(chunk);
  callback();
};
HtmlWritable.prototype._final = function _final(callback) {
  this.html = Buffer.concat(this.chunks).toString();
  callback();
};

module.exports = function render(url

ll(this, options);
  this.chunks = [];
  this.html = '';
}

HtmlWritable.prototype = Object.create(Writable.prototype);
HtmlWritable.prototype.getHtml = function getHtml() {
  return this.html;
};
HtmlWritable.prototype._write =


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

import * as React from 'react';
import {renderToPipeableStream} from 'react-dom/server';
import App from '../src/App';
import {ABORT_DELAY} from './delays';

// In a real setup, you'd read it from webpack build stats.
let assets = {
  'main.js': '/main.js',
  'main.css': '/main.css',
};

module.exports = function render(url, res) {
  // The

 />, {
    bootstrapScripts: [assets['main.js']],
    onAllReady() {
      // Full completion.
      // You can use this for SSG or crawlers.
      didFinish = true;
    },
    onShellReady() {
      // If something errored before we started streaming, we

 new wiring is a bit more involved.
  res.socket.on('error', error => {
    console.error('Fatal', error);
  });
  let didError = false;
  let didFinish = false;
  const {pipe, abort} = renderToPipeableStream(<App assets={assets}


API features in DevTools.
function Feature({children, label, version}) {
  return (

        {label}
        {version}

      {children}

  );
}

// Simplify interaction tracing for tests below.
let trace = null;
if (typeof SchedulerTracing !== 'undefined') {
  trace = SchedulerTracing.unstable_trace;
} else if (typeof ScheduleTracing !== 'undefined') {
  trace = Sched

.useState === 'function') {
          // Hooks
          function Hooks() {
            const [count, setCount] = React.useState(0);
            const incrementCount = React.useCallback(
              () => setCount(count + 1),
              [count]

uleTracing.unstable_trace;
} else {
  trace = (_, __, callback) => callback();
}

// https://github.com/facebook/react/blob/main/CHANGELOG.md
switch (major) {
  case 16:
    switch (minor) {
      case 7:
        if (typeof React


ight/test';

test('smoke test', async ({page}) => {
  const consoleErrors = [];
  page.on('console', msg => {
    const type = msg.type();
    if (type === 'warn' || type === 'error') {
      consoleErrors.push({type: type, text: msg.text()});
    }
  });
  const pageErrors = [];
  page.on('pageerror', error => {
    pageErrors.push(error.stack);
  });
  await page.goto('/');
  await expect(page.getByTestId('promise-as-a-child-test')).toHaveText(
    'Promise as a child hydrates without errors: deferred tex

')).not.toBeAttached();

  await expect(consoleErrors).toEqual([]);
  await expect(pageErrors).toEqual([]);

  await page.goto('/prerender');
  await expect(page.getByTestId('prerendered')).toBeAttached();

  await expect(consoleErrors).toEqual([]);
  awai

t'
  );
  await expect(page.getByTestId('prerendered


dom/client';
import {createFromFetch, encodeReply} from 'react-server-dom-webpack/client';

// TODO: This should be a dependency of the App but we haven't implemented CSS in Node yet.
import './style.css';

function findSourceMapURL(fileName) {
  return (
    document.location.origin +
    '/source-maps?name=' +
    encodeURIComponent(fileName)
  );
}

async function createWebSocketStream(url) {
  const ws = new WebSocket(url);
  ws.binaryType = 'arraybuffer';

  await new Promise((resolve, reject) => {

ose();
    },
    abort(reason) {
      ws.close(1000, reason && String(reason));
    },
  });

  const readable = new ReadableStream({
    start(controller) {
      ws.addEventListener('message', event => {
        controller.enqueue(event.data);
      })

 ws.addEventListener('open', resolve, {once: true});
    ws.addEventListener('error', reject, {once: true});
  });

  const writable = new WritableStream({
    write(chunk) {
      ws.send(chunk);
    },
    close() {
      ws.cl


//,
    function (file) {
      if ((path.dirname(file) + '/').startsWith(__dirname + '/')) {
        // Ignore everything in this folder
        // because it's a mix of CJS and ESM
        // and working with raw code is easier.
        return true;
      }
      return false;
    },
  ],
  presets: ['@babel/preset-react'],
  plugins: ['@babel/transform-modules-commonjs'],
  sourceMaps: process.env.NODE_ENV === 'development' ? 'inline' : false,
});

if (typeof fetch === 'undefined') {
  // Patch fetch for

('compression');
const {Readable} = require('node:stream');

const nodeModule = require('node:module');

app.use(compress());

// Application

const {readFile} = require('fs').promises;

const React = require('react');

const activeDebugChannels =
  proces

 earlier Node versions.
  global.fetch = require('undici').fetch;
}

const express = require('express');
const bodyParser = require('body-parser');
const busboy = require('busboy');
const app = express();
const compress = require


);
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin =
  process.env.TSC_COMPILE_ON_ERROR === 'true'
    ? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
    : require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const {WebpackManife

an cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';

const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
const reactRefreshWebpackPluginRuntimeEntry = require.re

stPlugin} = require('webpack-manifest-plugin');

function createEnvironmentHash(env) {
  const hash = createHash('md5');
  hash.update(JSON.stringify(env));

  return hash.digest('hex');
}

// Source maps are resource heavy and c


 Since the GitHub API is rate-limited
 * we attempt to save and load the tags in sessionStorage when possible. Since its unlikely
 * that versions will change during a single session this should be safe.
 */

const TAGS_CACHE_KEY = '@react-dom-fixtures/tags';

/**
 * Its possible that users will be testing changes frequently
 * in a browser that does not support sessionStorage. If the API does
 * get rate limited this hardcoded fallback will be loaded instead.
 * This way users can still switch between ~som

  '15.1.0',
  '15.0.2',
  '0.14.8',
  '0.13.0',
].map(version => ({
  name: `v${version}`,
}));

let canUseSessionStorage = true;

try {
  sessionStorage.setItem('foo', '');
} catch (err) {
  canUseSessionStorage = false;
}

/**
 * Attempts to load tags f

e versions while testing.
 * If there's a specific version they need to test that is not here, they
 * can manually load it by editing the URL (`?version={whatever}`)
 */
const fallbackTags = [
  '15.4.2',
  '15.3.2',
  '15.2.1',


0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
var REACT_SUSPENSE_TYPE = 0xead1;
var REACT_SUSPENSE_LIST_TYPE = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_BLOCK_TYPE = 0xead9;
var REACT_SERVER_BLOCK_TYPE = 0xeada;
var REACT_FUNDAMENTAL_TYPE = 0xead5;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY

olFor('react.fragment');
  REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
  REACT_PROFILER_TYPE = symbolFor('react.profiler');
  REACT_PROVIDER_TYPE = symbolFor('react.provider');
  REACT_CONTEXT_TYPE = symbolFor('react.context');
  REACT_FORWARD

_HIDDEN_TYPE = 0xeae3;

if (typeof Symbol === 'function' && Symbol.for) {
  var symbolFor = Symbol.for;
  REACT_ELEMENT_TYPE = symbolFor('react.element');
  REACT_PORTAL_TYPE = symbolFor('react.portal');
  exports.Fragment = symb


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

'use strict';

const babelRegister = require('@babel/register');
babelRegister({
  ignore: [/[\\\/](build|server\/server|node_modules)[\\\/]/],
  presets: [['react-app', {runtime: 'automatic'}]],
  plugins: ['@babel/transform-modules-commonjs'],
});

const express = require('express');
const compress = require('compression');
const {readFileSync} = require('fs');
co

lays');

const PORT = process.env.PORT || 4000;
const app = express();

app.use(compress());
app.get(
  '/',
  handleErrors(async function (req, res) {
    await waitForWebpack();
    renderToStream(req.url, res);
  })
);
app.get(
  '/string',
  handleErro

nst path = require('path');
const renderToString = require('./render-to-string');
const renderToStream = require('./render-to-stream');
const renderToBuffer = require('./render-to-buffer');
const {JS_BUNDLE_DELAY} = require('./de


;

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Ensure environment variables are read.
require('../config/env');

   return true;
  } catch (e) {
    return false;
  }
}

function isInMercurialRepository() {
  try {
    execSync('hg --cwd . root', {stdio: 'ignore'});
    return true;
  } catch (e) {
    return false;
  }
}

// Watch unless on CI or explicitly running

const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);

function isInGitRepository() {
  try {
    execSync('git rev-parse --is-inside-work-tree', {stdio: 'ignore'});


e as getSourceImpl,
  transformSource as reactTransformSource,
} from 'react-server-dom-unbundled/node-loader';

export {resolve};

import babel from '@babel/core';

const babelOptions = {
  babelrc: false,
  ignore: [/\/(build|node_modules)\//],
  plugins: [
    '@babel/plugin-syntax-import-meta',
    ['@babel/plugin-transform-react-jsx', {runtime: 'automatic'}],
  ],
  sourceMaps: process.env.NODE_ENV === 'development' ? 'inline' : false,
};

async function babelLoad(url, context, defaultLoad) {
  const {

result.source, opt);
    if (!newResult) {
      if (typeof result.source === 'string') {
        return result;
      }
      return {
        source: Buffer.from(result.source).toString('utf8'),
        format: 'module',
      };
    }
    return {source

format} = context;
  const result = await defaultLoad(url, context, defaultLoad);
  if (result.format === 'module') {
    const opt = Object.assign({filename: url}, babelOptions);
    const newResult = await babel.transformAsync(


);
const chalk = require('chalk');
const resolve = require('resolve');

/**
 * Get additional module paths based on the baseUrl of a compilerOptions object.
 *
 * @param {Object} options
 */
function getAdditionalModulePaths(options = {}) {
  const baseUrl = options.baseUrl;

  if (!baseUrl) {
    return '';
  }

  const baseUrlResolved = path.resolve(paths.appPath, baseUrl);

  // We don't need to do anything if `baseUrl` is set to `node_modules`. This is
  // the default behavior.
  if (path.relative(path

s equal to the root directory we ignore it here.
  // We don't want to allow importing from the root directly as source files are
  // not transpiled outside of `src`. We do allow importing them with the
  // absolute path (e.g. `src/Components/Button.js`)

s.appNodeModules, baseUrlResolved) === '') {
    return null;
  }

  // Allow the user set the `baseUrl` to `appSrc`.
  if (path.relative(paths.appSrc, baseUrlResolved) === '') {
    return [paths.appSrc];
  }

  // If the path i


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

export default function Html({assets, children, title}) {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="shortcut icon" href="favicon.ico" />
        <link rel="stylesheet" href={assets['main.css']} />
        <title>{title}</title>
      </head>
      <body>
        <noscript

 `<b>Enable JavaScript to run this app.</b>`,
          }}
        />
        {children}
        <script
          dangerouslySetInnerHTML={{
            __html: `assetManifest = ${JSON.stringify(assets)};`,
          }}
        />
      </body>
    </html

      dangerouslySetInnerHTML={{
            __html:


 sed. Aliquam et
        vestibulum eros. Pellentesque mattis efficitur erat. Quisque scelerisque
        sem venenatis eros bibendum porta. Fusce a elit et ante rutrum gravida.
        Sed ex orci, venenatis non elementum id, faucibus et diam. Nullam
        posuere viverra tempus. Duis faucibus metus urna, sit amet bibendum
        lorem fermentum ut. Quisque laoreet ultrices purus.
      </p>
      <p>
        Praesent placerat laoreet augue, eu mollis mi vulputate in. Sed commodo
        est at sapien l

sed hendrerit sem. Nulla facilisi. Sed tempor odio eu
        nisl facilisis, vel porttitor augue auctor. Fusce in ex euismod,
        dignissim diam quis, lacinia purus. Interdum et malesuada fames ac ante
        ipsum primis in faucibus. Integer non nib

aoreet pulvinar. Interdum et malesuada fames ac ante
        ipsum primis in faucibus. Sed libero velit, porttitor vitae lectus sit
        amet, accumsan rhoncus mi. Donec tincidunt purus odio. Aliquam ac
        molestie nisi,


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

'use strict';

const path = require('path');
const rimraf = require('rimraf');
const webpack = require('webpack');

const isProduction = process.env.NODE_ENV === 'production';
rimraf.sync(path.resolve(__dirname, '../build'));
webpack(
  {
    mode: isProduction ? 'production' : 'development',
    devtool: isProduction ? 'source

         test: /\.js$/,
          use: 'babel-loader',
          exclude: /node_modules/,
        },
      ],
    },
  },
  (err, stats) => {
    if (err) {
      console.error(err.stack || err);
      if (err.details) {
        console.error(err.details);

-map' : 'cheap-module-source-map',
    entry: [path.resolve(__dirname, '../src/index.js')],
    output: {
      path: path.resolve(__dirname, '../build'),
      filename: 'main.js',
    },
    module: {
      rules: [
        {


-js/es6/symbol';
import 'core-js/es6/promise';
import 'core-js/es6/set';
import 'core-js/es6/map';

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function () {
  var lastTime = 0;
  var vendors = ['ms', 'moz', 'webkit', 'o'];
  for (var x = 0; x < vendors.length && !window.requestAnimatio

ionFrame'];
  }

  if (!window.requestAnimationFrame)
    window.requestAnimationFrame = function (callback, element) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = window.setTime

nFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimationFrame =
      window[vendors[x] + 'CancelAnimationFrame'] ||
      window[vendors[x] + 'CancelRequestAnimat


w.React;

export default class MediaEvents extends React.Component {
  state = {
    playbackRate: 2,
    events: {
      onCanPlay: false,
      onCanPlayThrough: false,
      onDurationChange: false,
      onEmptied: false,
      onEnded: false,
      onError: false,
      onLoadedData: false,
      onLoadedMetadata: false,
      onLoadStart: false,
      onPause: false,
      onPlay: false,
      onPlaying: false,
      onProgress: false,
      onRateChange: false,
      onResize: false,
      onSeeked:

= el => {
    this.video = el;
  };

  eventDidFire(event) {
    this.setState({
      events: Object.assign({}, this.state.events, {[event]: true}),
    });
  }

  getProgress() {
    const events = Object.keys(this.state.events);
    const total = events

false,
      onSeeking: false,
      onSuspend: false,
      onTimeUpdate: false,
      onVolumeChange: false,
      onWaiting: false,
    },
  };

  updatePlaybackRate = () => {
    this.video.playbackRate = 2;
  };

  setVideo


;
}

declare class MediaList {
  @@iterator(): Iterator<string>;
  mediaText: string;
  length: number;
  item(index: number): ?string;
  deleteMedium(oldMedium: string): void;
  appendMedium(newMedium: string): void;
  [index: number]: string;
}

declare class CSSStyleSheet extends StyleSheet {
  +cssRules: CSSRuleList;
  +ownerRule: ?CSSRule;
  deleteRule(index: number): void;
  insertRule(rule: string, index: number): number;
  replace(text: string): Promise<CSSStyleSheet>;
  replaceSync(text: string): v

 conditionText: string;
}

declare class CSSMediaRule extends CSSConditionRule {
  +media: MediaList;
}

declare class CSSStyleRule extends CSSRule {
  selectorText: string;
  +style: CSSStyleDeclaration;
}

declare class CSSSupportsRule extends CSSConditi

oid;
}

declare class CSSGroupingRule extends CSSRule {
  +cssRules: CSSRuleList;
  deleteRule(index: number): void;
  insertRule(rule: string, index: number): number;
}

declare class CSSConditionRule extends CSSGroupingRule {


entHandler, ...}
  | WheelEventHandler;
type AbortProgressEventHandler = (event: ProgressEvent) => mixed;
type AbortProgressEventListener =
  | {handleEvent: AbortProgressEventHandler, ...}
  | AbortProgressEventHandler;
type ProgressEventHandler = (event: ProgressEvent) => mixed;
type ProgressEventListener =
  | {handleEvent: ProgressEventHandler, ...}
  | ProgressEventHandler;
type DragEventHandler = (event: DragEvent) => mixed;
type DragEventListener =
  | {handleEvent: DragEventHandler, ...}
  | DragEve

type AnimationEventListener =
  | {handleEvent: AnimationEventHandler, ...}
  | AnimationEventHandler;
type ClipboardEventHandler = (event: ClipboardEvent) => mixed;
type ClipboardEventListener =
  | {handleEvent: ClipboardEventHandler, ...}
  | Clipboard

ntHandler;
type PointerEventHandler = (event: PointerEvent) => mixed;
type PointerEventListener =
  | {handleEvent: PointerEventHandler, ...}
  | PointerEventHandler;
type AnimationEventHandler = (event: AnimationEvent) => mixed;


     b: number,
      c: number,
      d: number,
      e: number,
      f: number,
    |}
  | {|
      m11: number,
      m12: number,
      m21: number,
      m22: number,
      m41: number,
      m42: number,
    |};

type DOMMatrixInit =
  | {|
      ...DOMMatrix2DInit,
      is2D: true,
    |}
  | {|
      ...DOMMatrix2DInit,
      is2D: false,
      m13: number,
      m14: number,
      m23: number,
      m24: number,
      m31: number,
      m32: number,
      m33: number,
      m34: number,
      m4

e DOMRectInit = {|
  height: number,
  width: number,
  x: number,
  y: number,
|};

declare class DOMMatrix extends DOMMatrixReadOnly {
  a: number;
  b: number;
  c: number;
  d: number;
  e: number;
  f: number;
  m11: number;
  m12: number;
  m13: numb

3: number,
      m44: number,
    |};

type DOMPointInit = {|
  w: number,
  x: number,
  y: number,
  z: number,
|};

type DOMQuadInit = {|
  p1: DOMPointInit,
  p2: DOMPointInit,
  p3: DOMPointInit,
  p4: DOMPointInit,
|};

typ


@iterator(): Iterator<string>;
  +[key: number]: string;
  +length: number;
  item(number): string | null;
  contains(string): boolean;
}

declare type ElementDefinitionOptions = {|extends?: string|};

declare interface CustomElementRegistry {
  define(
    name: string,
    ctor: Class<Element>,
    options?: ElementDefinitionOptions
  ): void;
  get(name: string): any;
  whenDefined(name: string): Promise<void>;
}

// https://www.w3.org/TR/eventsource/
declare class EventSource extends EventTarget {
  con

 onmessage: MessageEventListener;
  onopen: () => void;
  close: () => void;
}

// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
declare class ErrorEvent extends Event {
  constructor(
    type: string,
    eventInitDict?:

structor(
    url: string,
    configuration?: {withCredentials: boolean, ...}
  ): void;
  +CLOSED: 2;
  +CONNECTING: 0;
  +OPEN: 1;
  +readyState: 0 | 1 | 2;
  +url: string;
  +withCredentials: boolean;
  onerror: () => void;


r$Encoding, start?: number, end?: number): string;
  values(): Iterator<number>;
  write(
    string: string,
    offset?: number,
    length?: number,
    encoding?: buffer$Encoding
  ): number;
  writeDoubleBE(value: number, offset?: number, noAssert?: boolean): number;
  writeDoubleLE(value: number, offset?: number, noAssert?: boolean): number;
  writeFloatBE(value: number, offset?: number, noAssert?: boolean): number;
  writeFloatLE(value: number, offset?: number, noAssert?: boolean): number;
  writeInt

2LE(value: number, offset?: number, noAssert?: boolean): number;
  writeInt8(value: number, offset?: number, noAssert?: boolean): number;
  writeIntBE(
    value: number,
    offset: number,
    byteLength: number,
    noAssert?: boolean
  ): number;
  wri

16BE(value: number, offset?: number, noAssert?: boolean): number;
  writeInt16LE(value: number, offset?: number, noAssert?: boolean): number;
  writeInt32BE(value: number, offset?: number, noAssert?: boolean): number;
  writeInt3


tate = 'hidden' | 'visible' | 'prerender' | 'unloaded';

declare class WindowClient extends Client {
  visibilityState: VisibilityState;
  focused: boolean;
  focus(): Promise<WindowClient>;
  navigate(url: string): Promise<WindowClient>;
}

declare class Client {
  id: string;
  reserved: boolean;
  url: string;
  frameType: FrameType;
  postMessage(message: any, transfer?: Iterator<any> | Array<any>): void;
}

declare class ExtendableEvent extends Event {
  waitUntil(f: Promise<mixed>): void;
}

type Noti

d;
  +notification: Notification;
  +action: string;
}

type ForeignFetchOptions = {
  scopes: Iterator<string>,
  origins: Iterator<string>,
  ...
};

declare class InstallEvent extends ExtendableEvent {
  registerForeignFetch(options: ForeignFetchOptions

ficationEvent$Init = {
  ...Event$Init,
  notification: Notification,
  action?: string,
  ...
};

declare class NotificationEvent extends ExtendableEvent {
  constructor(type: string, eventInitDict?: NotificationEvent$Init): voi


ow_>=v0.261.x

type TextEncodeOptions = {options?: boolean, ...};

declare class ReadableStreamController {
  constructor(
    stream: ReadableStream,
    underlyingSource: UnderlyingSource,
    size: number,
    highWaterMark: number
  ): void;

  desiredSize: number;

  close(): void;
  enqueue(chunk: any): void;
  error(error: Error): void;
}

declare class ReadableStreamBYOBRequest {
  constructor(controller: ReadableStreamController, view: $TypedArray): void;

  view: $TypedArray;

  respond(bytesWritt

    highWaterMark: number
  ): void;

  byobRequest: ReadableStreamBYOBRequest;
}

declare class ReadableStreamReader {
  constructor(stream: ReadableStream): void;

  closed: boolean;

  cancel(reason: string): void;
  read(): Promise<{
    value: ?any,

en: number): ?any;
  respondWithNewView(view: $TypedArray): ?any;
}

declare class ReadableByteStreamController extends ReadableStreamController {
  constructor(
    stream: ReadableStream,
    underlyingSource: UnderlyingSource,


ions/flow_>=v0.261.x

// https://www.w3.org/TR/web-animations-1/

type AnimationPlayState = 'idle' | 'running' | 'paused' | 'finished';

type AnimationReplaceState = 'active' | 'removed' | 'persisted';

type CompositeOperation = 'replace' | 'add' | 'accumulate';

type CompositeOperationOrAuto = 'replace' | 'add' | 'accumulate' | 'auto';

type FillMode = 'none' | 'forwards' | 'backwards' | 'both' | 'auto';

// This is actually web-animations-2
type IterationCompositeOperation = 'replace' | 'accumulate';

typ

edKeyframe = {|
  composite: CompositeOperationOrAuto,
  computedOffset: number,
  easing: string,
  offset: number | null,
|};

type BaseKeyframe = {|
  composite: CompositeOperationOrAuto,
  easing: string,
  offset: number | null,
|};

type BaseProperty

e PlaybackDirection =
  | 'normal'
  | 'reverse'
  | 'alternate'
  | 'alternate-reverse';

type AnimationPlaybackEvent$Init = Event$Init & {
  currentTime?: number | null,
  timelineTime?: number | null,
  ...
};

type BaseComput


d signature: 132e48034ef4756600e1d98681a166b5
// flow-typed version: c6154227d1/error-stack-parser_v2.x.x/flow_>=v0.104.x

declare module 'error-stack-parser' {
  declare interface StackFrame {
    constructor(object: StackFrame): StackFrame;

    isConstructor?: boolean;
    getIsConstructor(): boolean;
    setIsConstructor(): void;

    isEval?: boolean;
    getIsEval(): boolean;
    setIsEval(): void;

    isNative?: boolean;
    getIsNative(): boolean;
    setIsNative(): void;

    isTopLevel?: boolean;

    fileName?: string;
    getFileName(): string;
    setFileName(): void;

    functionName?: string;
    getFunctionName(): string;
    setFunctionName(): void;

    source?: string;
    getSource(): string;
    setSource(): void;

    args?: any[];

    getIsTopLevel(): boolean;
    setIsTopLevel(): void;

    columnNumber?: number;
    getColumnNumber(): number;
    setColumnNumber(): void;

    lineNumber?: number;
    getLineNumber(): number;
    setLineNumber(): void;


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

/**
 * Our philosophy for linting is that lints should be very high-signal:
 * - Error, don't warn. If it's worth mentioning it's worth fixing.
 * - Enable rules that consistently identify real problems. If we frequently would have to
 *   disable the rule due to false positives, it isn't high-signal.
 * - Enable rules that help improve consistent style (to avoid code review about style rather
 *   than substance).
 */

ue
     */
    "prefer-const": "off",

    // Not valuable enough to enable
    "no-useless-escape": "off",

    /*
     * There are valid use cases for loops with constant conditions where the body contains the
     * break
     */
    "no-constant-condit

module.exports = {
  extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
  rules: {
    /*
     * We prefer using const where variables are not reassigned, but occassional mistakes
     * aren't a major iss


;

const fs = require('fs');
const HermesParser = require('hermes-parser');
const BabelParser = require('@babel/parser');
const BabelCore = require('@babel/core');
const invariant = require('invariant');
const {argv, stdin} = require('process');
const prettier = require('prettier');
const {JSXText} = require('hermes-parser/dist/generated/ESTreeVisitorKeys');

function runPlugin(text, file, language) {
  let ast;
  if (language === 'flow') {
    ast = HermesParser.parse(text, {
      babel: true,
      flow:

],
      sourceType: 'module',
    });
  }
  const result = BabelCore.transformFromAstSync(ast, text, {
    ast: false,
    filename: file,
    highlightCode: false,
    retainLines: true,
    plugins: [[AnonymizePlugin]],
    sourceType: 'module',
    con

 'all',
      sourceFilename: file,
      sourceType: 'module',
      enableExperimentalComponentSyntax: true,
    });
  } else {
    ast = BabelParser.parse(text, {
      sourceFilename: file,
      plugins: ['typescript', 'jsx'


const ReactCompiler = require('../packages/babel-plugin-react-compiler/dist');

const combinedRules = [
  {
    name: 'rules-of-hooks',
    recommended: true,
    description:
      'Validates that components and hooks follow the [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks)',
  },
  {
    name: 'exhaustive-deps',
    recommended: true,
    description:
      'Validates that hooks which accept dependency arrays (`useMemo()`, `useCallback()`, `useEffect()`, etc) ' +
      'list all refer

ilter(
    ruleConfig => ruleConfig.rule.recommended && ruleConfig.severity !== 'Off'
  )
  .map(ruleConfig => {
    return `
## \`react-hooks/${ruleConfig.rule.name}\`

${ruleConfig.rule.description}
    `.trim();
  })
  .join('\n\n');

console.log(printe

enced variables in their dependency array. Referencing a value without including it in the ' +
      'dependency array can lead to stale UI or callbacks.',
  },
  ...ReactCompiler.LintRules,
];

const printed = combinedRules
  .f


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

const fs = require('fs');
const glob = require('glob');

const META_COPYRIGHT_COMMENT_BLOCK =
  `/**
 * 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.
 */`.trim() + '\n\n';

const files = glob.sync

 => {
  try {
    const result = processFile(file);
    if (result != null) {
      updatedFiles.set(file, result);
    }
  } catch (e) {
    console.error(e);
    hasErrors = true;
  }
});
if (hasErrors) {
  console.error('Update failed');
  process.exit(

('**/*.{js,ts,tsx,jsx,rs}', {
  ignore: [
    '**/dist/**',
    '**/node_modules/**',
    '**/tests/fixtures/**',
    '**/__tests__/fixtures/**',
  ],
});

const updatedFiles = new Map();
let hasErrors = false;
files.forEach(file


e.
 */

'use strict';

const fs = require('fs');
const path = require('path');
const {execSync} = require('child_process');
const yargs = require('yargs/yargs');
const {hideBin} = require('yargs/helpers');

// Constants
const COMPILER_ROOT = path.resolve(__dirname, '..');
const ENVIRONMENT_TS_PATH = path.join(
  COMPILER_ROOT,
  'packages/babel-plugin-react-compiler/src/HIR/Environment.ts'
);
const FIXTURES_PATH = path.join(
  COMPILER_ROOT,
  'packages/babel-plugin-react-compiler/src/__tests__/fixtures/com

 <flag-name>', 'Enable a feature flag by default', yargs => {
      yargs.positional('flag-name', {
        describe: 'Name of the feature flag to enable',
        type: 'string',
      });
    })
    .example(
      '$0 validateExhaustiveMemoizationDepend

piler'
);
const FIXTURE_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];

/**
 * Parse command line arguments
 */
function parseArgs() {
  const argv = yargs(hideBin(process.argv))
    .usage('Usage: $0 <flag-name>')
    .command('$0


 MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * INSTALLATION:
 *   - `$ npm install octokit
 *   - Get a token from https://github.com/settings/tokens for use in the command below,
 *     set the token value as the GITHUB_AUTH_TOKEN environment variable
 *
 *  USAGE:
 *   - $ GITHUB_AUTH_TOKEN="..." git filter-branch -f --msg-filter "node update-commit-message.js" 2364096862b72cf4d801ef2008c54252335a2df9..HEAD
 */

const {Octokit, App} = require('octokit');
const f

st(
    'GET /repos/{owner}/{repo}/pulls/{pull_number}',
    {
      owner: OWNER,
      repo: REPO,
      pull_number: pullNumber,
      headers: {
        'X-GitHub-Api-Version': '2022-11-28',
      },
    }
  );
  return {body: response.data.body, title

s = require('fs');

const OWNER = 'facebook';
const REPO = 'react-forget';
const octokit = new Octokit({auth: process.env.GITHUB_AUTH_TOKEN});

const fetchPullRequest = async pullNumber => {
  const response = await octokit.reque


e.
 */

'use strict';

const ora = require('ora');
const path = require('path');
const yargs = require('yargs');
const {hashElement} = require('folder-hash');
const promptForOTP = require('./prompt-for-otp');
const {PUBLISHABLE_PACKAGES} = require('./shared/packages');
const {
  execHelper,
  getDateStringForCommit,
  spawnHelper,
} = require('./shared/utils');
const {buildPackages} = require('./shared/build-packages');
const {readJson, writeJson} = require('fs-extra');

/**
 * Script for publishing PUBLISH

d double check the contents of the files that
 * will be pushed to npm.
 *
 * If it looks good, you can run `yarn npm:publish --for-real` to really publish to npm. You must
 * have 2FA enabled first and the script will prompt you to enter a 2FA code before

ABLE_PACKAGES to npm. By default, this runs in tarball mode, meaning
 * the script will only print out what the contents of the files included in the npm tarball would
 * be.
 *
 * Please run this first (ie `yarn npm:publish`) an


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

const cp = require('child_process');
const util = require('util');

function execHelper(command, options, streamStdout = false) {
  return new Promise((resolve, reject) => {
    const proc = cp.exec(command, options, (error, stdout) =>
      error ? reject(error) : resolve(stdout.trim())
    );
    if (streamStdout) {

nst spawnHelper = util.promisify(_spawn);

async function getDateStringForCommit(commit) {
  let dateString = await execHelper(
    `git show -s --no-show-signature --format=%cd --date=format:%Y%m%d ${commit}`
  );

  // On CI environment, this string is w

proc.stdout.pipe(process.stdout);
    }
  });
}

function _spawn(command, args, options, cb) {
  const child = cp.spawn(command, args, options);
  child.on('close', exitCode => {
    cb(null, exitCode);
  });
  return child;
}
co


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

'use strict';

const {tests} = require('./eslint-plugin-react-hooks-test-cases');
const {
  runBabelPluginReactCompiler,
} = require('../dist/Babel/RunReactCompilerBabelPlugin');
const fs = require('fs');
const path = require('path');
const prettier = require('prettier');
const prettierConfigPath = require.resolve('../.prettierrc');
const process = require('process');

ttier.resolveConfig.sync(FIXTURES_DIR, {
  config: prettierConfigPath,
});

const fixtures = [];
for (const test of tests.valid) {
  fixtures.push({code: test.code, valid: true});
}
for (const test of tests.invalid) {
  fixtures.push({code: test.code, vali

const {createHash} = require('crypto');
const {create} = require('domain');

const FIXTURES_DIR = path.join(
  process.cwd(),
  'src',
  '__tests__',
  'fixtures',
  'compiler',
  'rules-of-hooks'
);

const PRETTIER_OPTIONS = pre


     useHook();
        }
      `,
    },
    {
      code: normalizeIndent`
        // Valid because components can use hooks.
        function createComponentWithHook() {
          return function ComponentWithHook() {
            useHook();
          };
        }
      `,
    },
    {
      code: normalizeIndent`
        // Valid because hooks can use hooks.
        function useHookWithHook() {
          useHook();
        }
      `,
    },
    {
      code: normalizeIndent`
        // Valid because hook

n call functions.
        function ComponentWithNormalFunction() {
          doSomething();
        }
      `,
    },
    {
      code: normalizeIndent`
        // Valid because functions can call functions.
        function normalFunctionWithNormalFunctio

s can use hooks.
        function createHook() {
          return function useHookWithHook() {
            useHook();
          }
        }
      `,
    },
    {
      code: normalizeIndent`
        // Valid because components ca


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

module.exports = function makeE2EConfig(displayName, useForget) {
  return {
    displayName,
    testEnvironment: 'jsdom',
    rootDir: '../../src',
    testMatch: ['**/*.e2e.(js|tsx)'],
    modulePathIgnorePatterns: [
      // ignore snapshots from the opposite forget configuration
      useForget ? '.*\\.no-forget\\.sn

est/snapshot-resolver-with-forget.js'
      : '<rootDir>/../scripts/jest/snapshot-resolver-no-forget.js',

    transform: {
      '\\.[tj]sx?$': useForget
        ? '<rootDir>/../scripts/jest/transform-with-forget'
        : '<rootDir>/../scripts/jest/tran

ap$' : '.*\\.with-forget\\.snap$',
      // ignore snapshots from the main project
      '.*\\.ts\\.snap$',
    ],
    globals: {
      __FORGET__: useForget,
    },
    snapshotResolver: useForget
      ? '<rootDir>/../scripts/j


ezeFunctionExpressions:false
import {
  Stringify,
  mutate,
  identity,
  setPropertyByKey,
  shallowCopy,
} from 'shared-runtime';
/**
 * Function expression version of `aliased-nested-scope-truncated-dep`.
 *
 * In this fixture, the output would be invalid if propagateScopeDeps did not
 * avoid adding MemberExpression dependencies which would other evaluate during
 * the mutable ranges of their base objects.
 * This is different from `aliased-nested-scope-truncated-dep` which *does*
 * produce correct ou

ction expression creation until its
 *     earliest potential invocation
 * (2) it's invalid to eagerly evaluate function expression dependencies during
 *     their respective mutable ranges.
 */

function Component({prop}) {
  let obj = shallowCopy(prop)

tput regardless of MemberExpression dependency truncation.
 *
 * Note while other expressions evaluate inline, function expressions *always*
 * represent deferred evaluation. This means that
 * (1) it's always safe to reorder fun


;

/**
 * This fixture is similar to `bug-aliased-capture-aliased-mutate` and
 * `nonmutating-capture-in-unsplittable-memo-block`, but with a focus on
 * dependency extraction.
 *
 * NOTE: this fixture is currently valid, but will break with optimizations:
 * - Scope and mutable-range based reordering may move the array creation
 *     *after* the `mutate(aliasedObj)` call. This is invalid if mutate
 *     reassigns inner properties.
 * - RecycleInto or other deeper-equality optimizations may produce invali

 scope block creation, HIR looks like this:
 *  //
 *  // $1 is unscoped as obj's mutable range will be
 *  // extended in a later pass
 *  //
 *  $1    = LoadLocal obj@0[0:12]
 *  $2    = PropertyLoad $1.id
 *  //
 *  // $3 gets assigned a scope as Array

d
 *     output -- it may compare the array's contents / dependencies too early.
 * - Runtime validation for immutable values will break if `mutate` does
 *     interior mutation of the value captured into the array.
 *
 * Before


tity, makeArray, mutate} from 'shared-runtime';

/**
 * Here, identity('foo') is an immutable allocating instruction.
 * `arr` is a mutable value whose mutable range ends at `arr.map`.
 *
 * The previous (reactive function) version of alignScopesToBlocks set the range of
 * both scopes to end at value blocks within the <></> expression.
 * However, both scope ranges should be aligned to the outer value block
 * (e.g. `cond1 ? <>: null`). The HIR version of alignScopesToBlocks
 * handles this correctly.
 */

ay<any>({a: 2}, 2, []);

  return cond1 ? (
    <>
      <div>{identity('foo')}</div>
      <Stringify value={cond2 ? arr.map(mutate) : null} />
    </>
  ) : null;
}

export const FIXTURE_ENTRYPOINT = {
  fn: Foo,
  params: [{cond1: true, cond2: true}],
}

function Foo({cond1, cond2}) {
  const arr = makeArr


import {useEffect, useState} from 'react';

let someGlobal = {value: null};

function Component() {
  const [state, setState] = useState(someGlobal);

  // NOTE: if we initialize to eg null or a local, then it won't be a definitively global
  // mutation below when we modify `y`. The point of this is example is that if all control
  // flow paths produce a global, we allow the mutation in an effect
  let x = someGlobal;
  while (x == null) {
    x = someGlobal;
  }

  // capture into a separate variable tha

a rule of react violation.
   */
  useEffect(() => {
    y.value = 'hello';
  });

  useEffect(() => {
    setState(someGlobal.value);
  }, [someGlobal]);

  return <div>{String(state)}</div>;
}

export const FIXTURE_ENTRYPOINT = {
  fn: Component,
  param

t is not a context variable.
  const y = x;
  /**
   * Note that this fixture currently produces a stale effect closure if `y = x
   * = someGlobal` changes between renders. Under current compiler assumptions,
   * that would be


alidateRefAccessDuringRender @validateNoSetStateInRender:false
import {useCallback, useEffect, useRef, useState} from 'react';

function Component() {
  const ref = useRef(null);
  const [state, setState] = useState(false);
  const setRef = useCallback(() => {
    ref.current = 'Ok';
  }, []);

  useEffect(() => {
    setRef();
  }, []);

  useEffect(() => {
    setState(true);
  }, []);

  // We use state to force a re-render and observe whether the
  // ref updated. This lets us check that the effect actu

String(state)} ref={ref} />;
}

function Child({ref}) {
  'use no memo';
  // This violates the rules of React, so we access the ref in a child
  // component
  return ref.current;
}

export const FIXTURE_ENTRYPOINT = {
  fn: Component,
  params: [{}],
};

ally ran
  // and wasn't DCE'd
  return <Child key={


ote that this `Array.from` is inferred to be mutating its first
 * argument. This is because React Compiler's typing system does not yet support
 * annotating a function with a set of argument match cases + distinct
 * definitions (polymorphism).
 *
 * In this case, we should be able to infer that the `Array.from` call is
 * not mutating its 0th argument.
 * The 0th argument should be typed as having `effect:Mutate` only when
 * (1) it might be a mutable iterable or
 * (2) the 1st argument might mutate its

 = [{value: 'foo'}, {value: 'bar'}, {value}];
  useIdentity();
  const derived = Array.from(arr, (x, idx) => ({...x, id: idx}));
  return <Stringify>{derived.at(-1)}</Stringify>;
}

export const FIXTURE_ENTRYPOINT = {
  fn: Component,
  params: [{value: 5}

callee
 */
function Component({value}) {
  const arr


m` is inferred to be mutating its first
 * argument. This is because React Compiler's typing system does not yet support
 * annotating a function with a set of argument match cases + distinct
 * definitions (polymorphism)
 *
 * In this case, we should be able to infer that the `Array.from` call is
 * not mutating its 0th argument.
 * The 0th argument should be typed as having `effect:Mutate` only when
 * (1) it might be a mutable iterable or
 * (2) the 1st argument might mutate its callee
 */
function Compo

e: 'bar'}, {value}];
  useIdentity();
  const derived = Array.from(arr);
  return <Stringify>{derived.at(-1)}</Stringify>;
}

export const FIXTURE_ENTRYPOINT = {
  fn: Component,
  params: [{value: 5}],
  sequentialRenders: [{value: 5}, {value: 6}, {value:

nent({value}) {
  const arr = [{value: 'foo'}, {valu


* TODO: object spreads should have conditionally mutate semantics
 *   Found differences in evaluator results
 *   Non-forget (expected):
 *   (kind: ok) [3,1,5,4]
 *   [3,1,5,4]
 *   [4,1,5,4]
 *   Forget:
 *   (kind: ok) [3,1,5,4]
 *   [3,1,5,4]
 *   [4]
 */

function useBar({arg}) {
  'use memo';

  /**
   * Note that mutableIterator is mutated by the later object spread. Therefore,
   * `s.values()` should be memoized within the same block as the object spread.
   * In terms of compiler internals, they

e same reactive scope.
   */
  const s = new Set([1, 5, 4]);
  const mutableIterator = s.values();

  return [arg, ...mutableIterator];
}

export const FIXTURE_ENTRYPOINT = {
  fn: useBar,
  params: [{arg: 3}],
  sequentialRenders: [{arg: 3}, {arg: 3}, {ar


ef, useEffect} from 'react';

/**
 * The postfix increment operator should return the value before incrementing.
 * ```js
 * const id = count.current; // 0
 * count.current = count.current + 1; // 1
 * return id;
 * ```
 * The bug is that we currently increment the value before the expression is evaluated.
 * This bug does not trigger when the incremented value is a plain primitive.
 *
 * Found differences in evaluator results
 * Non-forget (expected):
 * (kind: ok) {"count":{"current":0},"updateCountPostfi

nction params=0 ]]"}
 * logs: ['id = 1','count = 1']
 */
function useFoo() {
  const count = useRef(0);
  const updateCountPostfix = () => {
    const id = count.current++;
    return id;
  };
  const updateCountPrefix = () => {
    const id = ++count.curr

x":"[[ function params=0 ]]","updateCountPrefix":"[[ function params=0 ]]"}
 * logs: ['id = 0','count = 1']
 * Forget:
 * (kind: ok) {"count":{"current":0},"updateCountPostfix":"[[ function params=0 ]]","updateCountPrefix":"[[ fu


false
import {ValidateMemoization} from 'shared-runtime';

const Codes = {
  en: {name: 'English'},
  ja: {name: 'Japanese'},
  ko: {name: 'Korean'},
  zh: {name: 'Chinese'},
};

function Component(a) {
  let keys;
  if (a) {
    keys = Object.keys(Codes);
  } else {
    return null;
  }
  const options = keys.map(code => {
    const country = Codes[code];
    return {
      name: country.name,
      code,
    };
  });
  return (
    <>
      <ValidateMemoization inputs={[]} output={keys} onlyCheckCompiled=

{[]}
        output={options}
        onlyCheckCompiled={true}
      />
    </>
  );
}

export const FIXTURE_ENTRYPOINT = {
  fn: Component,
  params: [{a: false}],
  sequentialRenders: [
    {a: false},
    {a: true},
    {a: true},
    {a: false},
    {a

{true} />
      <ValidateMemoization
        inputs=


ength === 1 && typeof arguments[0] === 'string') {
      str = arguments[0];
    } else {
      str = Array.prototype.map
        .call(arguments, function (arg) {
          return inspect(arg, {
            depth: 10,
          });
        })
        .join(', ');
    }
    const firstArg = arguments[0];
    let logLevel = level;
    if (
      typeof firstArg === 'string' &&
      firstArg.slice(0, 9) === 'Warning: ' &&
      logLevel >= LOG_LEVELS.error
    ) {
      logLevel = LOG_LEVELS.warn;
    }

rLog(
        INSPECTOR_LEVELS[logLevel],
        str,
        [].slice.call(arguments),
        INSPECTOR_FRAMES_TO_SKIP
      );
    }
    if (groupStack.length) {
      str = groupFormat('', str);
    }
    global.nativeLoggingHook(str, logLevel);
  };

if (global.__inspectorLog) {
      global.__inspecto


 `a`
 */
function ComponentA(props) {
  const a_DEBUG = [];
  a_DEBUG.push(props.a);
  if (props.b) {
    return null;
  }
  a_DEBUG.push(props.d);
  return a_DEBUG;
}

/**
 * props.b *does* influence `a`
 */
function ComponentB(props) {
  const a = [];
  a.push(props.a);
  if (props.b) {
    a.push(props.c);
  }
  a.push(props.d);
  return a;
}

/**
 * props.b *does* influence `a`, but only in a way that is never observable
 */
function ComponentC(props) {
  const a = [];
  a.push(props.a);
  if (props.b)

(props.d);
  return a;
}

/**
 * props.b *does* influence `a`
 */
function ComponentD(props) {
  const a = [];
  a.push(props.a);
  if (props.b) {
    a.push(props.c);
    return a;
  }
  a.push(props.d);
  return a;
}

export const FIXTURE_ENTRYPOINT = {

{
    a.push(props.c);
    return null;
  }
  a.push


 TestCase from '../../TestCase';
import Iframe from '../../Iframe';
const React = window.React;

export default class ReorderedInputsTestCase extends React.Component {
  state = {count: 0};

  componentDidMount() {
    this.interval = setInterval(() => {
      this.setState({count: this.state.count + 1});
    }, 2000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  renderInputs() {
    const inputs = [
      <input key={1} defaultValue="Foo" />,
      <input key={2} defaultValue="B

eps>

The two inputs below swap positions every two seconds

Select the text in either of them

Wait for the swap to occur

        </TestCase.Steps>
        <TestCase.ExpectedResult>
          The selec

ar" />,
    ];
    if (this.state.count % 2 === 0) {
      inputs.reverse();
    }
    return inputs;
  }

  render() {
    return (
      <TestCase title="Reordered input elements in iframes" description="">
        <TestCase.St


uttonText: 'Trigger error',
    badChildType: BadRender,
  };
  state = {
    shouldThrow: false,
    didThrow: false,
    error: null,
  };
  componentDidCatch(error) {
    this.setState({error, didThrow: true});
  }
  triggerError = () => {
    this.setState({
      shouldThrow: true,
    });
  };
  render() {
    if (this.state.didThrow) {
      if (this.state.error) {
        return
Captured an error: {this.state.error.message}
;
      } else {
        return
Captured an error: {String(this.sta

ops.buttonText}</button>;
  }
}
class Example extends React.Component {
  state = {key: 0};
  restart = () => {
    this.setState(state => ({key: state.key + 1}));
  };
  render() {
    return (
      <div>
        <button onClick={this.restart}>Reset</but

te.error)}</p>;
      }
    }
    if (this.state.shouldThrow) {
      const BadChild = this.props.badChildType;
      return <BadChild doThrow={this.props.doThrow} />;
    }
    return <button onClick={this.triggerError}>{this.pr


= window.React;

const startDate = new Date();
/**
 * This test case was originally provided by @richsoni,
 * https://github.com/facebook/react/issues/8116
 */
class SwitchDateTestCase extends React.Component {
  state = {
    fullDate: false,
    date: startDate,
  };

  render() {
    const attrs = this.inputAttrs();

    return (

          {attrs.type} input type ({attrs.value})

          <input
            type={attrs.type}
            value={attrs

  />{' '}
            Switch type
          </label>
        </p>
      </div>
    );
  }

  inputAttrs() {
    if (this.state.fullDate) {
      return {
        type: 'datetime-local',
        value: this.state.date.toISOString().replace(/\..*Z/, ''),

.value}
            onChange={this.onInputChange}
          />
          <label>
            <input
              type="checkbox"
              checked={this.state.fullDate}
              onChange={this.updateFullDate}


ixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import PasswordTestCase from './PasswordTestCase';

const React = window.React;

function NumberInputs() {
  return (
    <FixtureSet title="Password inputs">
      <TestCase
        title="The show password icon"
        description={`
          Some browsers have an unmask password icon that React accidentally
          prevents the display of.
        `}
        affectedBrowsers="IE Edge, IE 11">
        <TestCase.Steps>

      </TestCase.Steps>

        <TestCase.ExpectedResult>
          The field should include the "unmasking password" icon.
        </TestCase.ExpectedResult>

        <PasswordTestCase />
      </TestCase>
    </FixtureSet>
  );
}

export default NumberI

Type any string (not an actual password)


st React = window.React;

class RangeInputs extends React.Component {
  state = {value: 0.5};
  onChange = event => {
    this.setState({value: event.target.value});
  };
  render() {
    return (
      <FixtureSet
        title="Range Inputs"
        description="Note: Range inputs are not supported in IE9.">
        <form>
          <fieldset>
            <legend>Controlled</legend>
            <input
              type="range"
              value={this.state.value}
              onChange={this.onChange}

lue: {this.state.value}</span>
          </fieldset>

          <fieldset>
            <legend>Uncontrolled</legend>
            <input type="range" defaultValue={0.5} />
          </fieldset>
        </form>
      </FixtureSet>
    );
  }
}

export defaul

            />
            <span className="hint">Va


../TestCase';

const React = window.React;
const ReactDOM = window.ReactDOM;

const MouseEnter = () => {
  const containerRef = React.useRef();

  React.useEffect(function () {
    const hostEl = containerRef.current;
    ReactDOM.render(<MouseEnterDetect />, hostEl, () => {
      ReactDOM.render(<MouseEnterDetect />, hostEl.childNodes[1]);
    });
  }, []);

  return (
    <TestCase
      title="Mouse Enter"
      description=""
      affectedBrowsers="Chrome, Safari, Firefox">
      <TestCase.Steps>

r noreferrer"
          target="_blank"
          href="https://github.com/facebook/react/issues/16763">
          #16763
        {' '}
        should not happen.

      </TestCase.ExpectedResult>

    </Te

Mouse enter the boxes below, from different borders

      </TestCase.Steps>
      <TestCase.ExpectedResult>
        Mouse enter call count should equal to 1;

        Issue{' '}
        <a
          rel="noopene


ment.getElementById('status');
  var hydrate = document.getElementById('hydrate');
  var reload = document.getElementById('reload');
  var renders = 0;
  var failed = false;

  var needsReactDOM = getBooleanQueryParam('needsReactDOM');
  var needsCreateElement = getBooleanQueryParam('needsCreateElement');

  function unmountComponent(node) {
    // ReactDOM was moved into a separate package in 0.14
    if (needsReactDOM) {
      ReactDOM.unmountComponentAtNode(node);
    } else if (React.unmountComponentAtN

eplaced function invocation in 0.12
    if (needsCreateElement) {
      return React.createElement(value);
    } else {
      return value();
    }
  }

  function getQueryParam(key) {
    var pattern = new RegExp(key + '=([^&]+)(&|$)');
    var matches =

ode) {
      React.unmountComponentAtNode(node);
    } else {
      // Unmounting for React 0.4 and lower
      React.unmountAndReleaseReactRootNode(node);
    }
  }

  function createElement(value) {
    // React.createElement r


: boolean,
  linearAcceleration: null | Float32Array,
  linearVelocity: null | Float32Array,
  orientation: null | Float32Array,
  position: null | Float32Array,
  ...
};
type Gamepad = {
  axes: number[],
  buttons: GamepadButton[],
  connected: boolean,
  displayId?: number,
  hapticActuators?: GamepadHapticActuator[],
  hand?: '' | 'left' | 'right',
  id: string,
  index: number,
  mapping: string,
  pose?: null | GamepadPose,
  timestamp: number,
  ...
};

// deprecated
type BatteryManager = {
  +chargi

onlevelchange: ?(event: any) => mixed,
  ...
};

// https://wicg.github.io/web-share
type ShareData = {
  title?: string,
  text?: string,
  url?: string,
  ...
};

type PermissionName =
  | 'geolocation'
  | 'notifications'
  | 'push'
  | 'midi'
  | 'came

ng: boolean,
  +chargingTime: number,
  +dischargingTime: number,
  +level: number,
  onchargingchange: ?(event: any) => mixed,
  onchargingtimechange: ?(event: any) => mixed,
  ondischargingtimechange: ?(event: any) => mixed,


ss NumberTestCase extends React.Component {
  state = {value: ''};
  onChange = event => {
    const parsed = parseFloat(event.target.value, 10);
    const value = isNaN(parsed) ? '' : parsed;

    this.setState({value});
  };
  render() {
    return (
      <Fixture>

{this.props.children}

          <fieldset>
            <legend>Controlled</legend>
            <input
              type="number"
              value={this.state.value}
              on

pan className="hint">
              {' '}
              Value: {JSON.stringify(this.state.value)}
            </span>
          </fieldset>

          <fieldset>
            <legend>Uncontrolled</legend>
            <input type="number" defaultValue={0.5}

Change={this.onChange}
            />
            <s


./data';
import {CodeEditor, CodeError} from './Code';
import {compile} from './code-transformer';
import {reactPaths} from '../../../react-loader';
import qs from 'query-string';

const React = window.React;
// The Hydration fixture can render at a different version than the parent
// app. This allows rendering for versions of React older than the DOM
// test fixtures can support.
const initialVersion = qs.parse(window.location.search).version || 'local';

class Hydration extends React.Component {
  state

 {
    window.removeEventListener('message', this.handleMessage);
  }

  handleMessage = event => {
    var data = JSON.parse(event.data);

    switch (data.type) {
      case 'ready':
        this.ready = true;
        this.injectCode();
        break;

= {
    error: null,
    code: SAMPLE_CODE,
    hydrate: true,
    version: initialVersion,
  };

  ready = false;

  componentDidMount() {
    window.addEventListener('message', this.handleMessage);
  }

  componentWillUnmount()


ase from '../../TestCase';
import HitBox from './hit-box';

const React = window.React;

class Persistence extends React.Component {
  state = {
    persisted: 0,
    pooled: [],
  };

  addPersisted = event => {
    let {persisted, pooled} = this.state;

    event.persist();

    if (event.type === 'mousemove') {
      this.setState({
        persisted: persisted + 1,
        pooled: pooled.filter(e => e !== event),
      });
    }
  };

  addPooled = event => {
    let {pooled} = this.state;

    if (even

description="">
        <TestCase.Steps>

Mouse over the pooled event box

Mouse over the persisted event box

        </TestCase.Steps>

        <TestCase.ExpectedResult>
          The pool size should not increase abov

t.type === 'mousemove' && pooled.indexOf(event) === -1) {
      this.setState({pooled: pooled.concat(event)});
    }
  };

  render() {
    const {pooled, persisted} = this.state;

    return (
      <TestCase title="Persistence"


re from '../../Fixture';
const React = window.React;

class InputTestCase extends React.Component {
  static defaultProps = {
    type: 'text',
    defaultValue: '',
    parseAs: 'text',
  };

  constructor() {
    super(...arguments);

    this.state = {
      value: this.props.defaultValue,
    };
  }

  onChange = event => {
    const raw = event.target.value;

    switch (this.props.type) {
      case 'number':
        const parsed = parseFloat(event.target.value, 10);

        this.setState({value: isN

Fixture>

{children}

          <fieldset>
            <legend>Controlled {type}</legend>
            <input type={type} value={value} onChange={this.onChange} />

Value

aN(parsed) ? '' : parsed});

        break;
      default:
        this.setState({value: raw});
    }
  };

  render() {
    const {children, type, defaultValue} = this.props;
    const {value} = this.state;

    return (
      <


EmailInput';

const React = window.React;

class TextInputFixtures extends React.Component {
  render() {
    return (
      <FixtureSet
        title="Inputs"
        description="Common behavior across controlled and uncontrolled inputs">
        <TestCase title="Numbers in a controlled text field with no handler">
          <TestCase.Steps>

Move the cursor to after "2" in the text field

Type ".2" into the text input

          </TestCase.Steps>

          <TestCas

 number</legend>
                <input value={2} onChange={() => {}} />
              </fieldset>

              <fieldset>
                <legend>Value as string</legend>
                <input value={'2'} onChange={() => {}} />
              </fieldset

e.ExpectedResult>
            The text field's value should not update.
          </TestCase.ExpectedResult>

          <Fixture>
            <div className="control-box">
              <fieldset>
                <legend>Value as


ase from '../../TestCase';
import HoverBox from './hover-box';

const React = window.React;

class Hover extends React.Component {
  state = {
    overs: 0,
    outs: 0,
    enters: 0,
    leaves: 0,
  };

  onOver = () => this.setState({overs: this.state.overs + 1});
  onOut = () => this.setState({outs: this.state.outs + 1});
  onEnter = () => this.setState({enters: this.state.enters + 1});
  onLeave = () => this.setState({leaves: this.state.leaves + 1});

  render() {
    const {overs, outs, enters, leave

      Overs and outs should increase when moving over the obstacles but
          enters and leaves should not.
        </TestCase.ExpectedResult>

        <HoverBox
          onOver={this.onOver}
          onOut={this.onOut}
          onEnter={this.onEnte

s} = this.state;

    return (
      <TestCase title="Hover" description="">
        <TestCase.Steps>

Hover over the above box and the obstacles

        </TestCase.Steps>

        <TestCase.ExpectedResult>


estCase from '../../TestCase';
import ControlledFormFixture from './ControlledFormFixture';
const React = window.React;

export default class FormStateCases extends React.Component {
  render() {
    return (
      <FixtureSet title="Form State">
        <TestCase
          title="Form state autofills from browser"
          description="Form start should autofill/autocomplete if user has autocomplete/autofill information saved. The user may need to set-up autofill or autocomplete with their specific browse

                  href="https://support.google.com/chrome/answer/142893?co=GENIE.Platform%3DDesktop&hl=en"
                    text="Google Chrome"
                  />
                </li>
                <li>
                  <SafeLink

r.">
          <TestCase.Steps>

              Set up autofill/autocomplete for your browser.

              Instructions:

                  <SafeLink


reSet from '../../FixtureSet';
import TestCase from '../../TestCase';

const React = window.React;

function onButtonClick() {
  window.alert(`This shouldn't have happened!`);
}

export default class ButtonTestCases extends React.Component {
  render() {
    return (
      <FixtureSet title="Buttons">
        <TestCase
          title="onClick with disabled buttons"
          description="The onClick event handler should not be invoked when clicking on a disabled button">
          <TestCase.Steps>

            Click Me
          </button>
        </TestCase>
        <TestCase
          title="onClick with disabled buttons containing other elements"
          description="The onClick event handler should not be invoked when clicking on a disabled butt

Click on the disabled button

          </TestCase.Steps>
          <TestCase.ExpectedResult>
            Nothing should happen
          </TestCase.ExpectedResult>
          <button disabled onClick={onButtonClick}>


ase from '../../TestCase';
import Iframe from '../../Iframe';
const React = window.React;

class OnSelectIframe extends React.Component {
  state = {count: 0, value: 'Select Me!'};

  _onSelect = event => {
    this.setState(({count}) => ({count: count + 1}));
  };

  _onChange = event => {
    this.setState({value: event.target.value});
  };

  render() {
    const {count, value} = this.state;
    return (
      <Iframe height={60}>
        Selection Event Count: {count}
        <input
          type="text

rn (
      <TestCase
        title="onSelect events within iframes"
        description="onSelect events should fire for elements rendered inside iframes">
        <TestCase.Steps>

Highlight some of the text in the input below

"
          onSelect={this._onSelect}
          value={value}
          onChange={this._onChange}
        />
      </Iframe>
    );
  }
}

export default class OnSelectEventTestCase extends React.Component {
  render() {
    retu


;
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import SwitchDateTestCase from './switch-date-test-case';

const React = window.React;

class DateInputFixtures extends React.Component {
  render() {
    return (
      <FixtureSet title="Dates">
        <TestCase title="Switching between date and datetime-local">
          <TestCase.Steps>

Type a date into the date picker

Toggle "Switch type"

          </TestCase.Steps>

, and year values should correctly transfer. The
            hours/minutes/seconds should not be discarded.
          </TestCase.ExpectedResult>

          <Fixture>
            <SwitchDateTestCase />
          </Fixture>
        </TestCase>
      </Fixtur

<TestCase.ExpectedResult>
            The month, day


ort TestCase from '../../TestCase';

const React = window.React;

class MouseMovement extends React.Component {
  state = {
    movement: {x: 0, y: 0},
  };

  onMove = event => {
    this.setState({x: event.movementX, y: event.movementY});
  };

  render() {
    const {x, y} = this.state;

    const boxStyle = {
      padding: '10px 20px',
      border: '1px solid #d9d9d9',
      margin: '10px 0 20px',
    };

    return (
      <TestCase
        title="Mouse Movement"
        description="We polyfill the

es should equal the pixel (integer) difference
          between mouse movements positions.
        </TestCase.ExpectedResult>

Trace your mouse over this box.

movementX and movementY fields."
        affectedBrowsers="IE, Safari">
        <TestCase.Steps>

Mouse over the box below

        </TestCase.Steps>

        <TestCase.ExpectedResult>
          The reported valu