 A');

    // Deferred paint
    await waitForPaint(['Urgent: B, Deferred: B']);
    expect(root).toMatchRenderedOutput('Urgent: B, Deferred: B');
  });

  it('assertLog', async () => {
    const Yield = ({id}) => {
      Scheduler.log(id);
      React.useEffect(() => {
        Scheduler.log(`create effect ${id}`);
        return () => {
          Scheduler.log(`cleanup effect ${id}`);
        };
      });
      return id;
    };

    function App() {
      return (
        <div>
          <Yield id="A" />

trictMode>
      );
    });
    assertLog([
      'A',
      'B',
      'C',
      'create effect A',
      'create effect B',
      'create effect C',
    ]);

    await act(() => {
      root.render(null);
    });

    assertLog(['cleanup effect A', 'cle

          <Yield id="B" />
          <Yield id="C" />
        </div>
      );
    }

    const root = ReactNoop.createRoot();
    await act(() => {
      root.render(
        <React.StrictMode>
          <App />
        </React.S


etModules();
    act = require('internal-test-utils').act;
    simulateEventDispatch =
      require('internal-test-utils').simulateEventDispatch;
    Scheduler = require('scheduler/unstable_mock');
    ReactDOMClient = require('react-dom/client');
    React = require('react');
    assertLog = require('internal-test-utils').assertLog;
  });

  describe('simulateEventDispatch', () => {
    it('should batch discrete capture events', async () => {
      let childRef;
      function Component() {
        const

task');
              });
              setState(1);
              Scheduler.log('onClickCapture parent');
            }}>
            <button
              ref={ref => (childRef = ref)}
              onClickCapture={() => {
                queueMicrotask(

[state, setState] = React.useState(0);
        Scheduler.log(`Render ${state}`);
        return (
          <div
            onClickCapture={() => {
              queueMicrotask(() => {
                Scheduler.log('Parent micro


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

import type {AsyncDispatcher} from 'react-reconciler/src/ReactInternalTypes';
import type {ComponentStackNode} from './ReactFizzComponentStack';

import {currentTaskInDEV} from './ReactFizzCurrentTask';

function getCacheForType<T>(resourceType: () => T): T {
  throw new Error('Not implemented.');
}

function cacheSignal(): null | AbortSigna

 const DefaultAsyncDispatcher: AsyncDispatcher = ({
  getCacheForType,
  cacheSignal,
}: any);

if (__DEV__) {
  DefaultAsyncDispatcher.getOwner = (): ComponentStackNode | null => {
    if (currentTaskInDEV === null) {
      return null;
    }
    return c

l {
  throw new Error('Not implemented.');
}

export


 Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {LazyComponent} from 'react/src/ReactLazy';

// These indirections exists so we can exclude its stack frame in DEV (and anything below it).
// TODO: Consider marking the whole bundle instead of these boundaries.

const callComponent = {
  react_stack_bottom_frame: function <Props, Arg, R>(
    Component: (p: Props, arg:

g,
) => R = __DEV__
  ? // We use this technique to trick minifiers to preserve the function name.
    (callComponent.react_stack_bottom_frame.bind(callComponent): any)
  : (null: any);

interface ClassInstance<R> {
  render(): R;
}

const callRender = {

 Arg) => R,
    props: Props,
    secondArg: Arg,
  ): R {
    return Component(props, secondArg);
  },
};

export const callComponentInDEV: <Props, Arg, R>(
  Component: (p: Props, arg: Arg) => R,
  props: Props,
  secondArg: Ar


et didWarnAboutUninitializedState;
let didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
let didWarnAboutLegacyLifecyclesAndDerivedState;
let didWarnAboutUndefinedDerivedState;
let didWarnAboutDirectlyAssigningPropsToState;
let didWarnAboutContextTypeAndContextTypes;
let didWarnAboutContextTypes;
let didWarnAboutChildContextTypes;
let didWarnAboutInvalidateContextType;
let didWarnOnInvalidCallback;

if (__DEV__) {
  didWarnAboutUninitializedState = new Set<string>();
  didWarnAboutGetSnapshotBeforeUpdate

idWarnAboutContextTypeAndContextTypes = new Set<mixed>();
  didWarnAboutContextTypes = new Set<mixed>();
  didWarnAboutChildContextTypes = new Set<mixed>();
  didWarnAboutInvalidateContextType = new Set<mixed>();
  didWarnOnInvalidCallback = new Set<string

WithoutDidUpdate = new Set<mixed>();
  didWarnAboutLegacyLifecyclesAndDerivedState = new Set<string>();
  didWarnAboutDirectlyAssigningPropsToState = new Set<string>();
  didWarnAboutUndefinedDerivedState = new Set<string>();
  d


import type {ReactComponentInfo, ReactAsyncInfo} from 'shared/ReactTypes';
import type {LazyComponent} from 'react/src/ReactLazy';

import {
  describeBuiltInComponentFrame,
  describeFunctionComponentFrame,
  describeClassComponentFrame,
  describeDebugInfoFrame,
} from 'shared/ReactComponentStackFrame';

import {
  REACT_FORWARD_REF_TYPE,
  REACT_MEMO_TYPE,
  REACT_LAZY_TYPE,
  REACT_SUSPENSE_LIST_TYPE,
  REACT_SUSPENSE_TYPE,
  REACT_VIEW_TRANSITION_TYPE,
} from 'shared/ReactSymbols';

import {enableViewT

    | LazyComponent<any, any>
    | ReactComponentInfo
    | ReactAsyncInfo,
  owner?: null | ReactComponentInfo | ComponentStackNode, // DEV only
  stack?: null | string | Error, // DEV only
};

function shouldConstruct(Component: any) {
  return Compone

ransition} from 'shared/ReactFeatureFlags';

import {formatOwnerStack} from 'shared/ReactOwnerStackFrames';

export type ComponentStackNode = {
  parent: null | ComponentStackNode,
  type:
    | symbol
    | string
    | Function


nable,
  readPreviousThenable,
} from './ReactFizzThenable';

import {
  makeId,
  NotPendingTransition,
  supportsClientAPIs,
} from './ReactFizzConfig';
import {createFastHash} from './ReactServerStreamConfig';

import is from 'shared/objectIs';
import {
  REACT_CONTEXT_TYPE,
  REACT_MEMO_CACHE_SENTINEL,
} from 'shared/ReactSymbols';
import {checkAttributeStringCoercion} from 'shared/CheckStringCoercion';
import {getFormState} from './ReactFizzServer';

import noop from 'shared/noop';

type BasicStateActi

: UpdateQueue<any> | null,
  next: Hook | null,
};

let currentlyRenderingComponent: Object | null = null;
let currentlyRenderingTask: Task | null = null;
let currentlyRenderingRequest: Request | null = null;
let currentlyRenderingKeyPath: KeyNode | null =

on<S> = (S => S) | S;
type Dispatch<A> = A => void;

type Update<A> = {
  action: A,
  next: Update<A> | null,
};

type UpdateQueue<A> = {
  last: Update<A> | null,
  dispatch: any,
};

type Hook = {
  memoizedState: any,
  queue


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

import {disableLegacyContext} from 'shared/ReactFeatureFlags';
import getComponentNameFromType from 'shared/getComponentNameFromType';

let warnedAboutMissingGetChildContext;

if (__DEV__) {
  warnedAboutMissingGetChildContext = ({}: {[string]: boolean});
}

export const emptyContextObject: {} = {};
if (__DEV__) {
  Object.freeze(emptyContextObject);
}

exp

 emptyContextObject;
    }

    const context: {[string]: $FlowFixMe} = {};
    for (const key in contextTypes) {
      context[key] = unmaskedContext[key];
    }

    return context;
  }
}

export function processChildContext(
  instance: any,
  type: any

ort function getMaskedContext(type: any, unmaskedContext: Object): Object {
  if (disableLegacyContext) {
    return emptyContextObject;
  } else {
    const contextTypes = type.contextTypes;
    if (!contextTypes) {
      return


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

'use strict';

let React;
let ReactNoop;
let waitForAll;

// This is a new feature in Fiber so I put it in its own test file. It could
// probably move to one of the other test files once it is official.
describe('ReactTopLevelFragment', function () {
  beforeEach(function () {
    jest.resetModules();
    React = require('react');
    ReactNoop = require('react-noop-r

agment() {
      return [
Hello
,
World
];
    }
    ReactNoop.render(<Fragment />);
    await waitForAll([]);
  });

  it('should preserve state when switching from a single child', async function () {
    let instance =

enderer');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
  });

  it('should render a simple fragment at the top of a component', async function () {
    function Fr


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

import {isPrimaryRenderer} from './ReactFizzConfig';

let rendererSigil;
if (__DEV__) {
  // Use this to detect multiple renderers using the same context
  rendererSigil = {};
}

// Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.
type ContextNode<T> = {
  parent: null | ContextNode<any>,
  depth: number, // Short hand to compute the depth of the tree at this node.
  context: ReactContext<T>,
  pa

ny>;

export const rootContextSnapshot: ContextSnapshot = null;

// We assume that this runtime owns the "current" field on all ReactContext instances.
// This global (actually thread local) state represents what state all those "current",
// fields are cu

rentValue: T,
  value: T,
};

// The structure of a context snapshot is an implementation of this file.
// Currently, it's implemented as tracking the current active node.
export opaque type ContextSnapshot = null | ContextNode<a


this row is not blocked)
  hoistables: HoistableState, // Any dependencies that this row depends on. Future rows need to also depend on it.
  inheritedHoistables: null | HoistableState, // Any dependencies that previous row depend on, that new boundaries of this row needs.
  together: boolean, // All the boundaries within this row must be revealed together.
  next: null | SuspenseListRow, // The next row blocked by this one.
};

const CLIENT_RENDERED = 4; // if it errors or infinitely suspends

type Suspens

ndary blocks from completing.
  completedSegments: Array<Segment>, // completed but not yet flushed segments.
  byteSize: number, // used to determine whether to inline children boundaries.
  defer: boolean, // never inline deferred boundaries
  fallbackAb

eBoundary = {
  status: 0 | 1 | 4 | 5,
  rootSegmentID: number,
  parentFlushed: boolean,
  pendingTasks: number, // when it reaches zero we can show this boundary's content
  row: null | SuspenseListRow, // the row that this bou


e,
  RejectedThenable,
} from 'shared/ReactTypes';
import type {ComponentStackNode} from './ReactFizzComponentStack';

import noop from 'shared/noop';
import {currentTaskInDEV} from './ReactFizzCurrentTask';

export opaque type ThenableState = Array<Thenable<any>>;

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

 lead to ' +
    'unexpected behavior.\n\n' +
    'To handle async errors, wrap your component in an error boundary, or ' +
    "call the promise's `.catch` method and pass the result to `use`.",
);

export function createThenableState(): ThenableState {

It's an implementation " +
    'detail of `use` to interrupt the current render. You must either ' +
    'rethrow it immediately, or move the `use` call outside of the ' +
    '`try/catch` block. Capturing without rethrowing will


e;
let useEffect;
let act;
let waitFor;
let waitForPaint;
let assertLog;

describe('ReactUpdatePriority', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    ContinuousEventPriority =
      require('react-reconciler/constants').ContinuousEventPriority;
    startTransition = React.startTransition;
    useState = React.useState;
    useEffect

unction Text({text}) {
    Scheduler.log(text);
    return text;
  }

  it('setState inside passive effect triggered by sync update should have default priority', async () => {
    const root = ReactNoop.createRoot();

    function App() {
      const [sta

= React.useEffect;

    const InternalTestUtils = require('internal-test-utils');
    waitFor = InternalTestUtils.waitFor;
    waitForPaint = InternalTestUtils.waitForPaint;
    assertLog = InternalTestUtils.assertLog;
  });

  f


, retry immediately without unwinding the stack', async () => {
    let fulfilled = false;
    function Async() {
      if (fulfilled) {
        return <Text text="Async" />;
      }
      Scheduler.log('Suspend!');
      throw Promise.resolve().then(() => {
        Scheduler.log('Resolve in microtask');
        fulfilled = true;
      });
    }

    function App() {
      return (
        <Suspense fallback={<Text text="Loading..." />}>
          <Async />
        </Suspense>
      );
    }

    const root

'Resolve in microtask',

      // Finished rendering without unwinding the stack or preparing a fallback.
      'Async',
    ]);
    expect(root).toMatchRenderedOutput('Async');
  });

  it('if suspended fiber is pinged in a microtask, it does not block a

 = ReactNoop.createRoot();
    await act(() => {
      startTransition(() => {
        root.render(<App />);
      });
    });

    assertLog([
      // React will yield when the async component suspends.
      'Suspend!',


yMode
  it('should not double invoke effects in legacy mode', async () => {
    const log = [];
    function App({text}) {
      React.useEffect(() => {
        log.push('useEffect mount');
        return () => log.push('useEffect unmount');
      });

      React.useLayoutEffect(() => {
        log.push('useLayoutEffect mount');
        return () => log.push('useLayoutEffect unmount');
      });

      return text;
    }

    await act(() => {
      ReactNoop.renderLegacySyncRoot(
        <React.StrictMode

fecycles in legacy mode', async () => {
    const log = [];
    class App extends React.PureComponent {
      componentDidMount() {
        log.push('componentDidMount');
      }

      componentDidUpdate() {
        log.push('componentDidUpdate');
      }

>
          <App text={'mount'} />
        </React.StrictMode>,
      );
    });

    expect(log).toEqual(['useLayoutEffect mount', 'useEffect mount']);
  });

  // @gate !disableLegacyMode
  it('should not double invoke class li


ls.assertLog;
    assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
  });

  function Text(props) {
    Scheduler.log(props.text);
    return <span prop={props.text} />;
  }

  async function fakeImport(result) {
    return {default: result};
  }

  // Tests should run against both the lazy and non-lazy versions of `memo`.
  // To make the tests work for both versions, we wrap the non-lazy version in
  // a lazy function component.
  sharedTests('normal', (...args) => {
    const Memo = React

return React.lazy(() => fakeImport(Memo));
  });

  function sharedTests(label, memo) {
    describe(`${label}`, () => {
      it('bails out on props equality', async () => {
        function Counter({count}) {
          return <Text text={count} />;

.memo(...args);
    function Indirection(props) {
      return <Memo {...props} />;
    }
    return React.lazy(() => fakeImport(Indirection));
  });
  sharedTests('lazy', (...args) => {
    const Memo = React.memo(...args);


 {
    performanceMeasureCalls.length = 0;
    Object.defineProperty(performance, 'measure', {
      value: jest.fn((measureName, reusableOptions) => {
        performanceMeasureCalls.push([
          measureName,
          {
            // React will mutate the options it passes to performance.measure.
            ...reusableOptions,
          },
        ]);
      }),
      configurable: true,
    });
    console.timeStamp = () => {};
    jest.spyOn(console, 'timeStamp').mockImplementation(() => {});

ction getConsoleTimestampEntries() {
    try {
      return console.timeStamp.mock.calls.filter(call => {
        const [, startTime, endTime] = call;

        const isRegisterTrackCall = startTime !== 0.003 && endTime !== 0.003;
        return isRegisterT

jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    useEffect = React.useEffect;
  });

  fun


ct-core
 * @jest-environment node
 */

'use strict';

let React;
let ReactNoopPersistent;

let act;
let waitForAll;

describe('ReactPersistent', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoopPersistent = require('react-noop-renderer/persistent');
    ({act, waitForAll} = require('internal-test-utils'));
  });

  // Inlined from shared folder so we can run this test on a bundle.
  function createPortal(children, containerInfo, implementation, key) {
    ret

ment);
  }

  function div(...children) {
    children = children.map(c =>
      typeof c === 'string' ? {text: c, hidden: false} : c,
    );
    return {type: 'div', children, prop: undefined, hidden: false};
  }

  function span(prop) {
    return {type:

urn {
      $$typeof: Symbol.for('react.portal'),
      key: key == null ? null : String(key),
      children,
      containerInfo,
      implementation,
    };
  }

  function render(element) {
    ReactNoopPersistent.render(ele


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

'use strict';

let React;
let ReactNoop;
let act;

describe('ReactIncrementalUpdatesMinimalism', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactNoop = require('react-noop-renderer');

    act = require('internal-test-utils').act;
  });

  it('should render a simple component', async () => {
    function Child() {
      retu

)).toEqual({
      hostUpdateCounter: 0,
    });

    ReactNoop.startTrackingHostCounters();
    await act(() => ReactNoop.render(<Parent />));
    expect(ReactNoop.stopTrackingHostCounters()).toEqual({
      hostUpdateCounter: 1,
    });
  });

  it('shou

rn
Hello World
;
    }

    function Parent() {
      return <Child />;
    }

    ReactNoop.startTrackingHostCounters();
    await act(() => ReactNoop.render(<Parent />));
    expect(ReactNoop.stopTrackingHostCounters(


 container = document.createElement('div');
      document.body.appendChild(container);
    });

    afterEach(() => {
      document.body.removeChild(container);
      container = null;
    });

    // @gate enableScopeAPI
    it('DO_NOT_USE_queryAllNodes() works as intended', async () => {
      const testScopeQuery = (type, props) => true;
      const TestScope = React.unstable_Scope;
      const scopeRef = React.createRef();
      const divRef = React.createRef();
      const spanRef = React.createRef()

A
          </TestScope>
        ) : (
          <TestScope ref={scopeRef}>
            A

DIV

            SPAN
          </TestScope>
        );
      }

;
      const aRef = React.createRef();

      function Test({toggle}) {
        return toggle ? (
          <TestScope ref={scopeRef}>

DIV

            SPAN


et caches;
let seededCache;
let assertLog;

describe('ReactSuspenseWithNoopRenderer', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    Suspense = React.Suspense;
    useEffect = React.useEffect;

    getCacheForType = React.unstable_getCacheForType;

    const InternalTestUtils = require('internal-test-utils');
    assertLog = InternalTes

fore the initial render (i.e.
      // not a refresh because nothing has mounted yet).
      const cache = seededCache;
      seededCache = null;
      return cache;
    }

    const data = new Map();
    const version = caches.length + 1;
    const cache

tUtils.assertLog;

    caches = [];
    seededCache = null;
  });

  function createTextCache() {
    if (seededCache !== null) {
      // Trick to seed a cache before it exists.
      // TODO: Need a built-in API to seed data be


t}]`);
      const thenable = {
        pings: [],
        then(resolve) {
          if (newRecord.status === 'pending') {
            thenable.pings.push(resolve);
          } else {
            Promise.resolve().then(() => resolve(newRecord.value));
          }
        },
      };

      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.set(text, newRecord);

      throw thenable;
    }
  }

  function Text({text}) {
    Scheduler.log(text);
    return text;

n props.children;
    }

    function Foo({renderBar}) {
      Scheduler.log('Foo');
      return (
        <Suspense fallback={<Text text="Loading..." />}>
          {renderBar ? (
            <Bar>
              <AsyncText text="A" />
              <Text

  }

  function AsyncText({text}) {
    readText(text);
    Scheduler.log(text);
    return text;
  }

  it('suspends rendering and continues later', async () => {
    function Bar(props) {
      Scheduler.log('Bar');
      retur


OM', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
    assertLog = InternalTestUtils.assertLog;

    container = document.createElement('div');
    document.body.appendChild(container);

    f

     const newRecord = {
        status: 'pending',
        value: {default: Component},
        pings: [],
        then(ping) {
          switch (newRecord.status) {
            case 'pending': {
              newRecord.pings.push(ping);
              ret

akeModuleCache = new Map();
  });

  afterEach(() => {
    document.body.removeChild(container);
  });

  async function fakeImport(Component) {
    const record = fakeModuleCache.get(Component);
    if (record === undefined) {


e('ReactSuspenseFuzz', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    Suspense = React.Suspense;
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    Random = require('random-seed');
    ReactFeatureFlags = require('shared/ReactFeatureFlags');
  });

  jest.setTimeout(20000);

  function createFuzzer() {
    const {useState, useContext, useLayoutEffect} = React;

    const ShouldSuspen

dates}) {
      const [step, setStep] = useState(0);

      useLayoutEffect(() => {
        if (updates !== undefined) {
          const cleanUps = new Set();
          updates.forEach(({remountAfter}, i) => {
            const task = {
              label

dContext = React.createContext(true);

    let pendingTasks = new Set();
    let cache = new Map();

    function resetCache() {
      pendingTasks = new Set();
      cache = new Map();
    }

    function Container({children, up


uses the -s suffix in the spelling. ' +
        'Use "forwards" instead.' +
        '\n    in SuspenseList (at **)' +
        '\n    in Foo (at **)',
    ]);
  });

  // @gate enableSuspenseList
  it('warns if a single element is passed to a "forwards" list', async () => {
    function Foo({children}) {
      return (
        <SuspenseList revealOrder="forwards" tail="visible">
          {children}
        </SuspenseList>
      );
    }

    ReactNoop.render(<Foo />);
    // No warning
    await waitForAll(

    <Foo>
          <Suspense fallback="Loading">Child</Suspense>
        </Foo>,
      );
    });
    assertConsoleErrorDev([
      'A single row was passed to a <SuspenseList revealOrder="forwards" />. ' +
        'This is not useful since it needs multi

[]);

    ReactNoop.render(<Foo>{null}</Foo>);
    // No warning
    await waitForAll([]);

    ReactNoop.render(<Foo>{false}</Foo>);
    // No warning
    await waitForAll([]);

    await act(() => {
      ReactNoop.render(


stUtils = require('internal-test-utils');
    act = InternalTestUtils.act;
    assertLog = InternalTestUtils.assertLog;
    waitForPaint = InternalTestUtils.waitForPaint;
  });

  function Text({text}) {
    Scheduler.log(text);
    return text;
  }

  function SuspenseyImage({src}) {
    return (
      <suspensey-thing
        src={src}
        timeout={100}
        onLoadStart={() => Scheduler.log(`Image requested [${src}]`)}
      />
    );
  }

  // @gate enableSuspenseyImages
  it('suspend commit durin

nseyImage src="A" />
          </Suspense>,
        );
      });
    });
    assertLog(['Image requested [A]', 'Loading...']);
    expect(getSuspenseyThingStatus('A')).toBe('pending');
    expect(root).toMatchRenderedOutput('Loading...');

    // This shou

g initial mount', async () => {
    const root = ReactNoop.createRoot();
    await act(async () => {
      startTransition(() => {
        root.render(
          <Suspense fallback={<Text text="Loading..." />}>
            <Suspe


nst data = new Map();
    const version = caches.length + 1;
    const cache = {
      version,
      data,
      resolve(text) {
        const record = data.get(text);
        if (record === undefined) {
          const newRecord = {
            status: 'resolved',
            value: text,
          };
          data.set(text, newRecord);
        } else if (record.status === 'pending') {
          const thenable = record.value;
          record.status = 'resolved';
          record.value = text;

 value: error,
          };
          data.set(text, newRecord);
        } else if (record.status === 'pending') {
          const thenable = record.value;
          record.status = 'rejected';
          record.value = error;
          thenable.pings.forEa

thenable.pings.forEach(t => t());
        }
      },
      reject(text, error) {
        const record = data.get(text);
        if (record === undefined) {
          const newRecord = {
            status: 'rejected',


;
let act;
let waitFor;
let waitForAll;
let assertLog;

describe('updaters', () => {
  beforeEach(() => {
    jest.resetModules();

    allSchedulerTags = [];
    allSchedulerTypes = [];

    onCommitRootShouldYield = true;

    ReactFeatureFlags = require('shared/ReactFeatureFlags');
    ReactFeatureFlags.enableUpdaterTracking = true;

    mockDevToolsHook = {
      injectInternals: jest.fn(() => {}),
      isDevToolsPresent: true,
      onCommitRoot: jest.fn(fiberRoot => {
        if (onCommitRootShouldYi

   schedulerTypes.push(fiber.elementType);
        });
        allSchedulerTags.push(schedulerTags);
        allSchedulerTypes.push(schedulerTypes);
      }),
      onCommitUnmount: jest.fn(() => {}),
      onPostCommitRoot: jest.fn(() => {}),
      onSche

eld) {
          Scheduler.log('onCommitRoot');
        }
        const schedulerTags = [];
        const schedulerTypes = [];
        fiberRoot.memoizedUpdaters.forEach(fiber => {
          schedulerTags.push(fiber.tag);


 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.
 *
 * @emails react-core
 * @jest-environment node
 */

'use strict';

let act;
let ViewTransition;
let React;
let ReactServer;
let ReactNoop;
let ReactNoopFlightClient;
let ReactNoopFlightServer;

describe('ViewTransitionReactServer', () => {
  beforeEach(() => {
    jest.resetModules();
    jest.mock('react', () => require('react/react.react-serv

ire('react');
    ReactNoopFlightClient = require('react-noop-renderer/flight-client');
    ReactNoop = require('react-noop-renderer');
    const InternalTestUtils = require('internal-test-utils');
    act = InternalTestUtils.act;
  });

  afterEach(() =>

er'));
    ReactServer = require('react');
    ViewTransition = ReactServer.ViewTransition;
    ReactNoopFlightServer = require('react-noop-renderer/flight-server');

    jest.resetModules();
    __unmockReact();
    React = requ


 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.
 *
 * @jest-environment node
 */

// sanity tests for act()

const React = require('react');
const ReactNoop = require('react-noop-renderer');
const Scheduler = require('scheduler');
const act = require('internal-test-utils').act;
const {assertLog, waitForAll} = require('internal-test-utils');

// TODO: These tests are no longer specific to the noo

eEffect(props.callback);
      return null;
    }

    const calledLog = [];
    await act(() => {
      ReactNoop.render(
        <App
          callback={() => {
            calledLog.push(calledLog.length);
          }}
        />,
      );
    });

p renderer
// implementation. They test the internal implementation we use in the React
// test suite.
describe('internal act()', () => {
  it('can use act to flush effects', async () => {
    function App(props) {
      React.us


t(

        Hello

,
    );

    ReactNoop.render(<Foo text="World" />);
    await waitForAll([]);
    expect(ReactNoop).toMatchRenderedOutput(

        World
        World

,
    );
  });

  it('can update child nodes of a fragment', async function () {
    function Bar(props) {
      return {props.text};
    }

    function Foo(props) {
      return (

          <Bar text={props.text} />

an prop="test" />

      );
    }

    ReactNoop.render(<Foo text="Hello" />);
    await waitForAll([]);
    expect(ReactNoop).toMatchRenderedOutput(

        Hello

,
    );

{props.text === 'World'
            ? [<Bar key="a" text={props.text} />,
]
            : props.text === 'Hi'
              ? [
, <Bar key="a" text={props.text} />]
              : null}
          <sp


nal-test-utils').act;
    assertLog = require('internal-test-utils').assertLog;
    waitFor = require('internal-test-utils').waitFor;
    waitForPaint = require('internal-test-utils').waitForPaint;
    waitForAll = require('internal-test-utils').waitForAll;
    startTransition = React.startTransition;
    Suspense = React.Suspense;
    Activity = React.Activity;

    textCache = new Map();
  });

  function resolveText(text) {
    const record = textCache.get(text);
    if (record === undefined) {
      con

      record.value = text;
      thenable.pings.forEach(t => t());
    }
  }

  function readText(text) {
    const record = textCache.get(text);
    if (record !== undefined) {
      switch (record.status) {
        case 'pending':
          Scheduler.lo

st newRecord = {
        status: 'resolved',
        value: text,
      };
      textCache.set(text, newRecord);
    } else if (record.status === 'pending') {
      const thenable = record.value;
      record.status = 'resolved';


 case 'resolved':
          return textCache.version;
      }
    } else {
      Scheduler.log(`Suspend:${text}`);

      const thenable = {
        pings: [],
        then(resolve) {
          if (newRecord.status === 'pending') {
            thenable.pings.push(resolve);
          } else {
            Promise.resolve().then(() => resolve(newRecord.value));
          }
        },
      };

      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.data.set(text,

eturn () => {
        Scheduler.log(`Text:${text} destroy insertion`);
      };
    }, []);

    React.useLayoutEffect(() => {
      Scheduler.log(`Text:${text} create layout`);
      return () => {
        Scheduler.log(`Text:${text} destroy layout`);

newRecord);

      throw thenable;
    }
  }

  function Text({children = null, text}) {
    Scheduler.log(`Text:${text} render`);
    React.useInsertionEffect(() => {
      Scheduler.log(`Text:${text} create insertion`);
      r


t.Profiler;
    Suspense = React.Suspense;

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
    assertLog = InternalTestUtils.assertLog;
    act = InternalTestUtils.act;

    TextResource = ReactCache.unstable_createResource(
      ([text, ms = 0]) => {
        let listeners = null;
        let status = 'pending';
        let value = null;
        return {
          then(resolve, reject) {
            switch (status) {
              case 'pending'

rejected [${text}]`);
                      status = 'rejected';
                      value = new Error('Failed to load: ' + text);
                      listeners.forEach(listener => listener.reject(value));
                    } else {

: {
                if (listeners === null) {
                  listeners = [{resolve, reject}];
                  setTimeout(() => {
                    if (textResourceShouldFail) {
                      Scheduler.log(`Promise


pending',
        value: thenable,
      };
      textCache.data.set(text, newRecord);

      throw thenable;
    }
  }

  function Text({text}) {
    Scheduler.log(text);
    return ;
  }

  function AsyncText({text, showVersion}) {
    const version = readText(text);
    const fullText = showVersion ? `${text} [v${version}]` : text;
    Scheduler.log(fullText);
    return ;
  }

  function seedNextTextCache(text) {
    if (seededCache === null) {
      seededCac

ently created cache. An older cache can by
      // resolved with `caches[index].resolve(text)`.
      caches[caches.length - 1].resolve(text);
    }
  }

  const resolveText = resolveMostRecentTextCache;

  function rejectMostRecentTextCache(text, error)

he = createTextCache();
    }
    seededCache.resolve(text);
  }

  function resolveMostRecentTextCache(text) {
    if (caches.length === 0) {
      throw Error('Cache does not exist.');
    } else {
      // Resolve the most rec


   } else {
            Promise.resolve().then(() => resolve(newRecord.value));
          }
        },
      };

      const newRecord = {
        status: 'pending',
        value: thenable,
      };
      textCache.data.set(text, newRecord);

      throw thenable;
    }
  }

  function AsyncText({text}) {
    const fullText = readText(text);
    Scheduler.log(fullText);
    return fullText;
  }

  function Text({text}) {
    Scheduler.log(text);
    return text;
  }

  function resolveMostRecentTextCache(t

hes[caches.length - 1].resolve(text);
    }
  }

  const resolveText = resolveMostRecentTextCache;

  function advanceTimers(ms) {
    // Note: This advances Jest's virtual time but not React's. Use
    // ReactNoop.expire for that.
    if (typeof ms !== '

ext) {
    if (caches.length === 0) {
      throw Error('Cache does not exist');
    } else {
      // Resolve the most recently created cache. An older cache can by
      // resolved with `caches[index].resolve(text)`.
      cac


ct-core
 * @jest-environment node
 */

'use strict';

let React;
let ReactNoop;
let Scheduler;
let waitFor;
let waitForAll;

describe('ReactIncrementalReflection', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');

    const InternalTestUtils = require('internal-test-utils');
    waitFor = InternalTestUtils.waitFor;
    waitForAll = InternalTestUtils.waitForAll;
  });

  function div(...c

an', children: [], prop, hidden: false};
  }

  it('finds no node before insertion and correct node before deletion', async () => {
    let classInstance = null;

    function findInstance(inst) {
      // We ignore warnings fired by findInstance because w

hildren) {
    children = children.map(c =>
      typeof c === 'string' ? {text: c, hidden: false} : c,
    );
    return {type: 'div', children, prop: undefined, hidden: false};
  }

  function span(prop) {
    return {type: 'sp


aitForPaint;
let assertLog;
let waitFor;

describe('ReactSchedulerIntegration', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('internal-test-utils').act;
    NormalPriority = Scheduler.unstable_NormalPriority;
    IdlePriority = Scheduler.unstable_IdlePriority;
    runWithPriority = Scheduler.unstable_runWithPriority;
    startTransition = React.startTransition;

tils.waitFor;
  });

  // Note: This is based on a similar component we use in www. We can delete
  // once the extra div wrapper is no longer necessary.
  function LegacyHiddenDiv({children, mode}) {
    return (
      <div hidden={mode === 'hidden'}>

 const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
    waitForPaint = InternalTestUtils.waitForPaint;
    assertLog = InternalTestUtils.assertLog;
    waitFor = InternalTestU


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.
 *
 * @emails react-core
 * @jest-environment node
 */

'use strict';

let React;
let ReactNoop;
let waitForAll;

// This is a new feature in Fiber so I put it in its own test file. It could
// probably move to one of the other test files once it is official.
describe('ReactTopLevelText', () => {
  beforeEach(() => {
    jest.resetModu

nent returning strings directly from render', async () => {
    const Text = ({value}) => value;
    ReactNoop.render(<Text value="foo" />);
    await waitForAll([]);
    expect(ReactNoop).toMatchRenderedOutput('foo');
  });

  it('should render a componen

les();
    React = require('react');
    ReactNoop = require('react-noop-renderer');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
  });

  it('should render a compo


ayoutEffect mount');
        return () => log.push('useLayoutEffect unmount');
      });

      return text;
    }

    const root = ReactNoop.createLegacyRoot();
    await act(() => {
      root.render(
        <React.StrictMode>
          <App text={'mount'} />
        </React.StrictMode>,
      );
    });

    expect(log).toEqual(['useLayoutEffect mount', 'useEffect mount']);
  });

  it('double invoking for effects works properly', async () => {
    const log = [];
    function App({text}) {
      React

useLayoutEffect unmount');
      });

      return text;
    }

    await act(() => {
      ReactNoop.renderToRootWithID(
        <React.StrictMode>
          <App text={'mount'} />
        </React.StrictMode>,
        'root',
      );
    });

    if (__D

.useEffect(() => {
        log.push('useEffect mount');
        return () => log.push('useEffect unmount');
      });

      React.useLayoutEffect(() => {
        log.push('useLayoutEffect mount');
        return () => log.push('


et React;
let ReactNoop;
let Scheduler;
let Suspense;
let getCacheForType;
let caches;
let seededCache;
let waitForAll;

describe('ReactSuspenseFallback', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    Suspense = React.Suspense;
    getCacheForType = React.unstable_getCacheForType;
    caches = [];
    seededCache = null;

    const InternalTestUtils = require('internal-test-utils'

nitial render (i.e.
      // not a refresh because nothing has mounted yet).
      const cache = seededCache;
      seededCache = null;
      return cache;
    }

    const data = new Map();
    const version = caches.length + 1;
    const cache = {

);
    waitForAll = InternalTestUtils.waitForAll;
  });

  function createTextCache() {
    if (seededCache !== null) {
      // Trick to seed a cache before it exists.
      // TODO: Need a built-in API to seed data before the i


ct-core
 * @jest-environment node
 */
'use strict';

let React;
let ReactNoop;
let waitForAll;
let act;
let assertConsoleErrorDev;

describe('ReactSuspense', () => {
  beforeEach(() => {
    jest.resetModules();

    React = require('react');
    ReactNoop = require('react-noop-renderer');

    const InternalTestUtils = require('internal-test-utils');
    waitForAll = InternalTestUtils.waitForAll;
    act = InternalTestUtils.act;
    assertConsoleErrorDev = InternalTestUtils.assertConsoleErrorDev;
  });

    if (!completed) {
        throw promise;
      }
      return 'Done';
    };
    return {promise, resolve, PromiseComp};
  }

  // Warning don't fire in production, so this test passes in prod even if
  // the suspenseCallback feature is not enabled

function createThenable() {
    let completed = false;
    let resolve;
    const promise = new Promise(res => {
      resolve = () => {
        completed = true;
        res();
      };
    });
    const PromiseComp = () => {


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

import type {ViewTransitionProps, ViewTransitionClass} from 'shared/ReactTypes';
import type {TreeContext} from './ReactFizzTreeContext';
import type {ResumableState} from './ReactFizzConfig';

import {getTreeId} from './ReactFizzTreeContext';
import {makeId} from './ReactFizzConfig';

export function getViewTransitionName(
  props: ViewTransitionProps,
  t

d, 0);
}

function getClassNameByType(classByType: ?ViewTransitionClass): ?string {
  if (classByType == null || typeof classByType === 'string') {
    return classByType;
  }
  let className: ?string = null;
  const activeTypes = null; // TODO: Support pa

reeContext: TreeContext,
  resumableState: ResumableState,
): string {
  if (props.name != null && props.name !== 'auto') {
    return props.name;
  }
  const treeId = getTreeId(treeContext);
  return makeId(resumableState, treeI


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-parcel/src/server/ReactFlightServerConfigParcelBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

export const supportsRequestStorage = false;
export co

> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8'

nst requestStorage: AsyncLocalStorage<Request | void


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-turbopack/src/server/ReactFlightServerConfigTurbopackBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

export const supportsRequestStorage = false;
export const requestStorage: AsyncLocalStorage<Request | void>

ge = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8';
export * from '../ReactServerConsoleConfigBrowser';

 = (null: any);

export const supportsComponentStora


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-webpack/src/server/ReactFlightServerConfigWebpackBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

export const supportsRequestStorage = false;
export

id> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV

const requestStorage: AsyncLocalStorage<Request | vo


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from '../ReactFlightServerConfigBundlerCustom';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

export const supportsRequestStorage = false;
export const requestStorage: AsyncLocalStorage<Reques

nentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8';
export * from '../ReactServerConsoleConfig

t | void> = (null: any);

export const supportsCompo


 Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */
import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-parcel/src/server/ReactFlightServerConfigParcelBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

// For now, we get this fr

? new AsyncLocalStorage() : (null: any);

export const supportsComponentStorage: boolean =
  __DEV__ && supportsRequestStorage;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  supportsComponentStorage ? new AsyncLocalStorage

om the global scope, but this will likely move to a module.
export const supportsRequestStorage = typeof AsyncLocalStorage === 'function';
export const requestStorage: AsyncLocalStorage<Request | void> =
  supportsRequestStorage


 Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */
import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-turbopack/src/server/ReactFlightServerConfigTurbopackBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

// For now, we get t

orage ? new AsyncLocalStorage() : (null: any);

export const supportsComponentStorage: boolean =
  __DEV__ && supportsRequestStorage;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  supportsComponentStorage ? new AsyncLocalS

his from the global scope, but this will likely move to a module.
export const supportsRequestStorage = typeof AsyncLocalStorage === 'function';
export const requestStorage: AsyncLocalStorage<Request | void> =
  supportsRequestSt


 Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-webpack/src/server/ReactFlightServerConfigWebpackBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

// For now, we get this

ge ? new AsyncLocalStorage() : (null: any);

export const supportsComponentStorage: boolean =
  __DEV__ && supportsRequestStorage;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  supportsComponentStorage ? new AsyncLocalStor

 from the global scope, but this will likely move to a module.
export const supportsRequestStorage = typeof AsyncLocalStorage === 'function';
export const requestStorage: AsyncLocalStorage<Request | void> =
  supportsRequestStora


ight (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from '../ReactFlightServerConfigBundlerCustom';

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8';
export * from '../ReactServerConsoleCo

calStorage<Request | void> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export function createHints(): any {
  return null;
}

export type Forma

nfigServer';

export type Hints = any;
export type HintCode = any;
// eslint-disable-next-line no-unused-vars
export type HintModel<T: any> = any;

export const supportsRequestStorage = false;
export const requestStorage: AsyncLo


/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {AsyncLocalStorage} from 'async_hooks';

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-esm/src/server/ReactFlightServerConfigESMBundler';
export * from 'react-dom-bindings/src/server/ReactFl

ntStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  supportsComponentStorage ? new AsyncLocalStorage() : (null: any);

export * from '../ReactFlightServerConfigDebugNode';

export * from '../ReactFlightStackConfigV8';
export * from '../ReactServerC

ightServerConfigDOM';

export const supportsRequestStorage = true;
export const requestStorage: AsyncLocalStorage<Request | void> =
  new AsyncLocalStorage();

export const supportsComponentStorage = __DEV__;
export const compone


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-flight-server-fb/src/server/ReactFlightServerConfigFBBundler';
export * from 'react-flight-server-fb/src/server/ReactFlightServerConfigDOMFB';

export const supportsRequestStorage = false;
export c

d> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8

onst requestStorage: AsyncLocalStorage<Request | voi


/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {AsyncLocalStorage} from 'async_hooks';

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-parcel/src/server/ReactFlightServerConfigParcelBundler';
export * from 'react-dom-bindings/src/server/R

omponentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  supportsComponentStorage ? new AsyncLocalStorage() : (null: any);

export * from '../ReactFlightServerConfigDebugNode';

export * from '../ReactFlightStackConfigV8';
export * from '../ReactS

eactFlightServerConfigDOM';

export const supportsRequestStorage = true;
export const requestStorage: AsyncLocalStorage<Request | void> =
  new AsyncLocalStorage();

export const supportsComponentStorage = __DEV__;
export const c


**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {AsyncLocalStorage} from 'async_hooks';

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-turbopack/src/server/ReactFlightServerConfigTurbopackBundler';
export * from 'react-dom-bindings/src/ser

nst componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  supportsComponentStorage ? new AsyncLocalStorage() : (null: any);

export * from '../ReactFlightServerConfigDebugNode';

export * from '../ReactFlightStackConfigV8';
export * from '../R

ver/ReactFlightServerConfigDOM';

export const supportsRequestStorage = true;
export const requestStorage: AsyncLocalStorage<Request | void> =
  new AsyncLocalStorage();

export const supportsComponentStorage = __DEV__;
export co


**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {AsyncLocalStorage} from 'async_hooks';

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-unbundled/src/server/ReactFlightServerConfigUnbundledBundler';
export * from 'react-dom-bindings/src/ser


/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {AsyncLocalStorage} from 'async_hooks';

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-webpack/src/server/ReactFlightServerConfigWebpackBundler';
export * from 'react-dom-bindings/src/server

 componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  supportsComponentStorage ? new AsyncLocalStorage() : (null: any);

export * from '../ReactFlightServerConfigDebugNode';

export * from '../ReactFlightStackConfigV8';
export * from '../Reac

/ReactFlightServerConfigDOM';

export const supportsRequestStorage = true;
export const requestStorage: AsyncLocalStorage<Request | void> =
  new AsyncLocalStorage();

export const supportsComponentStorage = __DEV__;
export const


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';
import type {ReactClientValue} from 'react-server/src/ReactFlightServer';

export type HintCode = string;
export type HintModel<T: HintCode> = null; // eslint-disable-line no-unused-vars
export type Hints = null;

export function createHints(): Hints {
  return null;
}

export type For

parentContext;
}

export const supportsRequestStorage = false;
export const requestStorage: AsyncLocalStorage<Request | void> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo

matContext = null;

export function createRootFormatContext(): FormatContext {
  return null;
}

export function getChildFormatContext(
  parentContext: FormatContext,
  type: string,
  props: Object,
): FormatContext {
  return


ncLocalStorage<Request | void> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export function createHints(): Hints {
  return null;
}

export type

nfigPlain';

export type Hints = null;
export type HintCode = string;
export type HintModel<T: HintCode> = null; // eslint-disable-line no-unused-vars

export const supportsRequestStorage = false;
export const requestStorage: Asy


 Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

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

ion.

declare const $$$config: any;
export opaque type Destination = mixed;

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

export const scheduleWork = $$$config.scheduleWork;
export

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


ion.

declare const $$$config: $FlowFixMe;
export opaque type Destination = mixed;

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

export const scheduleWork = $$$config.scheduleWork;


 Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {AsyncDispatcher} from 'react-reconciler/src/ReactInternalTypes';

import {resolveRequest, getCache} from '../ReactFlightServer';
import {resolveOwner} from './ReactFlightCurrentOwner';

function resolveCache(): Map<Function, mixed> {
  const request = resolveRequest();
  if (request) {
    return get

Type): any);
    if (entry === undefined) {
      entry = resourceType();
      // TODO: Warn if undefined?
      cache.set(resourceType, entry);
    }
    return entry;
  },
  cacheSignal(): null | AbortSignal {
    const request = resolveRequest();
    i

Cache(request);
  }
  return new Map();
}

export const DefaultAsyncDispatcher: AsyncDispatcher = ({
  getCacheForType<T>(resourceType: () => T): T {
    const cache = resolveCache();
    let entry: T | void = (cache.get(resource


ight (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {AsyncDispatcher} from 'react-reconciler/src/ReactInternalTypes';
import ReactSharedInternals from 'shared/ReactSharedInternals';

export function waitForSuspense<T>(fn: () => T): Promise<T> {
  const cache: Map<Function, mixed> = new Map();
  const testDispatcher: AsyncDispatcher = {
    getCacheForType<R>

      }
      return entry;
    },
    cacheSignal(): null {
      return null;
    },
    getOwner(): null {
      return null;
    },
  };
  // Not using async/await because we don't compile it.
  return new Promise((resolve, reject) => {
    function r

(resourceType: () => R): R {
      let entry: R | void = (cache.get(resourceType): any);
      if (entry === undefined) {
        entry = resourceType();
        // TODO: Warn if undefined?
        cache.set(resourceType, entry);


ing,
  url: string,
};

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

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

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

type Source = string | ArrayBuffer | Uint8Array;

let warnedAboutConditionsFlag = false;

let stashedGetSourc

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

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

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

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


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

const acorn = require('acorn-loose');

const url = require('url');

const Module = require('module');

module.exports = function register() {
  const Server: any = require('react-server-dom-unbundled/server');
  const registerServerReference = Server.registerServerReference;
  const createClientModuleProxy = Server.createClientModuleProxy;

  // $FlowFixMe[prop-missing] found when upgrading Flow
  const ori

heck for the exact string. If it doesn't exist, don't
    // bother parsing.
    if (
      content.indexOf('use client') === -1 &&
      content.indexOf('use server') === -1
    ) {
      return originalCompile.apply(this, arguments);
    }

    let body;

ginalCompile = Module.prototype._compile;

  // $FlowFixMe[prop-missing] found when upgrading Flow
  Module.prototype._compile = function (
    this: any,
    content: string,
    filename: string,
  ): void {
    // Do a quick c


$$location?: Error,
};

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

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

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

export function isServerReference(reference: Object): boolean {
  return reference.$$typeof ==

+ '#' + exportName,
    false,
  );
}

function registerClientReferenceImpl<T>(
  proxyImplementation: any,
  id: string,
  async: boolean,
): ClientReference<T> {
  return Object.defineProperties(proxyImplementation, {
    $$typeof: {value: CLIENT_REFEREN

= SERVER_REFERENCE_TAG;
}

export function registerClientReference<T>(
  proxyImplementation: any,
  id: string,
  exportName: string,
): ClientReference<T> {
  return registerClientReferenceImpl(
    proxyImplementation,
    id


ight (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export type ImportManifestEntry = {
  id: string,
  // chunks is a double indexed array of chunkId / chunkFilename pairs
  chunks: Array<string>,
  name: string,
  async?: boolean,
};

// This is the parsed shape of the wire format which is why it is
// condensed to only the essentialy information
export type ImportMet

ndexed */ Array<string>,
      /* name */ string,
    ];

export const ID = 0;
export const CHUNKS = 1;
export const NAME = 2;
// export const ASYNC = 3;

// This logic is correct because currently only include the 4th tuple member
// when the module is as

adata =
  | [
      /* id */ string,
      /* chunks id/filename pairs, double indexed */ Array<string>,
      /* name */ string,
      /* async */ 1,
    ]
  | [
      /* id */ string,
      /* chunks id/filename pairs, double i


erRequest,
  startWork,
  startFlowing,
  startFlowingDebug,
  stopFlowing,
  abort,
  resolveDebugMessage,
  closeDebugChannel,
} from 'react-server/src/ReactFlightServer';

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

import {
  decodeAction,
  decodeFormState,
} from 'react-server/src/ReactFlightActionServer';

export {
  registerServerRefe

tStreamConfigNode';

import {textEncoder} from 'react-server/src/ReactServerStreamConfigNode';

import type {TemporaryReferenceSet} from 'react-server/src/ReactFlightServerTemporaryReferences';
import type {FileHandle} from 'react-server/src/ReactFlightRep

rence,
  registerClientReference,
  createClientModuleProxy,
} from '../ReactFlightUnbundledReferences';

import {
  createStringDecoder,
  readPartialStringChunk,
  readFinalStringChunk,
} from 'react-client/src/ReactFlightClien


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

import type {ReactClientValue} from 'react-server/src/ReactFlightServer';
import type {
  ImportMetadata,
  ImportManifestEntry,
} from '../shared/ReactFlightImportMetadata';

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

export type {ClientReference, ServerReference};

export type ClientManifest = {
  [id: string]: ClientReferenceManifestEntry,
};

export

e,
  isServerReference,
} from '../ReactFlightUnbundledReferences';

export function getClientReferenceKey(
  reference: ClientReference<any>,
): ClientReferenceKey {
  return reference.$$async ? reference.$$id + '#async' : reference.$$id;
}

export functi

type ServerReferenceId = string;

export type ClientReferenceMetadata = ImportMetadata;
export opaque type ClientReferenceManifestEntry = ImportManifestEntry;

export type ClientReferenceKey = string;

export {
  isClientReferenc


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

import type {ImportMetadata} from '../shared/ReactFlightImportMetadata';
import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig';

import {
  ID,
  CHUNKS,
  NAME,
  isAsyncImport,
} from '../shared/ReactFlightImportMetadata';
import {prepareDestinationWithChunks} from 'react-client/src/ReactFlightClientConfig';

import hasOwnProperty from 'shared/hasOwnProperty';

export type ServerConsumerMo

tadata;

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

// The reason this function needs to defined here in this file instead of just
// being exported direc

duleMap = {
  [clientId: string]: {
    [clientExportName: string]: ClientReference<any>,
  },
};

export type ServerManifest = void;

export type ServerReferenceId = string;

export opaque type ClientReferenceMetadata = ImportMe


* Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

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

export type ModuleLoading = null | {
  prefix: string,
  crossOrigin?: 'use-credentials' | '',
};

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

.]
  chunks: Array<string>,
  nonce: ?string,
) {
  if (moduleLoading !== null) {
    for (let i = 1; i < chunks.length; i += 2) {
      preinitScriptForSSR(
        moduleLoading.prefix + chunks[i],
        nonce,
        moduleLoading.crossOrigin,


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

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

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

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

type ServerConsumerManifest = {
  moduleMap: ServerConsumerModuleMap,
  moduleLoading: ModuleL

Reply,
  createServerReference as createServerReferenceImpl,
} from 'react-client/src/ReactFlightReplyClient';

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

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

oading,
  serverModuleMap: null | ServerManifest,
};

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

import {
  process


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

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

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

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

type ServerConsumerManifest = {
  moduleMap: ServerConsumerModuleMap,
  moduleLoading: Mod

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

export * from './ReactFlightDOMClientEdge';

function noServerCall() {
  throw new Error(
    'Server Functions cannot be called during initial render. ' +
      'This would create a fetch waterfall. Try to us

uleLoading,
  serverModuleMap: null | ServerManifest,
};

import type {Readable} from 'stream';

import {
  createResponse,
  createStreamState,
  getRoot,
  reportGlobalError,
  processStringChunk,
  processBinaryChunk,
  close,


r s;
if (process.env.NODE_ENV === 'production') {
  s = require('./cjs/react-server-dom-unbundled-server.node.production.js');
} else {
  s = require('./cjs/react-server-dom-unbundled-server.node.development.js');
}

exports.renderToReadableStream = s.renderToReadableStream;
exports.renderToPipeableStream = s.renderToPipeableStream;
exports.decodeReply = s.decodeReply;
exports.decodeReplyFromBusboy = s.decodeReplyFromBusboy;
exports.decodeReplyFromAsyncIterable = s.decodeReplyFromAsyncIterable;
exports.deco

 s.decodeFormState;
exports.registerServerReference = s.registerServerReference;
exports.registerClientReference = s.registerClientReference;
exports.createClientModuleProxy = s.createClientModuleProxy;
exports.createTemporaryReferenceSet = s.createTempora

deAction = s.decodeAction;
exports.decodeFormState =


 Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

// Keep in sync with ReactServerConsoleConfig
const badgeFormat = '%c%s%c';
// Same badge styling as DevTools.
const badgeStyle =
  // We use a fixed background if light-dark is not supported, otherwise
  // we use a transparent background.
  'background: #e6e6e6;' +
  'background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25)

 args: Array<any>,
  badgeName: string,
): () => any {
  let offset = 0;
  switch (methodName) {
    case 'dir':
    case 'dirxml':
    case 'groupEnd':
    case 'table': {
      // These methods cannot be colorized because they don't take a formatting str

);' +
  'color: #000000;' +
  'color: light-dark(#000000, #ffffff);' +
  'border-radius: 2px';
const resetStyle = '';
const pad = ' ';

const bind = Function.prototype.bind;

export function bindToConsole(
  methodName: string,


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

import type {
  ReactDebugInfo,
  ReactComponentInfo,
  ReactStackTrace,
} from 'shared/ReactTypes';

export const IO_NODE = 0;
export const PROMISE_NODE = 1;
export const AWAIT_NODE = 2;
export const UNRESOLVED_PROMISE_NODE = 3;
export const UNRESOLVED_AWAIT_NODE = 4;

type PromiseWithDebugInfo = interface extends Promise<any> {
  _debugInfo?: ReactDebugInfo,
};

export type IONode = {
  tag: 0,
  owner: n

here's no promise intermediate.
  promise: null, // not used on I/O
  awaited: null, // I/O is only blocked on external.
  previous: null | AwaitNode | UnresolvedAwaitNode, // the preceeding await that spawned this new work
};

export type PromiseNode = {

ull | ReactComponentInfo,
  stack: null | ReactStackTrace, // callsite that spawned the I/O
  start: number, // start time when the first part of the I/O sequence started
  end: number, // we typically don't use this. only when t


import type {Dispatcher} from 'react-reconciler/src/ReactInternalTypes';
import type {Request} from './ReactFlightServer';
import type {Thenable, Usable, ReactComponentInfo} from 'shared/ReactTypes';
import type {ThenableState} from './ReactFlightThenable';
import {
  REACT_MEMO_CACHE_SENTINEL,
  REACT_CONTEXT_TYPE,
} from 'shared/ReactSymbols';
import {createThenableState, trackUsedThenable} from './ReactFlightThenable';
import {isClientReference} from './ReactFlightServerConfig';

let currentRequest = nul

() {
  currentRequest = null;
}

export function prepareToUseHooksForComponent(
  prevThenableState: ThenableState | null,
  componentDebugInfo: null | ReactComponentInfo,
) {
  thenableIndexCounter = 0;
  thenableState = prevThenableState;
  if (__DEV__)

l;
let thenableIndexCounter = 0;
let thenableState = null;
let currentComponentDebugInfo = null;

export function prepareToUseHooksForRequest(request: Request) {
  currentRequest = request;
}

export function resetHooksForRequest


y: string]: JSONValue}
  | $ReadOnlyArray<JSONValue>;

const PENDING = 'pending';
const BLOCKED = 'blocked';
const RESOLVED_MODEL = 'resolved_model';
const INITIALIZED = 'fulfilled';
const ERRORED = 'rejected';

const __PROTO__ = '__proto__';

type RESPONSE_SYMBOL_TYPE = 'RESPONSE_SYMBOL'; // Fake symbol type.
const RESPONSE_SYMBOL: RESPONSE_SYMBOL_TYPE = (Symbol(): any);

type PendingChunk<T> = {
  status: 'pending',
  value: null | Array<InitializationReference | (T => mixed)>,
  reason: null | Array<Init

ll | Array<InitializationReference | (mixed => mixed)>,
  then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type ResolvedModelChunk<T> = {
  status: 'resolved_model',
  value: string,
  reason: {id: number, [RESPONSE_SYMBOL_TYPE]: Response},

ializationReference | (mixed => mixed)>,
  then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type BlockedChunk<T> = {
  status: 'blocked',
  value: null | Array<InitializationReference | (T => mixed)>,
  reason: nu


umber = callsite[2];
    const columnNumber = callsite[3];
    if (
      filterStackFrame(url, functionName, lineNumber, columnNumber) &&
      // Don't consider anonymous code first party even if the filter wants to include them in the stack.
      url !== ''
    ) {
      if (bestMatch === '') {
        // If we had no good stack frames for internal calls, just use the last
        // first party function name.
        return functionName;
      }
      return bestMatch;
    } else {
      bestMatch = fu

o save bandwidth even in DEV. We'll also replay these stacks on the client so by
  // stripping them early we avoid that overhead. Otherwise we'd normally just rely on
  // the DevTools or framework's ignore lists to filter them out.
  const filterStackFra

nctionName;
    }
  }
  return '';
}

function filterStackTrace(
  request: Request,
  stack: ReactStackTrace,
): ReactStackTrace {
  // Since stacks can be quite large and we pass a lot of them, we filter them out eagerly
  // t


 Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

declare const $$$config: any;

export opaque type ClientManifest = mixed;
export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars
export opaque type ServerReference<T> = mixed; // eslint-disable-line no-unused-vars
export opaque type ClientReferenceMetadata: any = mixed;
export opaque

tClientReferenceKey = $$$config.getClientReferenceKey;
export const resolveClientReferenceMetadata =
  $$$config.resolveClientReferenceMetadata;
export const getServerReferenceId = $$$config.getServerReferenceId;
export const getServerReferenceBoundArgumen

 type ServerReferenceId: any = mixed;
export opaque type ClientReferenceKey: any = mixed;
export const isClientReference = $$$config.isClientReference;
export const isServerReference = $$$config.isServerReference;
export const ge


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

const TEMPORARY_REFERENCE_TAG = Symbol.for('react.temporary.reference');

export opaque type TemporaryReferenceSet = WeakMap<
  TemporaryReference<any>,
  string,
>;

// eslint-disable-next-line no-unused-vars
export interface TemporaryReference<T> {}

export function createTemporaryReferenceSet(): TemporaryReferenceSet {
  return new WeakMap();
}

export function isOpaqueTemporaryReference(reference: Objec

  return temporaryReferences.get(temporaryReference);
}

const proxyHandlers: Proxy$traps<mixed> = {
  get: function (
    target: Function,
    name: string | symbol,
    receiver: Proxy<Function>,
  ) {
    switch (name) {
      // These names are read

t): boolean {
  return reference.$$typeof === TEMPORARY_REFERENCE_TAG;
}

export function resolveTemporaryReference<T>(
  temporaryReferences: TemporaryReferenceSet,
  temporaryReference: TemporaryReference<T>,
): void | string {


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

// Keep in sync with ReactClientConsoleConfig
const badgeFormat = '%c%s%c';
// Same badge styling as DevTools.
const badgeStyle =
  // We use a fixed background if light-dark is not supported, otherwise
  // we use a transparent background.
  'background: #e6e6e6;' +
  'background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));' +
  'color: #000000;'

FlightClient replays inside
// a FlightServer and we capture those replays.
export function unbadgeConsole(
  methodName: string,
  args: Array<any>,
): null | string {
  let offset = 0;
  switch (methodName) {
    case 'dir':
    case 'dirxml':
    case '

+
  'color: light-dark(#000000, #ffffff);' +
  'border-radius: 2px';

const padLength = 1;

// This mutates the args to remove any badges that was added by a FlightClient and
// returns the name in the badge. This is used when a


 Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

// Keep in sync with ReactClientConsoleConfig
const badgeFormat = '[%s]';
const padLength = 1;
const pad = ' ';

// This mutates the args to remove any badges that was added by a FlightClient and
// returns the name in the badge. This is used when a FlightClient replays inside
// a FlightServer and we capture those replays.
export

nnot be colorized because they don't take a formatting string.
      // So we wouldn't have added any badge in the first place.
      // $FlowFixMe
      return null;
    }
    case 'assert': {
      // assert takes formatting options as the second argumen

function unbadgeConsole(
  methodName: string,
  args: Array<any>,
): null | string {
  let offset = 0;
  switch (methodName) {
    case 'dir':
    case 'dirxml':
    case 'groupEnd':
    case 'table': {
      // These methods ca


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

/* global Bun */

import type {Writable} from 'stream';

type BunReadableStreamController = ReadableStreamController & {
  end(): mixed,
  write(data: Chunk | BinaryChunk): void,
  error(error: Error): void,
  flush?: () => void,
};

interface MightBeFlushable {
  flush?: () => void;
}

export type Destination =
  | BunReadableStreamController
  | (Writable & MightBeFlushable);

export type PrecomputedChunk

t function flushBuffered(destination: Destination) {
  // Bun direct streams provide a flush function.
  // If we don't have any more data to send right now.
  // Flush whatever is in the buffer to the wire.
  if (typeof destination.flush === 'function') {

 = string;
export opaque type Chunk = string;
export type BinaryChunk = $ArrayBufferView;

export function scheduleWork(callback: () => void) {
  setTimeout(callback, 0);
}

export const scheduleMicrotask = queueMicrotask;

expor


 Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export type Destination = {
  buffer: string,
  done: boolean,
  fatal: boolean,
  error: mixed,
};

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

export function flushBuffered(destination: Destination) {}

export const supportsRequestStorage = false;
expo

aryChunk,
): void {
  destination.buffer += chunk;
}

export function writeChunkAndReturn(
  destination: Destination,
  chunk: Chunk | PrecomputedChunk | BinaryChunk,
): boolean {
  destination.buffer += chunk;
  return true;
}

export function completeWr

rt const requestStorage: AsyncLocalStorage<Request | void> = (null: any);

export function beginWriting(destination: Destination) {}

export function writeChunk(
  destination: Destination,
  chunk: Chunk | PrecomputedChunk | Bin


* Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {SharedStateServer} from 'react/src/ReactSharedInternalsServer';

import * as React from 'react';

const ReactSharedInternalsServer: SharedStateServer =
  // $FlowFixMe: It's defined in the one we resolve to.
  React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;

if (!ReactSharedIn

 {
  throw new Error(
    'The "react" package in this environment is not configured correctly. ' +
      'The "react-server" condition must be enabled in any environment that ' +
      'runs React Server Components.',
  );
}

export default ReactSharedInt


nents but it should not
      // include that I/O as part of its own meta data.
      return text + ', ' + (await promise);
    }

    const stream = ReactServerDOMServer.renderToPipeableStream(<Component />);

    const readable = new Stream.PassThrough(streamOptions);

    const result = ReactServerDOMClient.createFromNodeStream(readable, {
      moduleMap: {},
      moduleLoading: {},
    });
    stream.pipe(readable);

    expect(await result).toBe('HI, SEB');

    await finishLoadingStream(readable);

            "time": 0,
          },
          {
            "env": "Server",
            "key": null,
            "name": "Component",
            "props": {},
            "stack": [
              [
                "Object.<anonymous>",
                "/

   if (
      __DEV__ &&
      gate(
        flags =>
          flags.enableComponentPerformanceTrack && flags.enableAsyncDebugInfo,
      )
    ) {
      expect(getDebugInfo(result)).toMatchInlineSnapshot(`
        [
          {


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

'use strict';
import {AsyncLocalStorage} from 'node:async_hooks';

let act;
let React;
let ReactNoopServer;

function normalizeCodeLocInfo(str) {
  return (
    str &&
    str.replace(/^ +(?:at|in) ([\S]+)[^\n]*/gm, function (m, name) {
      const dot = name.lastIndexOf('.');
      if (dot !== -1) {
        name = name.slice(dot + 1);
      }
      return '    in ' +

 = str.split('\n');

  // eslint-disable-next-line no-for-of-loops/no-for-of-loops
  for (const line of lines) {
    if (line.indexOf(__filename) === -1) {
    } else {
      ignoreListedStack += '\n' + line.replace(__dirname, '.');
    }
  }

  return ign

name + (/\d/.test(m) ? ' (at **)' : '');
    })
  );
}

/**
 * Removes all stackframes not pointing into this file
 */
function ignoreListStack(str) {
  if (!str) {
    return str;
  }

  let ignoreListedStack = '';
  const lines


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

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

ype {TransitionStatus} from 'react-reconciler/src/ReactFiberConfig';

declare const $$$config: $FlowFixMe;
export opaque type Destination = mixed;
export opaque type RenderState = mixed;
export opaque type HoistableState = mixed;
export opaque type Resumab

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

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


ight (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from '../ReactFlightServerConfigBundlerCustom';

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8';
export * from '../ReactServerConsoleCo

alStorage<Request | void> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export function createHints(): any {
  return null;
}

export type Format

nfigPlain';

export type Hints = any;
export type HintCode = any;
// eslint-disable-next-line no-unused-vars
export type HintModel<T: any> = any;

export const supportsRequestStorage = false;
export const requestStorage: AsyncLoc


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

import type {
  ServerManifest,
  ClientReference as ServerReference,
} from 'react-client/src/ReactFlightClientConfig';

import {
  resolveServerReference,
  preloadModule,
  requireModule,
} from 'react-client/src/ReactFlightClientConfig';

import {
  createResponse,
  close,
  getRoot,
  MAX_BOUND_ARGS,
} from './ReactFlightReplyServer';

type ServerReferenceId = any;

function bindArgs(fn: any, args: any) {
  if (args.length > MAX_BOUND_ARGS) {

rgs));
}

function loadServerReference<T>(
  bundlerConfig: ServerManifest,
  metaData: {
    id: ServerReferenceId,
    bound: null | Promise<Array<any>>,
  },
): Promise<T> {
  const id: ServerReferenceId = metaData.id;
  if (typeof id !== 'string') {

 throw new Error(
      'Server Function has too many bound arguments. Received ' +
        args.length +
        ' but the limit is ' +
        MAX_BOUND_ARGS +
        '.',
    );
  }

  return fn.bind.apply(fn, [null].concat(a


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

import type {LazyComponent} from 'react/src/ReactLazy';

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

import type {ReactClientValue} from './ReactFlightServer';

import {setCurrentOwner} from './flight/ReactFlightCurrentOwner';

// These indirections exists so we can exclude its stack frame in DEV (and anything below it).
// TODO: Consider ma

,
  ): R {
    // The secondArg is always undefined in Server Components since refs error early.
    const secondArg = undefined;
    setCurrentOwner(componentDebugInfo);
    try {
      return Component(props, secondArg);
    } finally {
      setCurrentO

rking the whole bundle instead of these boundaries.

const callComponent = {
  react_stack_bottom_frame: function <Props, R>(
    Component: (p: Props, arg: void) => R,
    props: Props,
    componentDebugInfo: ReactComponentInfo


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

/**
 * Backing FormData is a wrapper around FormData that allows iterating over the
 * keys while allowing to evict values from the FormData without affecting the iteration.
 * Native FormData.keys() will skip keys if entries with Blob are deleted e.g.
 * ```js
 * const formData = new FormData();
 * formData.append('a', new Blob());
 * formData.append('b',

mber,
  // Lazily initialized array of keys. We only need this at the moment
  // for referenced FormData.
  keys: null | Array<string>,
};

export function peekBackingEntry(backingStore: BackingFormData): string | void {
  let keys = backingStore.keys;

2);
 * const keys = formData.keys();
 * keys.next().value; // 'a'
 * formData.delete('a');
 * keys.next().value; // undefined, but we expect 'b'
 * ```
 */
export opaque type BackingFormData = {
  data: FormData,
  keyPointer: nu


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

let framesToSkip: number = 0;
let collectedStackTrace: null | ReactStackTrace = null;

const identifierRegExp = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;

function getMethodCallName(callSite: CallSite): string {
  const typeName = callSite.getTypeName();
  const methodName = callSite.getMethodName();
  const functionName = callSite.getFunctionName();
  let result = '';
  if (functionName) {
    if (
      typeName &&
      identifierRegExp.test(functionName) &&

unctionName.endsWith(' ' + methodName)
    ) {
      result += ' [as ' + methodName + ']';
    }
  } else {
    if (typeName) {
      result += typeName + '.';
    }
    if (methodName) {
      result += methodName;
    } else {
      result += '<anonymous

     functionName !== typeName
    ) {
      result += typeName + '.';
    }
    result += functionName;
    if (
      methodName &&
      functionName !== methodName &&
      !functionName.endsWith('.' + methodName) &&
      !f


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

// Keep in sync with ReactClientConsoleConfig
const badgeFormat = '\x1b[0m\x1b[7m%c%s\x1b[0m%c';
// Same badge styling as DevTools.
const badgeStyle =
  // We use a fixed background if light-dark is not supported, otherwise
  // we use a transparent background.
  'background: #e6e6e6;' +
  'background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));' +

This is used when a FlightClient replays inside
// a FlightServer and we capture those replays.
export function unbadgeConsole(
  methodName: string,
  args: Array<any>,
): null | string {
  let offset = 0;
  switch (methodName) {
    case 'dir':
    case

  'color: #000000;' +
  'color: light-dark(#000000, #ffffff);' +
  'border-radius: 2px';
const padLength = 1;

// This mutates the args to remove any badges that was added by a FlightClient and
// returns the name in the badge.


export type Destination = ReadableStreamController;

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

function handleErrorInNextTick(error: any) {
  setTimeout(() => {
    throw error;
  });
}

const LocalPromise = Promise;

export const scheduleMicrotask: (callback: () => void) => void =
  typeof queueMicrotask === 'function'
    ? queueMicrotask
    : callback => {
        LocalPromise.resolve(null).then(callback).catch(handleErrorInN

// transform streams. https://github.com/whatwg/streams/issues/960
}

// Chunks larger than VIEW_SIZE are written directly, without copying into the
// internal view buffer. This must be at least half of Node's internal Buffer
// pool size (8192) to avoid

extTick);
      };

export function scheduleWork(callback: () => void) {
  setTimeout(callback, 0);
}

export function flushBuffered(destination: Destination) {
  // WHATWG Streams do not yet have a way to flush the underlying


import type {Writable} from 'stream';

import {TextEncoder} from 'util';
import {createHash} from 'crypto';

interface MightBeFlushable {
  flush?: () => void;
}

export type Destination = Writable & MightBeFlushable;

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

export function scheduleWork(callback: () => void) {
  setImmediate(callback);
}

export const scheduleMicrotask = queueMicrotask;

export function flushBuffered(destination: D

n for this purpose.
    // For Express, compression middleware adds this method.
    destination.flush();
  }
}

// Chunks larger than VIEW_SIZE are written directly, without copying into the
// internal view buffer. This must be at least half of Node's in

estination) {
  // If we don't have any more data to send right now.
  // Flush whatever is in the buffer to the wire.
  if (typeof destination.flush === 'function') {
    // By convention the Zlib streams provide a flush functio


ct-core
 * @jest-environment node
 */

'use strict';

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

function normalizeCodeLocInfo(str) {
  return (
    str &&
    str.replace(/^ +(?:at|in) ([\S]+)[^\n]*/gm, function (m, name) {
      const dot = name.lastIndexOf('.');
      if (dot !== -1) {
        name = name.slice(d

ribe('ReactFlight', () => {
  beforeEach(() => {
    // Mock performance.now for timing tests
    let time = 0;
    advanceTimersByTime = timeMS => {
      time += timeMS;
      jest.advanceTimersByTime(timeMS);
    };
    const now = jest.fn().mockImpleme

ot + 1);
      }
      return '    in ' + name + (/\d/.test(m) ? ' (at **)' : '');
    })
  );
}

let ReactServer;
let ReactNoopFlightServer;
let Scheduler;
let advanceTimersByTime;
let assertLog;
let assertConsoleErrorDev;

desc


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-flight-server-fb/src/server/ReactFlightServerConfigFBBundler';
export * from 'react-flight-server-fb/src/server/ReactFlightServerConfigDOMFB';

export const supportsRequestStorage = false;
export c

d> = (null: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8

onst requestStorage: AsyncLocalStorage<Request | voi


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

import type {Request} from 'react-server/src/ReactFlightServer';
import type {ReactComponentInfo} from 'shared/ReactTypes';

export * from 'react-server-dom-esm/src/server/ReactFlightServerConfigESMBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';

export const supportsRequestStorage = false;
export const re

ull: any);

export const supportsComponentStorage = false;
export const componentStorage: AsyncLocalStorage<ReactComponentInfo | void> =
  (null: any);

export * from '../ReactFlightServerConfigDebugNoop';

export * from '../ReactFlightStackConfigV8';
expo

questStorage: AsyncLocalStorage<Request | void> = (n


// Ids are base 32 strings whose binary representation corresponds to the
// position of a node in a tree.

// Every time the tree forks into multiple children, we add additional bits to
// the left of the sequence that represent the position of the child within the
// current level of children.
//
//      00101       00010001011010101
//      ╰─┬─╯       ╰───────┬───────╯
//   Fork 5 of 20       Parent id
//
// The leading 0s are important. In the above example, you only need 3 bits to
// represent slot 5.

a level would be indistinguishable from its parent.
//
// If a node has only one child, and does not materialize an id (i.e. does not
// contain a useId hook), then we don't need to allocate any space in the
// sequence. It's treated as a transparent indir

 However, you need 5 bits to represent all the forks at
// the current level, so we must account for the empty bits at the end.
//
// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
// the zeroth id at


nce';

import {
  IO_NODE,
  PROMISE_NODE,
  UNRESOLVED_PROMISE_NODE,
  AWAIT_NODE,
  UNRESOLVED_AWAIT_NODE,
} from './ReactFlightAsyncSequence';
import {resolveOwner} from './flight/ReactFlightCurrentOwner';
import {resolveRequest, isAwaitInUserspace} from './ReactFlightServer';
import {createHook, executionAsyncId, AsyncResource} from 'async_hooks';
import {enableAsyncDebugInfo} from 'shared/ReactFeatureFlags';
import {parseStackTracePrivate} from './ReactFlightServerConfig';

// $FlowFixMe[method-unbindi

c functions missing data.
let lastRanAwait: null | AwaitNode = null;

function resolvePromiseOrAwaitNode(
  unresolvedNode: UnresolvedAwaitNode | UnresolvedPromiseNode,
  endTime: number,
): AwaitNode | PromiseNode {
  const resolvedNode: AwaitNode | Promi

ng]
const getAsyncId = AsyncResource.prototype.asyncId;

const pendingOperations: Map<number, AsyncSequence> =
  __DEV__ && enableAsyncDebugInfo ? new Map() : (null: any);

// Keep the last resolved await as a workaround for asyn


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

// A pure JS implementation of a string hashing function. We do not use it for
// security or obfuscation purposes, only to create compact hashes. So we
// prioritize speed over collision avoidance. For example, we use this to hash
// the component key path used by useActionState for MPA-style submissions.
//
// In environments where built-in hashing functions are available, we prefer
// those instead. Like

o high to be worth it.
//
// The most popular hashing algorithm that meets these requirements in the JS
// ecosystem is MurmurHash3, and almost all implementations I could find used
// some version of the implementation by Gary Court inlined below.

export

 Node's crypto module, or Bun.hash. Unfortunately this
// does not include the web standard crypto API because those methods are all
// async. For our purposes, we need it to be sync because the cost of context
// switching is to


ype {TransitionStatus} from 'react-reconciler/src/ReactFiberConfig';

declare const $$$config: any;
export opaque type Destination = mixed;
export opaque type RenderState = mixed;
export opaque type HoistableState = mixed;
export opaque type ResumableState