repo_name
stringlengths
4
68
text
stringlengths
21
269k
avg_line_length
float64
9.4
9.51k
max_line_length
int64
20
28.5k
alphnanum_fraction
float64
0.3
0.92
cybersecurity-penetration-testing
/** @flow */ // This test harness mounts each test app as a separate root to test multi-root applications. import {createElement} from 'react'; import {createRoot} from 'react-dom/client'; import {render, unmountComponentAtNode} from 'react-dom'; import DeeplyNestedComponents from './DeeplyNestedComponents'; import Iframe from './Iframe'; import EditableProps from './EditableProps'; import ElementTypes from './ElementTypes'; import Hydration from './Hydration'; import InspectableElements from './InspectableElements'; import ReactNativeWeb from './ReactNativeWeb'; import ToDoList from './ToDoList'; import Toggle from './Toggle'; import ErrorBoundaries from './ErrorBoundaries'; import PartiallyStrictApp from './PartiallyStrictApp'; import SuspenseTree from './SuspenseTree'; import {ignoreErrors, ignoreLogs, ignoreWarnings} from './console'; import './styles.css'; // DevTools intentionally tests compatibility with certain legacy APIs. // Suppress their error messages in the local dev shell, // because they might mask other more serious error messages. ignoreErrors([ 'Warning: Legacy context API', 'Warning: Unsafe lifecycle methods', 'Warning: %s is deprecated in StrictMode.', // findDOMNode 'Warning: ReactDOM.render is no longer supported in React 18', ]); ignoreWarnings(['Warning: componentWillReceiveProps has been renamed']); ignoreLogs([]); const unmountFunctions: Array<() => void | boolean> = []; function createContainer() { const container = document.createElement('div'); ((document.body: any): HTMLBodyElement).appendChild(container); return container; } function mountApp(App: () => React$Node) { const container = createContainer(); const root = createRoot(container); root.render(createElement(App)); unmountFunctions.push(() => root.unmount()); } // $FlowFixMe[missing-local-annot] function mountStrictApp(App) { function StrictRoot() { return createElement(App); } const container = createContainer(); const root = createRoot(container, {unstable_strictMode: true}); root.render(createElement(StrictRoot)); unmountFunctions.push(() => root.unmount()); } function mountLegacyApp(App: () => React$Node) { function LegacyRender() { return createElement(App); } const container = createContainer(); render(createElement(LegacyRender), container); unmountFunctions.push(() => unmountComponentAtNode(container)); } function mountTestApp() { mountStrictApp(ToDoList); mountApp(InspectableElements); mountApp(Hydration); mountApp(ElementTypes); mountApp(EditableProps); mountApp(ReactNativeWeb); mountApp(Toggle); mountApp(ErrorBoundaries); mountApp(SuspenseTree); mountApp(DeeplyNestedComponents); mountApp(Iframe); mountLegacyApp(PartiallyStrictApp); } function unmountTestApp() { unmountFunctions.forEach(fn => fn()); } mountTestApp(); window.parent.mountTestApp = mountTestApp; window.parent.unmountTestApp = unmountTestApp;
27.423077
93
0.749577
Python-Penetration-Testing-Cookbook
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export {Component as ComponentUsingHooksIndirectly} from './ComponentUsingHooksIndirectly'; export {Component as ComponentWithCustomHook} from './ComponentWithCustomHook'; export {Component as ComponentWithExternalCustomHooks} from './ComponentWithExternalCustomHooks'; export {Component as ComponentWithMultipleHooksPerLine} from './ComponentWithMultipleHooksPerLine'; export {Component as ComponentWithNestedHooks} from './ComponentWithNestedHooks'; export {Component as ContainingStringSourceMappingURL} from './ContainingStringSourceMappingURL'; export {Component as Example} from './Example'; export {Component as InlineRequire} from './InlineRequire'; import * as ToDoList from './ToDoList'; export {ToDoList}; export {default as useTheme} from './useTheme';
45.190476
99
0.795666
cybersecurity-penetration-testing
/** * 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. */ // List derived from Gecko source code: // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js export const shorthandToLonghand = { animation: [ 'animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction', ], background: [ 'backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize', ], backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'], border: [ 'borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth', ], borderBlockEnd: [ 'borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth', ], borderBlockStart: [ 'borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth', ], borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'], borderColor: [ 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', ], borderImage: [ 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', ], borderInlineEnd: [ 'borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth', ], borderInlineStart: [ 'borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth', ], borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'], borderRadius: [ 'borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius', ], borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'], borderStyle: [ 'borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle', ], borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'], borderWidth: [ 'borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth', ], columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'], columns: ['columnCount', 'columnWidth'], flex: ['flexBasis', 'flexGrow', 'flexShrink'], flexFlow: ['flexDirection', 'flexWrap'], font: [ 'fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight', ], fontVariant: [ 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', ], gap: ['columnGap', 'rowGap'], grid: [ 'gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows', ], gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'], gridColumn: ['gridColumnEnd', 'gridColumnStart'], gridColumnGap: ['columnGap'], gridGap: ['columnGap', 'rowGap'], gridRow: ['gridRowEnd', 'gridRowStart'], gridRowGap: ['rowGap'], gridTemplate: [ 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows', ], listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'], margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'], marker: ['markerEnd', 'markerMid', 'markerStart'], mask: [ 'maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize', ], maskPosition: ['maskPositionX', 'maskPositionY'], outline: ['outlineColor', 'outlineStyle', 'outlineWidth'], overflow: ['overflowX', 'overflowY'], padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'], placeContent: ['alignContent', 'justifyContent'], placeItems: ['alignItems', 'justifyItems'], placeSelf: ['alignSelf', 'justifySelf'], textDecoration: [ 'textDecorationColor', 'textDecorationLine', 'textDecorationStyle', ], textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'], transition: [ 'transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction', ], wordWrap: ['overflowWrap'], };
25.502591
94
0.674619
Python-Penetration-Testing-Cookbook
"use strict"; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const { useMemo, useState } = require('react'); function Component(props) { const InnerComponent = useMemo(() => () => { const [state] = useState(0); return state; }); props.callback(InnerComponent); return null; } module.exports = { Component }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhOZXN0ZWRIb29rcy5qcyJdLCJuYW1lcyI6WyJ1c2VNZW1vIiwidXNlU3RhdGUiLCJyZXF1aXJlIiwiQ29tcG9uZW50IiwicHJvcHMiLCJJbm5lckNvbXBvbmVudCIsInN0YXRlIiwiY2FsbGJhY2siLCJtb2R1bGUiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOztBQUFBOzs7Ozs7OztBQVFBLE1BQUE7QUFBQUEsRUFBQUEsT0FBQTtBQUFBQyxFQUFBQTtBQUFBLElBQUFDLE9BQUEsQ0FBQSxPQUFBLENBQUE7O0FBRUEsU0FBQUMsU0FBQSxDQUFBQyxLQUFBLEVBQUE7QUFDQSxRQUFBQyxjQUFBLEdBQUFMLE9BQUEsQ0FBQSxNQUFBLE1BQUE7QUFDQSxVQUFBLENBQUFNLEtBQUEsSUFBQUwsUUFBQSxDQUFBLENBQUEsQ0FBQTtBQUVBLFdBQUFLLEtBQUE7QUFDQSxHQUpBLENBQUE7QUFLQUYsRUFBQUEsS0FBQSxDQUFBRyxRQUFBLENBQUFGLGNBQUE7QUFFQSxTQUFBLElBQUE7QUFDQTs7QUFFQUcsTUFBQSxDQUFBQyxPQUFBLEdBQUE7QUFBQU4sRUFBQUE7QUFBQSxDQUFBIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5jb25zdCB7dXNlTWVtbywgdXNlU3RhdGV9ID0gcmVxdWlyZSgncmVhY3QnKTtcblxuZnVuY3Rpb24gQ29tcG9uZW50KHByb3BzKSB7XG4gIGNvbnN0IElubmVyQ29tcG9uZW50ID0gdXNlTWVtbygoKSA9PiAoKSA9PiB7XG4gICAgY29uc3QgW3N0YXRlXSA9IHVzZVN0YXRlKDApO1xuXG4gICAgcmV0dXJuIHN0YXRlO1xuICB9KTtcbiAgcHJvcHMuY2FsbGJhY2soSW5uZXJDb21wb25lbnQpO1xuXG4gIHJldHVybiBudWxsO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHtDb21wb25lbnR9O1xuIl19
68.035714
1,448
0.905797
owtf
import { resolve, load as reactLoad, getSource as getSourceImpl, transformSource as reactTransformSource, } from 'react-server-dom-esm/node-loader'; export {resolve}; async function textLoad(url, context, defaultLoad) { const {format} = context; const result = await defaultLoad(url, context, defaultLoad); if (result.format === 'module') { if (typeof result.source === 'string') { return result; } return { source: Buffer.from(result.source).toString('utf8'), format: 'module', }; } return result; } export async function load(url, context, defaultLoad) { return await reactLoad(url, context, (u, c) => { return textLoad(u, c, defaultLoad); }); } async function textTransformSource(source, context, defaultTransformSource) { const {format} = context; if (format === 'module') { if (typeof source === 'string') { return {source}; } return { source: Buffer.from(source).toString('utf8'), }; } return defaultTransformSource(source, context, defaultTransformSource); } async function transformSourceImpl(source, context, defaultTransformSource) { return await reactTransformSource(source, context, (s, c) => { return textTransformSource(s, c, defaultTransformSource); }); } export const transformSource = process.version < 'v16' ? transformSourceImpl : undefined; export const getSource = process.version < 'v16' ? getSourceImpl : undefined;
26.396226
77
0.687802
null
/** * 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 {useSyncExternalStore as client} from './useSyncExternalStoreShimClient'; import {useSyncExternalStore as server} from './useSyncExternalStoreShimServer'; import {isServerEnvironment} from './isServerEnvironment'; import {useSyncExternalStore as builtInAPI} from 'react'; const shim = isServerEnvironment ? server : client; export const useSyncExternalStore: <T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ) => T = builtInAPI !== undefined ? builtInAPI : shim;
32.136364
80
0.71978
owtf
import TestCase from '../../TestCase'; import HoverBox from './hover-box'; const React = window.React; class Hover extends React.Component { state = { overs: 0, outs: 0, enters: 0, leaves: 0, }; onOver = () => this.setState({overs: this.state.overs + 1}); onOut = () => this.setState({outs: this.state.outs + 1}); onEnter = () => this.setState({enters: this.state.enters + 1}); onLeave = () => this.setState({leaves: this.state.leaves + 1}); render() { const {overs, outs, enters, leaves} = this.state; return ( <TestCase title="Hover" description=""> <TestCase.Steps> <li>Hover over the above box and the obstacles</li> </TestCase.Steps> <TestCase.ExpectedResult> Overs and outs should increase when moving over the obstacles but enters and leaves should not. </TestCase.ExpectedResult> <HoverBox onOver={this.onOver} onOut={this.onOut} onEnter={this.onEnter} onLeave={this.onLeave} /> <p> Pointer Overs: <b>{overs}</b> <br /> Pointer Outs: <b>{outs}</b> <br /> Pointer Enters: <b>{enters}</b> <br /> Pointer Leaves: <b>{leaves}</b> <br /> </p> </TestCase> ); } } export default Hover;
24.519231
75
0.558824
PenetrationTestingScripts
'use strict'; /** @flow */ const semver = require('semver'); const config = require('../../playwright.config'); const {test} = require('@playwright/test'); function runOnlyForReactRange(range) { test.skip( !semver.satisfies(config.use.react_version, range), `This test requires a React version of ${range} to run. ` + `The React version you're using is ${config.use.react_version}` ); } module.exports = {runOnlyForReactRange};
24.055556
69
0.677778
null
/** * 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. * * @emails react-core */ // This test doesn't really have a good home yet. I'm leaving it here since this // behavior belongs to the old propTypes system yet is currently implemented // in the core ReactCompositeComponent. It should technically live in core's // test suite but I'll leave it here to indicate that this is an issue that // needs to be fixed. 'use strict'; let PropTypes; let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; describe('ReactContextValidator', () => { beforeEach(() => { jest.resetModules(); PropTypes = require('prop-types'); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); }); // TODO: This behavior creates a runtime dependency on propTypes. We should // ensure that this is not required for ES6 classes with Flow. // @gate !disableLegacyContext it('should filter out context not in contextTypes', () => { class Component extends React.Component { render() { return <div />; } } Component.contextTypes = { foo: PropTypes.string, }; class ComponentInFooBarContext extends React.Component { childRef = React.createRef(); getChildContext() { return { foo: 'abc', bar: 123, }; } render() { return <Component ref={this.childRef} />; } } ComponentInFooBarContext.childContextTypes = { foo: PropTypes.string, bar: PropTypes.number, }; const instance = ReactTestUtils.renderIntoDocument( <ComponentInFooBarContext />, ); expect(instance.childRef.current.context).toEqual({foo: 'abc'}); }); // @gate !disableLegacyContext it('should pass next context to lifecycles', () => { let componentDidMountContext; let componentDidUpdateContext; let componentWillReceivePropsContext; let componentWillReceivePropsNextContext; let componentWillUpdateContext; let componentWillUpdateNextContext; let constructorContext; let renderContext; let shouldComponentUpdateContext; let shouldComponentUpdateNextContext; class Parent extends React.Component { getChildContext() { return { foo: this.props.foo, bar: 'bar', }; } render() { return <Component />; } } Parent.childContextTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.string.isRequired, }; class Component extends React.Component { constructor(props, context) { super(props, context); constructorContext = context; } UNSAFE_componentWillReceiveProps(nextProps, nextContext) { componentWillReceivePropsContext = this.context; componentWillReceivePropsNextContext = nextContext; return true; } shouldComponentUpdate(nextProps, nextState, nextContext) { shouldComponentUpdateContext = this.context; shouldComponentUpdateNextContext = nextContext; return true; } UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { componentWillUpdateContext = this.context; componentWillUpdateNextContext = nextContext; } render() { renderContext = this.context; return <div />; } componentDidMount() { componentDidMountContext = this.context; } componentDidUpdate() { componentDidUpdateContext = this.context; } } Component.contextTypes = { foo: PropTypes.string, }; const container = document.createElement('div'); ReactDOM.render(<Parent foo="abc" />, container); expect(constructorContext).toEqual({foo: 'abc'}); expect(renderContext).toEqual({foo: 'abc'}); expect(componentDidMountContext).toEqual({foo: 'abc'}); ReactDOM.render(<Parent foo="def" />, container); expect(componentWillReceivePropsContext).toEqual({foo: 'abc'}); expect(componentWillReceivePropsNextContext).toEqual({foo: 'def'}); expect(shouldComponentUpdateContext).toEqual({foo: 'abc'}); expect(shouldComponentUpdateNextContext).toEqual({foo: 'def'}); expect(componentWillUpdateContext).toEqual({foo: 'abc'}); expect(componentWillUpdateNextContext).toEqual({foo: 'def'}); expect(renderContext).toEqual({foo: 'def'}); expect(componentDidUpdateContext).toEqual({foo: 'def'}); }); // @gate !disableLegacyContext || !__DEV__ it('should check context types', () => { class Component extends React.Component { render() { return <div />; } } Component.contextTypes = { foo: PropTypes.string.isRequired, }; expect(() => ReactTestUtils.renderIntoDocument(<Component />)).toErrorDev( 'Warning: Failed context type: ' + 'The context `foo` is marked as required in `Component`, but its value ' + 'is `undefined`.\n' + ' in Component (at **)', ); class ComponentInFooStringContext extends React.Component { getChildContext() { return { foo: this.props.fooValue, }; } render() { return <Component />; } } ComponentInFooStringContext.childContextTypes = { foo: PropTypes.string, }; // No additional errors expected ReactTestUtils.renderIntoDocument( <ComponentInFooStringContext fooValue={'bar'} />, ); class ComponentInFooNumberContext extends React.Component { getChildContext() { return { foo: this.props.fooValue, }; } render() { return <Component />; } } ComponentInFooNumberContext.childContextTypes = { foo: PropTypes.number, }; expect(() => ReactTestUtils.renderIntoDocument( <ComponentInFooNumberContext fooValue={123} />, ), ).toErrorDev( 'Warning: Failed context type: ' + 'Invalid context `foo` of type `number` supplied ' + 'to `Component`, expected `string`.\n' + ' in Component (at **)\n' + ' in ComponentInFooNumberContext (at **)', ); }); // @gate !disableLegacyContext || !__DEV__ it('should check child context types', () => { class Component extends React.Component { getChildContext() { return this.props.testContext; } render() { return <div />; } } Component.childContextTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.number, }; expect(() => ReactTestUtils.renderIntoDocument(<Component testContext={{bar: 123}} />), ).toErrorDev( 'Warning: Failed child context type: ' + 'The child context `foo` is marked as required in `Component`, but its ' + 'value is `undefined`.\n' + ' in Component (at **)', ); expect(() => ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 123}} />), ).toErrorDev( 'Warning: Failed child context type: ' + 'Invalid child context `foo` of type `number` ' + 'supplied to `Component`, expected `string`.\n' + ' in Component (at **)', ); // No additional errors expected ReactTestUtils.renderIntoDocument( <Component testContext={{foo: 'foo', bar: 123}} />, ); ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 'foo'}} />); }); it('warns of incorrect prop types on context provider', () => { const TestContext = React.createContext(); TestContext.Provider.propTypes = { value: PropTypes.string.isRequired, }; ReactTestUtils.renderIntoDocument(<TestContext.Provider value="val" />); class Component extends React.Component { render() { return <TestContext.Provider value={undefined} />; } } expect(() => ReactTestUtils.renderIntoDocument(<Component />)).toErrorDev( 'Warning: Failed prop type: The prop `value` is marked as required in ' + '`Context.Provider`, but its value is `undefined`.\n' + ' in Component (at **)', ); }); // TODO (bvaughn) Remove this test and the associated behavior in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. // @gate !disableLegacyContext || !__DEV__ it('should warn (but not error) if getChildContext method is missing', () => { class ComponentA extends React.Component { static childContextTypes = { foo: PropTypes.string.isRequired, }; render() { return <div />; } } class ComponentB extends React.Component { static childContextTypes = { foo: PropTypes.string.isRequired, }; render() { return <div />; } } expect(() => ReactTestUtils.renderIntoDocument(<ComponentA />)).toErrorDev( 'Warning: ComponentA.childContextTypes is specified but there is no ' + 'getChildContext() method on the instance. You can either define ' + 'getChildContext() on ComponentA or remove childContextTypes from it.', ); // Warnings should be deduped by component type ReactTestUtils.renderIntoDocument(<ComponentA />); expect(() => ReactTestUtils.renderIntoDocument(<ComponentB />)).toErrorDev( 'Warning: ComponentB.childContextTypes is specified but there is no ' + 'getChildContext() method on the instance. You can either define ' + 'getChildContext() on ComponentB or remove childContextTypes from it.', ); }); // TODO (bvaughn) Remove this test and the associated behavior in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. // @gate !disableLegacyContext it('should pass parent context if getChildContext method is missing', () => { class ParentContextProvider extends React.Component { static childContextTypes = { foo: PropTypes.string, }; getChildContext() { return { foo: 'FOO', }; } render() { return <MiddleMissingContext />; } } class MiddleMissingContext extends React.Component { static childContextTypes = { bar: PropTypes.string.isRequired, }; render() { return <ChildContextConsumer />; } } let childContext; class ChildContextConsumer extends React.Component { render() { childContext = this.context; return <div />; } } ChildContextConsumer.contextTypes = { bar: PropTypes.string.isRequired, foo: PropTypes.string.isRequired, }; expect(() => ReactTestUtils.renderIntoDocument(<ParentContextProvider />), ).toErrorDev([ 'Warning: MiddleMissingContext.childContextTypes is specified but there is no ' + 'getChildContext() method on the instance. You can either define getChildContext() ' + 'on MiddleMissingContext or remove childContextTypes from it.', 'Warning: Failed context type: The context `bar` is marked as required ' + 'in `ChildContextConsumer`, but its value is `undefined`.', ]); expect(childContext.bar).toBeUndefined(); expect(childContext.foo).toBe('FOO'); }); it('should pass next context to lifecycles', () => { let componentDidMountContext; let componentDidUpdateContext; let componentWillReceivePropsContext; let componentWillReceivePropsNextContext; let componentWillUpdateContext; let componentWillUpdateNextContext; let constructorContext; let renderContext; let shouldComponentUpdateWasCalled = false; const Context = React.createContext(); class Component extends React.Component { static contextType = Context; constructor(props, context) { super(props, context); constructorContext = context; } UNSAFE_componentWillReceiveProps(nextProps, nextContext) { componentWillReceivePropsContext = this.context; componentWillReceivePropsNextContext = nextContext; return true; } shouldComponentUpdate(nextProps, nextState, nextContext) { shouldComponentUpdateWasCalled = true; return true; } UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { componentWillUpdateContext = this.context; componentWillUpdateNextContext = nextContext; } render() { renderContext = this.context; return <div />; } componentDidMount() { componentDidMountContext = this.context; } componentDidUpdate() { componentDidUpdateContext = this.context; } } const firstContext = {foo: 123}; const secondContext = {bar: 456}; const container = document.createElement('div'); ReactDOM.render( <Context.Provider value={firstContext}> <Component /> </Context.Provider>, container, ); expect(constructorContext).toBe(firstContext); expect(renderContext).toBe(firstContext); expect(componentDidMountContext).toBe(firstContext); ReactDOM.render( <Context.Provider value={secondContext}> <Component /> </Context.Provider>, container, ); expect(componentWillReceivePropsContext).toBe(firstContext); expect(componentWillReceivePropsNextContext).toBe(secondContext); expect(componentWillUpdateContext).toBe(firstContext); expect(componentWillUpdateNextContext).toBe(secondContext); expect(renderContext).toBe(secondContext); expect(componentDidUpdateContext).toBe(secondContext); if (gate(flags => flags.enableLazyContextPropagation)) { expect(shouldComponentUpdateWasCalled).toBe(true); } else { // sCU is not called in this case because React force updates when a provider re-renders expect(shouldComponentUpdateWasCalled).toBe(false); } }); it('should re-render PureComponents when context Provider updates', () => { let renderedContext; const Context = React.createContext(); class Component extends React.PureComponent { static contextType = Context; render() { renderedContext = this.context; return <div />; } } const firstContext = {foo: 123}; const secondContext = {bar: 456}; const container = document.createElement('div'); ReactDOM.render( <Context.Provider value={firstContext}> <Component /> </Context.Provider>, container, ); expect(renderedContext).toBe(firstContext); ReactDOM.render( <Context.Provider value={secondContext}> <Component /> </Context.Provider>, container, ); expect(renderedContext).toBe(secondContext); }); // @gate !disableLegacyContext || !__DEV__ it('should warn if both contextType and contextTypes are defined', () => { const Context = React.createContext(); class ParentContextProvider extends React.Component { static childContextTypes = { foo: PropTypes.string, }; getChildContext() { return { foo: 'FOO', }; } render() { return this.props.children; } } class ComponentA extends React.Component { static contextTypes = { foo: PropTypes.string.isRequired, }; static contextType = Context; render() { return <div />; } } class ComponentB extends React.Component { static contextTypes = { foo: PropTypes.string.isRequired, }; static contextType = Context; render() { return <div />; } } expect(() => ReactTestUtils.renderIntoDocument( <ParentContextProvider> <ComponentA /> </ParentContextProvider>, ), ).toErrorDev( 'Warning: ComponentA declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', ); // Warnings should be deduped by component type ReactTestUtils.renderIntoDocument( <ParentContextProvider> <ComponentA /> </ParentContextProvider>, ); expect(() => ReactTestUtils.renderIntoDocument( <ParentContextProvider> <ComponentB /> </ParentContextProvider>, ), ).toErrorDev( 'Warning: ComponentB declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', ); }); it('should warn if an invalid contextType is defined', () => { const Context = React.createContext(); // This tests that both Context.Consumer and Context.Provider // warn about invalid contextType. class ComponentA extends React.Component { static contextType = Context.Consumer; render() { return <div />; } } class ComponentB extends React.Component { static contextType = Context.Provider; render() { return <div />; } } expect(() => { ReactTestUtils.renderIntoDocument(<ComponentA />); }).toErrorDev( 'Warning: ComponentA defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'Did you accidentally pass the Context.Consumer instead?', ); // Warnings should be deduped by component type ReactTestUtils.renderIntoDocument(<ComponentA />); expect(() => { ReactTestUtils.renderIntoDocument(<ComponentB />); }).toErrorDev( 'Warning: ComponentB defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'Did you accidentally pass the Context.Provider instead?', ); }); it('should not warn when class contextType is null', () => { class Foo extends React.Component { static contextType = null; // Handy for conditional declaration render() { return this.context.hello.world; } } expect(() => { ReactTestUtils.renderIntoDocument(<Foo />); }).toThrow("Cannot read property 'world' of undefined"); }); it('should warn when class contextType is undefined', () => { class Foo extends React.Component { // This commonly happens with circular deps // https://github.com/facebook/react/issues/13969 static contextType = undefined; render() { return this.context.hello.world; } } expect(() => { expect(() => { ReactTestUtils.renderIntoDocument(<Foo />); }).toThrow("Cannot read property 'world' of undefined"); }).toErrorDev( 'Foo defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, ' + 'so try moving the createContext() call to a separate file.', ); }); it('should warn when class contextType is an object', () => { class Foo extends React.Component { // Can happen due to a typo static contextType = { x: 42, y: 'hello', }; render() { return this.context.hello.world; } } expect(() => { expect(() => { ReactTestUtils.renderIntoDocument(<Foo />); }).toThrow("Cannot read property 'hello' of undefined"); }).toErrorDev( 'Foo defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'However, it is set to an object with keys {x, y}.', ); }); it('should warn when class contextType is a primitive', () => { class Foo extends React.Component { static contextType = 'foo'; render() { return this.context.hello.world; } } expect(() => { expect(() => { ReactTestUtils.renderIntoDocument(<Foo />); }).toThrow("Cannot read property 'world' of undefined"); }).toErrorDev( 'Foo defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'However, it is set to a string.', ); }); it('should warn if you define contextType on a function component', () => { const Context = React.createContext(); function ComponentA() { return <div />; } ComponentA.contextType = Context; function ComponentB() { return <div />; } ComponentB.contextType = Context; expect(() => ReactTestUtils.renderIntoDocument(<ComponentA />)).toErrorDev( 'Warning: ComponentA: Function components do not support contextType.', ); // Warnings should be deduped by component type ReactTestUtils.renderIntoDocument(<ComponentA />); expect(() => ReactTestUtils.renderIntoDocument(<ComponentB />)).toErrorDev( 'Warning: ComponentB: Function components do not support contextType.', ); }); it('should honor a displayName if set on the context type', () => { const Context = React.createContext(null); Context.displayName = 'MyContextType'; function Validator() { return null; } Validator.propTypes = {dontPassToSeeErrorStack: PropTypes.bool.isRequired}; expect(() => { ReactDOMServer.renderToStaticMarkup( <Context.Provider> <Context.Consumer>{() => <Validator />}</Context.Consumer> </Context.Provider>, ); }).toErrorDev( 'Warning: Failed prop type: The prop `dontPassToSeeErrorStack` is marked as required in `Validator`, but its value is `undefined`.\n' + ' in Validator (at **)', ); }); it('warns if displayName is set on the consumer type', () => { const Context = React.createContext(null); expect(() => { Context.Consumer.displayName = 'IgnoredName'; }).toWarnDev( 'Warning: Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = 'IgnoredName'.", {withoutStack: true}, ); // warning is deduped by Context so subsequent setting is fine Context.Consumer.displayName = 'ADifferentName'; }); });
30.089655
141
0.636719
null
/** * 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. */ 'use strict'; const invertObject = require('../invertObject'); const objectValues = target => Object.keys(target).map(key => target[key]); describe('invertObject', () => { it('should return an empty object for an empty input', () => { expect(invertObject({})).toEqual({}); }); it('should invert key-values', () => { expect( invertObject({ a: '3', b: '4', }) ).toEqual({ 3: 'a', 4: 'b', }); }); it('should take the last value when there are duplications in vals', () => { expect( invertObject({ a: '3', b: '4', c: '3', }) ).toEqual({ 4: 'b', 3: 'c', }); }); it('should preserve the original order', () => { expect( Object.keys( invertObject({ a: '3', b: '4', c: '3', }) ) ).toEqual(['3', '4']); expect( objectValues( invertObject({ a: '3', b: '4', c: '3', }) ) ).toEqual(['c', 'b']); }); });
18.292308
78
0.468476
owtf
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; const React = window.React; const ReactDOM = window.ReactDOM; class SelectFixture extends React.Component { state = {value: ''}; _nestedDOMNode = null; _singleFormDOMNode = null; _multipleFormDOMNode = null; onChange = event => { this.setState({value: event.target.value}); }; resetSingleOptionForm = event => { event.preventDefault(); this._singleFormDOMNode.reset(); }; resetMultipleOptionForm = event => { event.preventDefault(); this._multipleFormDOMNode.reset(); }; componentDidMount() { this._renderNestedSelect(); } componentDidUpdate() { this._renderNestedSelect(); } _renderNestedSelect() { ReactDOM.render( <select value={this.state.value} onChange={this.onChange}> <option value="">Select a color</option> <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> </select>, this._nestedDOMNode ); } render() { return ( <FixtureSet title="Selects"> <form className="field-group"> <fieldset> <legend>Controlled</legend> <select value={this.state.value} onChange={this.onChange}> <option value="">Select a color</option> <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> </select> <span className="hint">Value: {this.state.value}</span> </fieldset> <fieldset> <legend>Uncontrolled</legend> <select defaultValue=""> <option value="">Select a color</option> <option value="red">Red</option> <option value="blue">Blue</option> <option value="green">Green</option> </select> </fieldset> <fieldset> <legend>Controlled in nested subtree</legend> <div ref={node => (this._nestedDOMNode = node)} /> <span className="hint"> This should synchronize in both direction with the "Controlled". </span> </fieldset> </form> <TestCase title="A selected disabled option" relatedIssues="2803"> <TestCase.Steps> <li>Open the select</li> <li>Select "1"</li> <li>Attempt to reselect "Please select an item"</li> </TestCase.Steps> <TestCase.ExpectedResult> The initial picked option should be "Please select an item", however it should not be a selectable option. </TestCase.ExpectedResult> <div className="test-fixture"> <select defaultValue=""> <option value="" disabled> Please select an item </option> <option>0</option> <option>1</option> <option>2</option> </select> </div> </TestCase> <TestCase title="An unselected disabled option" relatedIssues="2803"> <TestCase.ExpectedResult> The initial picked option value should "0": the first non-disabled option. </TestCase.ExpectedResult> <div className="test-fixture"> <select defaultValue=""> <option disabled>Please select an item</option> <option>0</option> <option>1</option> <option>2</option> </select> </div> </TestCase> <TestCase title="A single select being reset"> <TestCase.Steps> <li>Open the select</li> <li>Select "baz" or "foo"</li> <li>Click the "Reset" button</li> </TestCase.Steps> <TestCase.ExpectedResult> The select should be reset to the initial value, "bar" </TestCase.ExpectedResult> <div className="test-fixture"> <form ref={n => (this._singleFormDOMNode = n)}> <select defaultValue="bar"> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> <button onClick={this.resetSingleOptionForm}>Reset</button> </form> </div> </TestCase> <TestCase title="A multiple select being reset"> <TestCase.Steps> <li>Select any combination of options</li> <li>Click the "Reset" button</li> </TestCase.Steps> <TestCase.ExpectedResult> The select should be reset to the initial values "foo" and "baz" </TestCase.ExpectedResult> <div className="test-fixture"> <form ref={n => (this._multipleFormDOMNode = n)}> <select multiple defaultValue={['foo', 'baz']}> <option value="foo">foo</option> <option value="bar">bar</option> <option value="baz">baz</option> </select> <button onClick={this.resetMultipleOptionForm}>Reset</button> </form> </div> </TestCase> <TestCase title="A multiple select being scrolled to first selected option"> <TestCase.ExpectedResult> First selected option should be visible </TestCase.ExpectedResult> <div className="test-fixture"> <form> <select multiple defaultValue={['tiger']}> <option value="gorilla">gorilla</option> <option value="giraffe">giraffe</option> <option value="monkey">monkey</option> <option value="lion">lion</option> <option value="mongoose">mongoose</option> <option value="tiger">tiger</option> </select> </form> </div> </TestCase> <TestCase title="An option which contains conditional render fails" relatedIssues="11911"> <TestCase.Steps> <li>Select any option</li> </TestCase.Steps> <TestCase.ExpectedResult> Option should be set </TestCase.ExpectedResult> <div className="test-fixture"> <select value={this.state.value} onChange={this.onChange}> <option value="red"> red {this.state.value === 'red' && 'is chosen '} TextNode </option> <option value="blue"> blue {this.state.value === 'blue' && 'is chosen '} TextNode </option> <option value="green"> green {this.state.value === 'green' && 'is chosen '} TextNode </option> </select> </div> </TestCase> <TestCase title="A select with the size attribute should not set first option as selected" relatedIssues="14239" introducedIn="16.0.0"> <TestCase.ExpectedResult> No options should be selected. </TestCase.ExpectedResult> <div className="test-fixture"> <select size="3"> <option>0</option> <option>1</option> <option>2</option> </select> </div> <p className="footnote"> <b>Notes:</b> This happens if <code>size</code> is assigned after options are selected. The select element picks the first item by default, then it is expanded to show more options when{' '} <code>size</code> is assigned, preserving the default selection. </p> <p className="footnote"> This was introduced in React 16.0.0 when options were added before select attribute assignment. </p> </TestCase> </FixtureSet> ); } } export default SelectFixture;
32.656904
90
0.538232
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-noop-renderer.production.min.js'); } else { module.exports = require('./cjs/react-noop-renderer.development.js'); }
26.375
74
0.688073
cybersecurity-penetration-testing
/** * 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. * * @emails react-core */ 'use strict'; let React; let ReactDOM; let Suspense; let Scheduler; let act; let textCache; describe('ReactDOMSuspensePlaceholder', () => { let container; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; Suspense = React.Suspense; container = document.createElement('div'); document.body.appendChild(container); textCache = new Map(); }); afterEach(() => { document.body.removeChild(container); }); function resolveText(text) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; 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.log(`Suspend! [${text}]`); throw record.value; case 'rejected': throw record.value; case 'resolved': return record.value; } } 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.set(text, newRecord); throw thenable; } } function Text({text}) { Scheduler.log(text); return text; } function AsyncText({text}) { readText(text); Scheduler.log(text); return text; } it('hides and unhides timed out DOM elements', async () => { const divs = [ React.createRef(null), React.createRef(null), React.createRef(null), ]; function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <div ref={divs[0]}> <Text text="A" /> </div> <div ref={divs[1]}> <AsyncText text="B" /> </div> <div style={{display: 'inline'}} ref={divs[2]}> <Text text="C" /> </div> </Suspense> ); } ReactDOM.render(<App />, container); expect(window.getComputedStyle(divs[0].current).display).toEqual('none'); expect(window.getComputedStyle(divs[1].current).display).toEqual('none'); expect(window.getComputedStyle(divs[2].current).display).toEqual('none'); await act(async () => { await resolveText('B'); }); expect(window.getComputedStyle(divs[0].current).display).toEqual('block'); expect(window.getComputedStyle(divs[1].current).display).toEqual('block'); // This div's display was set with a prop. expect(window.getComputedStyle(divs[2].current).display).toEqual('inline'); }); it('hides and unhides timed out text nodes', async () => { function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <Text text="A" /> <AsyncText text="B" /> <Text text="C" /> </Suspense> ); } ReactDOM.render(<App />, container); expect(container.textContent).toEqual('Loading...'); await act(async () => { await resolveText('B'); }); expect(container.textContent).toEqual('ABC'); }); it( 'outside concurrent mode, re-hides children if their display is updated ' + 'but the boundary is still showing the fallback', async () => { const {useState} = React; let setIsVisible; function Sibling({children}) { const [isVisible, _setIsVisible] = useState(false); setIsVisible = _setIsVisible; return ( <span style={{display: isVisible ? 'inline' : 'none'}}> {children} </span> ); } function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <Sibling>Sibling</Sibling> <span> <AsyncText text="Async" /> </span> </Suspense> ); } await act(() => { ReactDOM.render(<App />, container); }); expect(container.innerHTML).toEqual( '<span style="display: none;">Sibling</span><span style=' + '"display: none;"></span>Loading...', ); // Update the inline display style. It will be overridden because it's // inside a hidden fallback. await act(() => setIsVisible(true)); expect(container.innerHTML).toEqual( '<span style="display: none;">Sibling</span><span style=' + '"display: none;"></span>Loading...', ); // Unsuspend. The style should now match the inline prop. await act(() => resolveText('Async')); expect(container.innerHTML).toEqual( '<span style="display: inline;">Sibling</span><span style="">Async</span>', ); }, ); // Regression test for https://github.com/facebook/react/issues/14188 it('can call findDOMNode() in a suspended component commit phase', async () => { const log = []; const Lazy = React.lazy( () => new Promise(resolve => resolve({ default() { return 'lazy'; }, }), ), ); class Child extends React.Component { componentDidMount() { log.push('cDM ' + this.props.id); ReactDOM.findDOMNode(this); } componentDidUpdate() { log.push('cDU ' + this.props.id); ReactDOM.findDOMNode(this); } render() { return 'child'; } } const buttonRef = React.createRef(); class App extends React.Component { state = { suspend: false, }; handleClick = () => { this.setState({suspend: true}); }; render() { return ( <React.Suspense fallback="Loading"> <Child id="first" /> <button ref={buttonRef} onClick={this.handleClick}> Suspend </button> <Child id="second" /> {this.state.suspend && <Lazy />} </React.Suspense> ); } } ReactDOM.render(<App />, container); expect(log).toEqual(['cDM first', 'cDM second']); log.length = 0; buttonRef.current.dispatchEvent(new MouseEvent('click', {bubbles: true})); await Lazy; expect(log).toEqual(['cDU first', 'cDU second']); }); // Regression test for https://github.com/facebook/react/issues/14188 it('can call findDOMNode() in a suspended component commit phase (#2)', () => { let suspendOnce = Promise.resolve(); function Suspend() { if (suspendOnce) { const promise = suspendOnce; suspendOnce = null; throw promise; } return null; } const log = []; class Child extends React.Component { componentDidMount() { log.push('cDM'); ReactDOM.findDOMNode(this); } componentDidUpdate() { log.push('cDU'); ReactDOM.findDOMNode(this); } render() { return null; } } function App() { return ( <Suspense fallback="Loading"> <Suspend /> <Child /> </Suspense> ); } ReactDOM.render(<App />, container); expect(log).toEqual(['cDM']); ReactDOM.render(<App />, container); expect(log).toEqual(['cDM', 'cDU']); }); });
24.722045
83
0.545342
Hands-On-Penetration-Testing-with-Python
/** * 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 throttle from 'lodash.throttle'; import { useCallback, useEffect, useLayoutEffect, useReducer, useState, useContext, } from 'react'; import { localStorageGetItem, localStorageSetItem, } from 'react-devtools-shared/src/storage'; import {StoreContext, BridgeContext} from './context'; import {sanitizeForParse, smartParse, smartStringify} from '../utils'; type ACTION_RESET = { type: 'RESET', externalValue: any, }; type ACTION_UPDATE = { type: 'UPDATE', editableValue: any, externalValue: any, }; type UseEditableValueAction = ACTION_RESET | ACTION_UPDATE; type UseEditableValueDispatch = (action: UseEditableValueAction) => void; type UseEditableValueState = { editableValue: any, externalValue: any, hasPendingChanges: boolean, isValid: boolean, parsedValue: any, }; function useEditableValueReducer( state: UseEditableValueState, action: UseEditableValueAction, ) { switch (action.type) { case 'RESET': return { ...state, editableValue: smartStringify(action.externalValue), externalValue: action.externalValue, hasPendingChanges: false, isValid: true, parsedValue: action.externalValue, }; case 'UPDATE': let isNewValueValid = false; let newParsedValue; try { newParsedValue = smartParse(action.editableValue); isNewValueValid = true; } catch (error) {} return { ...state, editableValue: sanitizeForParse(action.editableValue), externalValue: action.externalValue, hasPendingChanges: smartStringify(action.externalValue) !== action.editableValue, isValid: isNewValueValid, parsedValue: isNewValueValid ? newParsedValue : state.parsedValue, }; default: throw new Error(`Invalid action "${action.type}"`); } } // Convenience hook for working with an editable value that is validated via JSON.parse. export function useEditableValue( externalValue: any, ): [UseEditableValueState, UseEditableValueDispatch] { const [state, dispatch] = useReducer< UseEditableValueState, UseEditableValueState, UseEditableValueAction, >(useEditableValueReducer, { editableValue: smartStringify(externalValue), externalValue, hasPendingChanges: false, isValid: true, parsedValue: externalValue, }); if (!Object.is(state.externalValue, externalValue)) { if (!state.hasPendingChanges) { dispatch({ type: 'RESET', externalValue, }); } else { dispatch({ type: 'UPDATE', editableValue: state.editableValue, externalValue, }); } } return [state, dispatch]; } export function useIsOverflowing( containerRef: {current: HTMLDivElement | null, ...}, totalChildWidth: number, ): boolean { const [isOverflowing, setIsOverflowing] = useState<boolean>(false); // It's important to use a layout effect, so that we avoid showing a flash of overflowed content. useLayoutEffect(() => { if (containerRef.current === null) { return () => {}; } const container = ((containerRef.current: any): HTMLDivElement); const handleResize = throttle( () => setIsOverflowing(container.clientWidth <= totalChildWidth), 100, ); handleResize(); // It's important to listen to the ownerDocument.defaultView to support the browser extension. // Here we use portals to render individual tabs (e.g. Profiler), // and the root document might belong to a different window. const ownerWindow = container.ownerDocument.defaultView; ownerWindow.addEventListener('resize', handleResize); return () => ownerWindow.removeEventListener('resize', handleResize); }, [containerRef, totalChildWidth]); return isOverflowing; } // Forked from https://usehooks.com/useLocalStorage/ export function useLocalStorage<T>( key: string, initialValue: T | (() => T), onValueSet?: (any, string) => void, ): [T, (value: T | (() => T)) => void] { const getValueFromLocalStorage = useCallback(() => { try { const item = localStorageGetItem(key); if (item != null) { return JSON.parse(item); } } catch (error) { console.log(error); } if (typeof initialValue === 'function') { return ((initialValue: any): () => T)(); } else { return initialValue; } }, [initialValue, key]); const [storedValue, setStoredValue] = useState<any>(getValueFromLocalStorage); const setValue = useCallback( (value: $FlowFixMe) => { try { const valueToStore = value instanceof Function ? (value: any)(storedValue) : value; setStoredValue(valueToStore); localStorageSetItem(key, JSON.stringify(valueToStore)); // Notify listeners that this setting has changed. window.dispatchEvent(new Event(key)); if (onValueSet != null) { onValueSet(valueToStore, key); } } catch (error) { console.log(error); } }, [key, storedValue], ); // Listen for changes to this local storage value made from other windows. // This enables the e.g. "⚛️ Elements" tab to update in response to changes from "⚛️ Settings". useLayoutEffect(() => { // $FlowFixMe[missing-local-annot] const onStorage = event => { const newValue = getValueFromLocalStorage(); if (key === event.key && storedValue !== newValue) { setValue(newValue); } }; window.addEventListener('storage', onStorage); return () => { window.removeEventListener('storage', onStorage); }; }, [getValueFromLocalStorage, key, storedValue, setValue]); return [storedValue, setValue]; } export function useModalDismissSignal( modalRef: {current: HTMLDivElement | null, ...}, dismissCallback: () => void, dismissOnClickOutside?: boolean = true, ): void { useEffect(() => { if (modalRef.current === null) { return () => {}; } const handleDocumentKeyDown = (event: any) => { if (event.key === 'Escape') { dismissCallback(); } }; const handleDocumentClick = (event: any) => { if ( modalRef.current !== null && !modalRef.current.contains(event.target) ) { event.stopPropagation(); event.preventDefault(); dismissCallback(); } }; let ownerDocument = null; // Delay until after the current call stack is empty, // in case this effect is being run while an event is currently bubbling. // In that case, we don't want to listen to the pre-existing event. let timeoutID: null | TimeoutID = setTimeout(() => { timeoutID = null; // It's important to listen to the ownerDocument to support the browser extension. // Here we use portals to render individual tabs (e.g. Profiler), // and the root document might belong to a different window. const div = modalRef.current; if (div != null) { ownerDocument = div.ownerDocument; ownerDocument.addEventListener('keydown', handleDocumentKeyDown); if (dismissOnClickOutside) { ownerDocument.addEventListener('click', handleDocumentClick, true); } } }, 0); return () => { if (timeoutID !== null) { clearTimeout(timeoutID); } if (ownerDocument !== null) { ownerDocument.removeEventListener('keydown', handleDocumentKeyDown); ownerDocument.removeEventListener('click', handleDocumentClick, true); } }; }, [modalRef, dismissCallback, dismissOnClickOutside]); } // Copied from https://github.com/facebook/react/pull/15022 export function useSubscription<Value>({ getCurrentValue, subscribe, }: { getCurrentValue: () => Value, subscribe: (callback: Function) => () => void, }): Value { const [state, setState] = useState(() => ({ getCurrentValue, subscribe, value: getCurrentValue(), })); if ( state.getCurrentValue !== getCurrentValue || state.subscribe !== subscribe ) { setState({ getCurrentValue, subscribe, value: getCurrentValue(), }); } useEffect(() => { let didUnsubscribe = false; const checkForUpdates = () => { if (didUnsubscribe) { return; } setState(prevState => { if ( prevState.getCurrentValue !== getCurrentValue || prevState.subscribe !== subscribe ) { return prevState; } const value = getCurrentValue(); if (prevState.value === value) { return prevState; } return {...prevState, value}; }); }; const unsubscribe = subscribe(checkForUpdates); checkForUpdates(); return () => { didUnsubscribe = true; unsubscribe(); }; }, [getCurrentValue, subscribe]); return state.value; } export function useHighlightNativeElement(): { clearHighlightNativeElement: () => void, highlightNativeElement: (id: number) => void, } { const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const highlightNativeElement = useCallback( (id: number) => { const element = store.getElementByID(id); const rendererID = store.getRendererIDForElement(id); if (element !== null && rendererID !== null) { bridge.send('highlightNativeElement', { displayName: element.displayName, hideAfterTimeout: false, id, openNativeElementsPanel: false, rendererID, scrollIntoView: false, }); } }, [store, bridge], ); const clearHighlightNativeElement = useCallback(() => { bridge.send('clearNativeElementHighlight'); }, [bridge]); return { highlightNativeElement, clearHighlightNativeElement, }; }
26.172973
99
0.638416
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type ModuleLoading = null; export function prepareDestinationForModuleImpl( moduleLoading: ModuleLoading, chunks: mixed, nonce: ?string, ) { // In the browser we don't need to prepare our destination since the browser is the Destination }
23.210526
97
0.732026
PenetrationTestingScripts
/** * 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 {StyleXPlugin} from 'react-devtools-shared/src/frontend/types'; import isArray from 'react-devtools-shared/src/isArray'; const cachedStyleNameToValueMap: Map<string, string> = new Map(); export function getStyleXData(data: any): StyleXPlugin { const sources = new Set<string>(); const resolvedStyles = {}; crawlData(data, sources, resolvedStyles); return { sources: Array.from(sources).sort(), resolvedStyles, }; } export function crawlData( data: any, sources: Set<string>, resolvedStyles: Object, ): void { if (data == null) { return; } if (isArray(data)) { data.forEach(entry => { if (entry == null) { return; } if (isArray(entry)) { crawlData(entry, sources, resolvedStyles); } else { crawlObjectProperties(entry, sources, resolvedStyles); } }); } else { crawlObjectProperties(data, sources, resolvedStyles); } resolvedStyles = Object.fromEntries<string, any>( Object.entries(resolvedStyles).sort(), ); } function crawlObjectProperties( entry: Object, sources: Set<string>, resolvedStyles: Object, ): void { const keys = Object.keys(entry); keys.forEach(key => { const value = entry[key]; if (typeof value === 'string') { if (key === value) { // Special case; this key is the name of the style's source/file/module. sources.add(key); } else { const propertyValue = getPropertyValueForStyleName(value); if (propertyValue != null) { resolvedStyles[key] = propertyValue; } } } else { const nestedStyle = {}; resolvedStyles[key] = nestedStyle; crawlData([value], sources, nestedStyle); } }); } function getPropertyValueForStyleName(styleName: string): string | null { if (cachedStyleNameToValueMap.has(styleName)) { return ((cachedStyleNameToValueMap.get(styleName): any): string); } for ( let styleSheetIndex = 0; styleSheetIndex < document.styleSheets.length; styleSheetIndex++ ) { const styleSheet = ((document.styleSheets[ styleSheetIndex ]: any): CSSStyleSheet); let rules: CSSRuleList | null = null; // this might throw if CORS rules are enforced https://www.w3.org/TR/cssom-1/#the-cssstylesheet-interface try { rules = styleSheet.cssRules; } catch (_e) { continue; } for (let ruleIndex = 0; ruleIndex < rules.length; ruleIndex++) { if (!(rules[ruleIndex] instanceof CSSStyleRule)) { continue; } const rule = ((rules[ruleIndex]: any): CSSStyleRule); const {cssText, selectorText, style} = rule; if (selectorText != null) { if (selectorText.startsWith(`.${styleName}`)) { const match = cssText.match(/{ *([a-z\-]+):/); if (match !== null) { const property = match[1]; const value = style.getPropertyValue(property); cachedStyleNameToValueMap.set(styleName, value); return value; } else { return null; } } } } } return null; }
24.435115
109
0.619334
owtf
/** * 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. * */ export default function Layout({children}) { return <main>{children}</main>; }
22.083333
66
0.699275
null
/** * 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. * * @emails react-core */ 'use strict'; import {insertNodesAndExecuteScripts} from 'react-dom/src/test-utils/FizzTestUtils'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; global.TextDecoder = require('util').TextDecoder; // Don't wait before processing work on the server. // TODO: we can replace this with FlightServer.act(). global.setTimeout = cb => cb(); let container; let clientExports; let serverExports; let webpackMap; let webpackServerMap; let React; let ReactDOMServer; let ReactServerDOMServer; let ReactServerDOMClient; let ReactDOMClient; let useFormState; let act; describe('ReactFlightDOMForm', () => { beforeEach(() => { jest.resetModules(); // Simulate the condition resolution jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-server-dom-webpack/server', () => require('react-server-dom-webpack/server.edge'), ); ReactServerDOMServer = require('react-server-dom-webpack/server.edge'); const WebpackMock = require('./utils/WebpackMock'); clientExports = WebpackMock.clientExports; serverExports = WebpackMock.serverExports; webpackMap = WebpackMock.webpackMap; webpackServerMap = WebpackMock.webpackServerMap; __unmockReact(); jest.resetModules(); React = require('react'); ReactServerDOMClient = require('react-server-dom-webpack/client.edge'); ReactDOMServer = require('react-dom/server.edge'); ReactDOMClient = require('react-dom/client'); act = React.unstable_act; useFormState = require('react-dom').useFormState; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); }); async function POST(formData) { const boundAction = await ReactServerDOMServer.decodeAction( formData, webpackServerMap, ); const returnValue = boundAction(); const formState = await ReactServerDOMServer.decodeFormState( await returnValue, formData, webpackServerMap, ); return {returnValue, formState}; } function submit(submitter) { const form = submitter.form || submitter; if (!submitter.form) { submitter = undefined; } const submitEvent = new Event('submit', {bubbles: true, cancelable: true}); submitEvent.submitter = submitter; const returnValue = form.dispatchEvent(submitEvent); if (!returnValue) { return; } const action = (submitter && submitter.getAttribute('formaction')) || form.action; if (!/\s*javascript:/i.test(action)) { const method = (submitter && submitter.formMethod) || form.method; const encType = (submitter && submitter.formEnctype) || form.enctype; if (method === 'post' && encType === 'multipart/form-data') { let formData; if (submitter) { const temp = document.createElement('input'); temp.name = submitter.name; temp.value = submitter.value; submitter.parentNode.insertBefore(temp, submitter); formData = new FormData(form); temp.parentNode.removeChild(temp); } else { formData = new FormData(form); } return POST(formData); } throw new Error('Navigate to: ' + action); } } async function readIntoContainer(stream) { const reader = stream.getReader(); let result = ''; while (true) { const {done, value} = await reader.read(); if (done) { break; } result += Buffer.from(value).toString('utf8'); } const temp = document.createElement('div'); temp.innerHTML = result; insertNodesAndExecuteScripts(temp, container, null); } // @gate enableFormActions it('can submit a passed server action without hydrating it', async () => { let foo = null; const serverAction = serverExports(function action(formData) { foo = formData.get('foo'); return 'hello'; }); function App() { return ( <form action={serverAction}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const rscStream = ReactServerDOMServer.renderToReadableStream(<App />); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.firstChild; expect(foo).toBe(null); const {returnValue} = await submit(form); expect(returnValue).toBe('hello'); expect(foo).toBe('bar'); }); // @gate enableFormActions it('can submit an imported server action without hydrating it', async () => { let foo = null; const ServerModule = serverExports(function action(formData) { foo = formData.get('foo'); return 'hi'; }); const serverAction = ReactServerDOMClient.createServerReference( ServerModule.$$id, ); function App() { return ( <form action={serverAction}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const ssrStream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(ssrStream); const form = container.firstChild; expect(foo).toBe(null); const {returnValue} = await submit(form); expect(returnValue).toBe('hi'); expect(foo).toBe('bar'); }); // @gate enableFormActions it('can submit a complex closure server action without hydrating it', async () => { let foo = null; const serverAction = serverExports(function action(bound, formData) { foo = formData.get('foo') + bound.complex; return 'hello'; }); function App() { return ( <form action={serverAction.bind(null, {complex: 'object'})}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const rscStream = ReactServerDOMServer.renderToReadableStream(<App />); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.firstChild; expect(foo).toBe(null); const {returnValue} = await submit(form); expect(returnValue).toBe('hello'); expect(foo).toBe('barobject'); }); // @gate enableFormActions it('can submit a multiple complex closure server action without hydrating it', async () => { let foo = null; const serverAction = serverExports(function action(bound, formData) { foo = formData.get('foo') + bound.complex; return 'hello' + bound.complex; }); function App() { return ( <form action={serverAction.bind(null, {complex: 'a'})}> <input type="text" name="foo" defaultValue="bar" /> <button formAction={serverAction.bind(null, {complex: 'b'})} /> <button formAction={serverAction.bind(null, {complex: 'c'})} /> <input type="submit" formAction={serverAction.bind(null, {complex: 'd'})} /> </form> ); } const rscStream = ReactServerDOMServer.renderToReadableStream(<App />); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.firstChild; expect(foo).toBe(null); const {returnValue} = await submit(form.getElementsByTagName('button')[1]); expect(returnValue).toBe('helloc'); expect(foo).toBe('barc'); }); // @gate enableFormActions it('can bind an imported server action on the client without hydrating it', async () => { let foo = null; const ServerModule = serverExports(function action(bound, formData) { foo = formData.get('foo') + bound.complex; return 'hello'; }); const serverAction = ReactServerDOMClient.createServerReference( ServerModule.$$id, ); function Client() { return ( <form action={serverAction.bind(null, {complex: 'object'})}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const ssrStream = await ReactDOMServer.renderToReadableStream(<Client />); await readIntoContainer(ssrStream); const form = container.firstChild; expect(foo).toBe(null); const {returnValue} = await submit(form); expect(returnValue).toBe('hello'); expect(foo).toBe('barobject'); }); // @gate enableFormActions it('can bind a server action on the client without hydrating it', async () => { let foo = null; const serverAction = serverExports(function action(bound, formData) { foo = formData.get('foo') + bound.complex; return 'hello'; }); function Client({action}) { return ( <form action={action.bind(null, {complex: 'object'})}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const ClientRef = await clientExports(Client); const rscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={serverAction} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.firstChild; expect(foo).toBe(null); const {returnValue} = await submit(form); expect(returnValue).toBe('hello'); expect(foo).toBe('barobject'); }); // @gate enableFormActions // @gate enableAsyncActions it("useFormState's dispatch binds the initial state to the provided action", async () => { const serverAction = serverExports( async function action(prevState, formData) { return { count: prevState.count + parseInt(formData.get('incrementAmount'), 10), }; }, ); const initialState = {count: 1}; function Client({action}) { const [state, dispatch] = useFormState(action, initialState); return ( <form action={dispatch}> <span>Count: {state.count}</span> <input type="text" name="incrementAmount" defaultValue="5" /> </form> ); } const ClientRef = await clientExports(Client); const rscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={serverAction} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.getElementsByTagName('form')[0]; const span = container.getElementsByTagName('span')[0]; expect(span.textContent).toBe('Count: 1'); const {returnValue} = await submit(form); expect(await returnValue).toEqual({count: 6}); }); // @gate enableFormActions // @gate enableAsyncActions it('useFormState can reuse state during MPA form submission', async () => { const serverAction = serverExports( async function action(prevState, formData) { return prevState + 1; }, ); function Form({action}) { const [count, dispatch] = useFormState(action, 1); return <form action={dispatch}>{count}</form>; } function Client({action}) { return ( <div> <Form action={action} /> <Form action={action} /> <Form action={action} /> </div> ); } const ClientRef = await clientExports(Client); const rscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={serverAction} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); expect(container.textContent).toBe('111'); // There are three identical forms. We're going to submit the second one. const form = container.getElementsByTagName('form')[1]; const {formState} = await submit(form); // Simulate an MPA form submission by resetting the container and // rendering again. container.innerHTML = ''; const postbackRscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={serverAction} />, webpackMap, ); const postbackResponse = ReactServerDOMClient.createFromReadableStream( postbackRscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }, ); const postbackSsrStream = await ReactDOMServer.renderToReadableStream( postbackResponse, {formState: formState}, ); await readIntoContainer(postbackSsrStream); // Only the second form's state should have been updated. expect(container.textContent).toBe('121'); // Test that it hydrates correctly if (__DEV__) { // TODO: Can't use our internal act() util that works in production // because it works by overriding the timer APIs, which this test module // also does. Remove dev condition once FlightServer.act() is available. await act(() => { ReactDOMClient.hydrateRoot(container, postbackResponse, { formState: formState, }); }); expect(container.textContent).toBe('121'); } }); // @gate enableFormActions // @gate enableAsyncActions it( 'useFormState preserves state if arity is the same, but different ' + 'arguments are bound (i.e. inline closure)', async () => { const serverAction = serverExports( async function action(stepSize, prevState, formData) { return prevState + stepSize; }, ); function Form({action}) { const [count, dispatch] = useFormState(action, 1); return <form action={dispatch}>{count}</form>; } function Client({action}) { return ( <div> <Form action={action} /> <Form action={action} /> <Form action={action} /> </div> ); } const ClientRef = await clientExports(Client); const rscStream = ReactServerDOMServer.renderToReadableStream( // Note: `.bind` is the same as an inline closure with 'use server' <ClientRef action={serverAction.bind(null, 1)} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream( rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }, ); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); expect(container.textContent).toBe('111'); // There are three identical forms. We're going to submit the second one. const form = container.getElementsByTagName('form')[1]; const {formState} = await submit(form); // Simulate an MPA form submission by resetting the container and // rendering again. container.innerHTML = ''; // On the next page, the same server action is rendered again, but with // a different bound stepSize argument. We should treat this as the same // action signature. const postbackRscStream = ReactServerDOMServer.renderToReadableStream( // Note: `.bind` is the same as an inline closure with 'use server' <ClientRef action={serverAction.bind(null, 5)} />, webpackMap, ); const postbackResponse = ReactServerDOMClient.createFromReadableStream( postbackRscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }, ); const postbackSsrStream = await ReactDOMServer.renderToReadableStream( postbackResponse, {formState: formState}, ); await readIntoContainer(postbackSsrStream); // The state should have been preserved because the action signatures are // the same. (Note that the amount increased by 1, because that was the // value of stepSize at the time the form was submitted) expect(container.textContent).toBe('121'); // Now submit the form again. This time, the state should increase by 5 // because the stepSize argument has changed. const form2 = container.getElementsByTagName('form')[1]; const {formState: formState2} = await submit(form2); container.innerHTML = ''; const postbackRscStream2 = ReactServerDOMServer.renderToReadableStream( // Note: `.bind` is the same as an inline closure with 'use server' <ClientRef action={serverAction.bind(null, 5)} />, webpackMap, ); const postbackResponse2 = ReactServerDOMClient.createFromReadableStream( postbackRscStream2, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }, ); const postbackSsrStream2 = await ReactDOMServer.renderToReadableStream( postbackResponse2, {formState: formState2}, ); await readIntoContainer(postbackSsrStream2); expect(container.textContent).toBe('171'); }, ); // @gate enableFormActions // @gate enableAsyncActions it('useFormState does not reuse state if action signatures are different', async () => { // This is the same as the previous test, except instead of using bind to // configure the server action (i.e. a closure), it swaps the action. const increaseBy1 = serverExports( async function action(prevState, formData) { return prevState + 1; }, ); const increaseBy5 = serverExports( async function action(prevState, formData) { return prevState + 5; }, ); function Form({action}) { const [count, dispatch] = useFormState(action, 1); return <form action={dispatch}>{count}</form>; } function Client({action}) { return ( <div> <Form action={action} /> <Form action={action} /> <Form action={action} /> </div> ); } const ClientRef = await clientExports(Client); const rscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={increaseBy1} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); expect(container.textContent).toBe('111'); // There are three identical forms. We're going to submit the second one. const form = container.getElementsByTagName('form')[1]; const {formState} = await submit(form); // Simulate an MPA form submission by resetting the container and // rendering again. container.innerHTML = ''; // On the next page, a different server action is rendered. It should not // reuse the state from the previous page. const postbackRscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={increaseBy5} />, webpackMap, ); const postbackResponse = ReactServerDOMClient.createFromReadableStream( postbackRscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }, ); const postbackSsrStream = await ReactDOMServer.renderToReadableStream( postbackResponse, {formState: formState}, ); await readIntoContainer(postbackSsrStream); // The state should not have been preserved because the action signatures // are not the same. expect(container.textContent).toBe('111'); }); // @gate enableFormActions // @gate enableAsyncActions it('when permalink is provided, useFormState compares that instead of the keypath', async () => { const serverAction = serverExports( async function action(prevState, formData) { return prevState + 1; }, ); function Form({action, permalink}) { const [count, dispatch] = useFormState(action, 1, permalink); return <form action={dispatch}>{count}</form>; } function Page1({action, permalink}) { return <Form action={action} permalink={permalink} />; } function Page2({action, permalink}) { return <Form action={action} permalink={permalink} />; } const Page1Ref = await clientExports(Page1); const Page2Ref = await clientExports(Page2); const rscStream = ReactServerDOMServer.renderToReadableStream( <Page1Ref action={serverAction} permalink="/permalink" />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); expect(container.textContent).toBe('1'); // Submit the form const form = container.getElementsByTagName('form')[0]; const {formState} = await submit(form); // Simulate an MPA form submission by resetting the container and // rendering again. container.innerHTML = ''; // On the next page, the same server action is rendered again, but in // a different component tree. However, because a permalink option was // passed, the state should be preserved. const postbackRscStream = ReactServerDOMServer.renderToReadableStream( <Page2Ref action={serverAction} permalink="/permalink" />, webpackMap, ); const postbackResponse = ReactServerDOMClient.createFromReadableStream( postbackRscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }, ); const postbackSsrStream = await ReactDOMServer.renderToReadableStream( postbackResponse, {formState: formState}, ); await readIntoContainer(postbackSsrStream); expect(container.textContent).toBe('2'); // Now submit the form again. This time, the permalink will be different, so // the state is not preserved. const form2 = container.getElementsByTagName('form')[0]; const {formState: formState2} = await submit(form2); container.innerHTML = ''; const postbackRscStream2 = ReactServerDOMServer.renderToReadableStream( <Page1Ref action={serverAction} permalink="/some-other-permalink" />, webpackMap, ); const postbackResponse2 = ReactServerDOMClient.createFromReadableStream( postbackRscStream2, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }, ); const postbackSsrStream2 = await ReactDOMServer.renderToReadableStream( postbackResponse2, {formState: formState2}, ); await readIntoContainer(postbackSsrStream2); // The state was reset because the permalink didn't match expect(container.textContent).toBe('1'); }); // @gate enableFormActions // @gate enableAsyncActions it('useFormState can change the action URL with the `permalink` argument', async () => { const serverAction = serverExports(function action(prevState) { return {state: prevState.count + 1}; }); const initialState = {count: 1}; function Client({action}) { const [state, dispatch] = useFormState( action, initialState, '/permalink', ); return ( <form action={dispatch}> <span>Count: {state.count}</span> </form> ); } const ClientRef = await clientExports(Client); const rscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={serverAction} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.getElementsByTagName('form')[0]; const span = container.getElementsByTagName('span')[0]; expect(span.textContent).toBe('Count: 1'); expect(form.action).toBe('http://localhost/permalink'); }); // @gate enableFormActions // @gate enableAsyncActions it('useFormState `permalink` is coerced to string', async () => { const serverAction = serverExports(function action(prevState) { return {state: prevState.count + 1}; }); class Permalink { toString() { return '/permalink'; } } const permalink = new Permalink(); const initialState = {count: 1}; function Client({action}) { const [state, dispatch] = useFormState(action, initialState, permalink); return ( <form action={dispatch}> <span>Count: {state.count}</span> </form> ); } const ClientRef = await clientExports(Client); const rscStream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={serverAction} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.getElementsByTagName('form')[0]; const span = container.getElementsByTagName('span')[0]; expect(span.textContent).toBe('Count: 1'); expect(form.action).toBe('http://localhost/permalink'); }); });
30.00578
99
0.645065
Python-Penetration-Testing-for-Developers
/** * 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. * * @emails react-core */ 'use strict'; let useSyncExternalStore; let React; let ReactNoop; let Scheduler; let act; let useLayoutEffect; let forwardRef; let useImperativeHandle; let useRef; let useState; let use; let startTransition; let waitFor; let waitForAll; let assertLog; // This tests the native useSyncExternalStore implementation, not the shim. // Tests that apply to both the native implementation and the shim should go // into useSyncExternalStoreShared-test.js. The reason they are separate is // because at some point we may start running the shared tests against vendored // React DOM versions (16, 17, etc) instead of React Noop. describe('useSyncExternalStore', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); useLayoutEffect = React.useLayoutEffect; useImperativeHandle = React.useImperativeHandle; forwardRef = React.forwardRef; useRef = React.useRef; useState = React.useState; use = React.use; useSyncExternalStore = React.useSyncExternalStore; startTransition = React.startTransition; const InternalTestUtils = require('internal-test-utils'); waitFor = InternalTestUtils.waitFor; waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; act = require('internal-test-utils').act; }); function Text({text}) { Scheduler.log(text); return text; } function createExternalStore(initialState) { const listeners = new Set(); let currentState = initialState; return { set(text) { currentState = text; ReactNoop.batchedUpdates(() => { listeners.forEach(listener => listener()); }); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, getState() { return currentState; }, getSubscriberCount() { return listeners.size; }, }; } test( 'detects interleaved mutations during a concurrent read before ' + 'layout effects fire', async () => { const store1 = createExternalStore(0); const store2 = createExternalStore(0); const Child = forwardRef(({store, label}, ref) => { const value = useSyncExternalStore(store.subscribe, store.getState); useImperativeHandle( ref, () => { return value; }, [], ); return <Text text={label + value} />; }); function App({store}) { const refA = useRef(null); const refB = useRef(null); const refC = useRef(null); useLayoutEffect(() => { // This layout effect reads children that depend on an external store. // This demostrates whether the children are consistent when the // layout phase runs. const aText = refA.current; const bText = refB.current; const cText = refC.current; Scheduler.log( `Children observed during layout: A${aText}B${bText}C${cText}`, ); }); return ( <> <Child store={store} ref={refA} label="A" /> <Child store={store} ref={refB} label="B" /> <Child store={store} ref={refC} label="C" /> </> ); } const root = ReactNoop.createRoot(); await act(async () => { // Start a concurrent render that reads from the store, then yield. startTransition(() => { root.render(<App store={store1} />); }); await waitFor(['A0', 'B0']); // During an interleaved event, the store is mutated. store1.set(1); // Then we continue rendering. await waitForAll([ // C reads a newer value from the store than A or B, which means they // are inconsistent. 'C1', // Before committing the layout effects, React detects that the store // has been mutated. So it throws out the entire completed tree and // re-renders the new values. 'A1', 'B1', 'C1', // The layout effects reads consistent children. 'Children observed during layout: A1B1C1', ]); }); // Now we're going test the same thing during an update that // switches stores. await act(async () => { startTransition(() => { root.render(<App store={store2} />); }); // Start a concurrent render that reads from the store, then yield. await waitFor(['A0', 'B0']); // During an interleaved event, the store is mutated. store2.set(1); // Then we continue rendering. await waitForAll([ // C reads a newer value from the store than A or B, which means they // are inconsistent. 'C1', // Before committing the layout effects, React detects that the store // has been mutated. So it throws out the entire completed tree and // re-renders the new values. 'A1', 'B1', 'C1', // The layout effects reads consistent children. 'Children observed during layout: A1B1C1', ]); }); }, ); test('next value is correctly cached when state is dispatched in render phase', async () => { const store = createExternalStore('value:initial'); function App() { const value = useSyncExternalStore(store.subscribe, store.getState); const [sameValue, setSameValue] = useState(value); if (value !== sameValue) setSameValue(value); return <Text text={value} />; } const root = ReactNoop.createRoot(); await act(() => { // Start a render that reads from the store and yields value root.render(<App />); }); assertLog(['value:initial']); await act(() => { store.set('value:changed'); }); assertLog(['value:changed']); // If cached value was updated, we expect a re-render await act(() => { store.set('value:initial'); }); assertLog(['value:initial']); }); test( 'regression: suspending in shell after synchronously patching ' + 'up store mutation', async () => { // Tests a case where a store is mutated during a concurrent event, then // during the sync re-render, a synchronous render is triggered. const store = createExternalStore('Initial'); let resolve; const promise = new Promise(r => { resolve = r; }); function A() { const value = useSyncExternalStore(store.subscribe, store.getState); if (value === 'Updated') { try { use(promise); } catch (x) { Scheduler.log('Suspend A'); throw x; } } return <Text text={'A: ' + value} />; } function B() { const value = useSyncExternalStore(store.subscribe, store.getState); return <Text text={'B: ' + value} />; } function App() { return ( <> <span> <A /> </span> <span> <B /> </span> </> ); } const root = ReactNoop.createRoot(); await act(async () => { // A and B both read from the same store. Partially render A. startTransition(() => root.render(<App />)); // A reads the initial value of the store. await waitFor(['A: Initial']); // Before B renders, mutate the store. store.set('Updated'); }); assertLog([ // B reads the updated value of the store. 'B: Updated', // This should a synchronous re-render of A using the updated value. In // this test, this causes A to suspend. 'Suspend A', ]); // Nothing has committed, because A suspended and no fallback // was provided. expect(root).toMatchRenderedOutput(null); // Resolve the data and finish rendering. await act(() => resolve()); assertLog(['A: Updated', 'B: Updated']); expect(root).toMatchRenderedOutput( <> <span>A: Updated</span> <span>B: Updated</span> </>, ); }, ); });
27.748322
95
0.574481
PenetrationTestingScripts
/** * In order to support reload-and-profile functionality, the renderer needs to be injected before any other scripts. * Since it is a complex file (with imports) we can't just toString() it like we do with the hook itself, * So this entry point (one of the web_accessible_resources) provides a way to eagerly inject it. * The hook will look for the presence of a global __REACT_DEVTOOLS_ATTACH__ and attach an injected renderer early. * The normal case (not a reload-and-profile) will not make use of this entry point though. * * @flow */ import {attach} from 'react-devtools-shared/src/backend/renderer'; import {SESSION_STORAGE_RELOAD_AND_PROFILE_KEY} from 'react-devtools-shared/src/constants'; import {sessionStorageGetItem} from 'react-devtools-shared/src/storage'; if ( sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true' && !window.hasOwnProperty('__REACT_DEVTOOLS_ATTACH__') ) { Object.defineProperty( window, '__REACT_DEVTOOLS_ATTACH__', ({ enumerable: false, // This property needs to be configurable to allow third-party integrations // to attach their own renderer. Note that using third-party integrations // is not officially supported. Use at your own risk. configurable: true, get() { return attach; }, }: Object), ); }
38.529412
116
0.708861
Effective-Python-Penetration-Testing
/** * 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 {ReactContext} from 'shared/ReactTypes'; import type {Thenable} from 'shared/ReactTypes'; import {createContext} from 'react'; import typeof * as ParseHookNamesModule from 'react-devtools-shared/src/hooks/parseHookNames'; export type HookNamesModuleLoaderFunction = () => Thenable<ParseHookNamesModule>; export type Context = HookNamesModuleLoaderFunction | null; // TODO (Webpack 5) Hopefully we can remove this context entirely once the Webpack 5 upgrade is completed. const HookNamesModuleLoaderContext: ReactContext<Context> = createContext<Context>(null); HookNamesModuleLoaderContext.displayName = 'HookNamesModuleLoaderContext'; export default HookNamesModuleLoaderContext;
32.592593
106
0.785872
null
'use strict'; const asyncCopyTo = require('./utils').asyncCopyTo; const chalk = require('chalk'); const resolvePath = require('./utils').resolvePath; const DEFAULT_FB_SOURCE_PATH = '~/fbsource/'; const DEFAULT_WWW_PATH = '~/www/'; const RELATIVE_RN_OSS_PATH = 'xplat/js/react-native-github/Libraries/Renderer/'; const RELATIVE_WWW_PATH = 'html/shared/react/'; async function doSync(buildPath, destPath) { console.log(`${chalk.bgYellow.black(' SYNCING ')} React to ${destPath}`); await asyncCopyTo(buildPath, destPath); console.log(`${chalk.bgGreen.black(' SYNCED ')} React to ${destPath}`); } async function syncReactDom(buildPath, wwwPath) { wwwPath = typeof wwwPath === 'string' ? wwwPath : DEFAULT_WWW_PATH; if (wwwPath.charAt(wwwPath.length - 1) !== '/') { wwwPath += '/'; } const destPath = resolvePath(wwwPath + RELATIVE_WWW_PATH); await doSync(buildPath, destPath); } async function syncReactNativeHelper( buildPath, fbSourcePath, relativeDestPath ) { fbSourcePath = typeof fbSourcePath === 'string' ? fbSourcePath : DEFAULT_FB_SOURCE_PATH; if (fbSourcePath.charAt(fbSourcePath.length - 1) !== '/') { fbSourcePath += '/'; } const destPath = resolvePath(fbSourcePath + relativeDestPath); await doSync(buildPath, destPath); } async function syncReactNative(fbSourcePath) { await syncReactNativeHelper( 'build/react-native', fbSourcePath, RELATIVE_RN_OSS_PATH ); } module.exports = { syncReactDom, syncReactNative, };
24.844828
80
0.698264
owtf
'use strict'; // Fork Start const ReactFlightWebpackPlugin = require('react-server-dom-webpack/plugin'); // Fork End const fs = require('fs'); const {createHash} = require('crypto'); const path = require('path'); const webpack = require('webpack'); const resolve = require('resolve'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent'); const paths = require('./paths'); const modules = require('./modules'); const getClientEnvironment = require('./env'); const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin'); const ForkTsCheckerWebpackPlugin = process.env.TSC_COMPILE_ON_ERROR === 'true' ? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin') : require('react-dev-utils/ForkTsCheckerWebpackPlugin'); const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); const {WebpackManifestPlugin} = require('webpack-manifest-plugin'); function createEnvironmentHash(env) { const hash = createHash('md5'); hash.update(JSON.stringify(env)); return hash.digest('hex'); } // Source maps are resource heavy and can cause out of memory issue for large source files. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime'); const reactRefreshWebpackPluginRuntimeEntry = require.resolve( '@pmmmwh/react-refresh-webpack-plugin' ); const babelRuntimeEntry = require.resolve('babel-preset-react-app'); const babelRuntimeEntryHelpers = require.resolve( '@babel/runtime/helpers/esm/assertThisInitialized', {paths: [babelRuntimeEntry]} ); const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', { paths: [babelRuntimeEntry], }); // Some apps do not need the benefits of saving a web request, so not inlining the chunk // makes for a smoother build process. const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false'; const imageInlineSizeLimit = parseInt( process.env.IMAGE_INLINE_SIZE_LIMIT || '10000' ); // Check if TypeScript is setup const useTypeScript = fs.existsSync(paths.appTsConfig); // Check if Tailwind config exists const useTailwind = fs.existsSync( path.join(paths.appPath, 'tailwind.config.js') ); // Get the path to the uncompiled service worker (if it exists). const swSrc = paths.swSrc; // style files regexes const cssRegex = /\.css$/; const cssModuleRegex = /\.module\.css$/; const sassRegex = /\.(scss|sass)$/; const sassModuleRegex = /\.module\.(scss|sass)$/; const hasJsxRuntime = (() => { if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') { return false; } try { require.resolve('react/jsx-runtime'); return true; } catch (e) { return false; } })(); // This is the production and development configuration. // It is focused on developer experience, fast rebuilds, and a minimal bundle. module.exports = function (webpackEnv) { const isEnvDevelopment = webpackEnv === 'development'; const isEnvProduction = webpackEnv === 'production'; // Variable used for enabling profiling in Production // passed into alias object. Uses a flag if passed into the build command const isEnvProductionProfile = isEnvProduction && process.argv.includes('--profile'); // We will provide `paths.publicUrlOrPath` to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. // Get environment variables to inject into our app. const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)); const shouldUseReactRefresh = env.raw.FAST_REFRESH; // common function to get style loaders const getStyleLoaders = (cssOptions, preProcessor) => { const loaders = [ isEnvDevelopment && require.resolve('style-loader'), { loader: MiniCssExtractPlugin.loader, // css is located in `static/css`, use '../../' to locate index.html folder // in production `paths.publicUrlOrPath` can be a relative path options: paths.publicUrlOrPath.startsWith('.') ? {publicPath: '../../'} : {}, }, { loader: require.resolve('css-loader'), options: cssOptions, }, { // Options for PostCSS as we reference these options twice // Adds vendor prefixing based on your specified browser support in // package.json loader: require.resolve('postcss-loader'), options: { postcssOptions: { // Necessary for external CSS imports to work // https://github.com/facebook/create-react-app/issues/2677 ident: 'postcss', config: false, plugins: !useTailwind ? [ 'postcss-flexbugs-fixes', [ 'postcss-preset-env', { autoprefixer: { flexbox: 'no-2009', }, stage: 3, }, ], // Adds PostCSS Normalize as the reset css with default options, // so that it honors browserslist config in package.json // which in turn let's users customize the target behavior as per their needs. 'postcss-normalize', ] : [ 'tailwindcss', 'postcss-flexbugs-fixes', [ 'postcss-preset-env', { autoprefixer: { flexbox: 'no-2009', }, stage: 3, }, ], ], }, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, }, }, ].filter(Boolean); if (preProcessor) { loaders.push( { loader: require.resolve('resolve-url-loader'), options: { sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, root: paths.appSrc, }, }, { loader: require.resolve(preProcessor), options: { sourceMap: true, }, } ); } return loaders; }; return { target: ['browserslist'], // Webpack noise constrained to errors and warnings stats: 'errors-warnings', mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development', // Stop compilation early in production bail: isEnvProduction, devtool: isEnvProduction ? shouldUseSourceMap ? 'source-map' : false : isEnvDevelopment && 'cheap-module-source-map', // These are the "entry points" to our application. // This means they will be the "root" imports that are included in JS bundle. entry: isEnvProduction ? [paths.appIndexJs] : [ paths.appIndexJs, // HMR client 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', ], output: { // The build folder. path: paths.appBuild, // Add /* filename */ comments to generated require()s in the output. pathinfo: isEnvDevelopment, // There will be one main bundle, and one file per asynchronous chunk. // In development, it does not produce real files. filename: isEnvProduction ? 'static/js/[name].[contenthash:8].js' : isEnvDevelopment && 'static/js/bundle.js', // There are also additional JS chunk files if you use code splitting. chunkFilename: isEnvProduction ? 'static/js/[name].[contenthash:8].chunk.js' : isEnvDevelopment && 'static/js/[name].chunk.js', assetModuleFilename: 'static/media/[name].[hash][ext]', // webpack uses `publicPath` to determine where the app is being served from. // It requires a trailing slash, or the file assets will get an incorrect path. // We inferred the "public path" (such as / or /my-project) from homepage. publicPath: paths.publicUrlOrPath, // Point sourcemap entries to original disk location (format as URL on Windows) devtoolModuleFilenameTemplate: isEnvProduction ? info => path .relative(paths.appSrc, info.absoluteResourcePath) .replace(/\\/g, '/') : isEnvDevelopment && (info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')), }, cache: { type: 'filesystem', version: createEnvironmentHash(env.raw), cacheDirectory: paths.appWebpackCache, store: 'pack', buildDependencies: { defaultWebpack: ['webpack/lib/'], config: [__filename], tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f => fs.existsSync(f) ), }, }, infrastructureLogging: { level: 'none', }, optimization: { minimize: isEnvProduction, minimizer: [ // This is only used in production mode new TerserPlugin({ terserOptions: { parse: { // We want terser to parse ecma 8 code. However, we don't want it // to apply any minification steps that turns valid ecma 5 code // into invalid ecma 5 code. This is why the 'compress' and 'output' // sections only apply transformations that are ecma 5 safe // https://github.com/facebook/create-react-app/pull/4234 ecma: 8, }, compress: { ecma: 5, warnings: false, // Disabled because of an issue with Uglify breaking seemingly valid code: // https://github.com/facebook/create-react-app/issues/2376 // Pending further investigation: // https://github.com/mishoo/UglifyJS2/issues/2011 comparisons: false, // Disabled because of an issue with Terser breaking valid code: // https://github.com/facebook/create-react-app/issues/5250 // Pending further investigation: // https://github.com/terser-js/terser/issues/120 inline: 2, }, mangle: { safari10: true, }, // Added for profiling in devtools keep_classnames: isEnvProductionProfile, keep_fnames: isEnvProductionProfile, output: { ecma: 5, comments: false, // Turned on because emoji and regex is not minified properly using default // https://github.com/facebook/create-react-app/issues/2488 ascii_only: true, }, }, }), // This is only used in production mode new CssMinimizerPlugin(), ], }, resolve: { // This allows you to set a fallback for where webpack should look for modules. // We placed these paths second because we want `node_modules` to "win" // if there are any conflicts. This matches Node resolution mechanism. // https://github.com/facebook/create-react-app/issues/253 modules: ['node_modules', paths.appNodeModules].concat( modules.additionalModulePaths || [] ), // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebook/create-react-app/issues/290 // `web` extension prefixes have been added for better support // for React Native Web. extensions: paths.moduleFileExtensions .map(ext => `.${ext}`) .filter(ext => useTypeScript || !ext.includes('ts')), alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web', // Allows for better profiling with ReactDevTools ...(isEnvProductionProfile && { 'react-dom$': 'react-dom/profiling', 'scheduler/tracing': 'scheduler/tracing-profiling', }), ...(modules.webpackAliases || {}), }, plugins: [ // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, // please link the files into your node_modules/ and let module-resolution kick in. // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc, [ paths.appPackageJson, reactRefreshRuntimeEntry, reactRefreshWebpackPluginRuntimeEntry, babelRuntimeEntry, babelRuntimeEntryHelpers, babelRuntimeRegenerator, ]), ], }, module: { strictExportPresence: true, rules: [ // Handle node_modules packages that contain sourcemaps shouldUseSourceMap && { enforce: 'pre', exclude: /@babel(?:\/|\\{1,2})runtime/, test: /\.(js|mjs|jsx|ts|tsx|css)$/, loader: require.resolve('source-map-loader'), }, { // "oneOf" will traverse all following loaders until one will // match the requirements. When no loader matches it will fall // back to the "file" loader at the end of the loader list. oneOf: [ // TODO: Merge this config once `image/avif` is in the mime-db // https://github.com/jshttp/mime-db { test: [/\.avif$/], type: 'asset', mimetype: 'image/avif', parser: { dataUrlCondition: { maxSize: imageInlineSizeLimit, }, }, }, // "url" loader works like "file" loader except that it embeds assets // smaller than specified limit in bytes as data URLs to avoid requests. // A missing `test` is equivalent to a match. { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], type: 'asset', parser: { dataUrlCondition: { maxSize: imageInlineSizeLimit, }, }, }, { test: /\.svg$/, use: [ { loader: require.resolve('@svgr/webpack'), options: { prettier: false, svgo: false, svgoConfig: { plugins: [{removeViewBox: false}], }, titleProp: true, ref: true, }, }, { loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[hash].[ext]', }, }, ], issuer: { and: [/\.(ts|tsx|js|jsx|md|mdx)$/], }, }, // Process application JS with Babel. // The preset includes JSX, Flow, TypeScript, and some ESnext features. { test: /\.(js|mjs|jsx|ts|tsx)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { customize: require.resolve( 'babel-preset-react-app/webpack-overrides' ), presets: [ [ require.resolve('babel-preset-react-app'), { runtime: hasJsxRuntime ? 'automatic' : 'classic', }, ], ], plugins: [ isEnvDevelopment && shouldUseReactRefresh && require.resolve('react-refresh/babel'), ].filter(Boolean), // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true, // See #6846 for context on why cacheCompression is disabled cacheCompression: false, compact: isEnvProduction, }, }, // Process any JS outside of the app with Babel. // Unlike the application JS, we only compile the standard ES features. { test: /\.(js|mjs)$/, exclude: /@babel(?:\/|\\{1,2})runtime/, loader: require.resolve('babel-loader'), options: { babelrc: false, configFile: false, compact: false, presets: [ [ require.resolve('babel-preset-react-app/dependencies'), {helpers: true}, ], ], cacheDirectory: true, // See #6846 for context on why cacheCompression is disabled cacheCompression: false, // Babel sourcemaps are needed for debugging into node_modules // code. Without the options below, debuggers like VSCode // show incorrect code and set breakpoints on the wrong lines. sourceMaps: shouldUseSourceMap, inputSourceMap: shouldUseSourceMap, }, }, // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader turns CSS into JS modules that inject <style> tags. // In production, we use MiniCSSExtractPlugin to extract that CSS // to a file, but in development "style" loader enables hot editing // of CSS. // By default we support CSS Modules with the extension .module.css { test: cssRegex, exclude: cssModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: { mode: 'icss', }, }), // Don't consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this when webpack adds a warning or an error for this. // See https://github.com/webpack/webpack/issues/6571 sideEffects: true, }, // Adds support for CSS Modules (https://github.com/css-modules/css-modules) // using the extension .module.css { test: cssModuleRegex, use: getStyleLoaders({ importLoaders: 1, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: { mode: 'local', getLocalIdent: getCSSModuleLocalIdent, }, }), }, // Opt-in support for SASS (using .scss or .sass extensions). // By default we support SASS Modules with the // extensions .module.scss or .module.sass { test: sassRegex, exclude: sassModuleRegex, use: getStyleLoaders( { importLoaders: 3, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: { mode: 'icss', }, }, 'sass-loader' ), // Don't consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this when webpack adds a warning or an error for this. // See https://github.com/webpack/webpack/issues/6571 sideEffects: true, }, // Adds support for CSS Modules, but using SASS // using the extension .module.scss or .module.sass { test: sassModuleRegex, use: getStyleLoaders( { importLoaders: 3, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, modules: { mode: 'local', getLocalIdent: getCSSModuleLocalIdent, }, }, 'sass-loader' ), }, // "file" loader makes sure those assets get served by WebpackDevServer. // When you `import` an asset, you get its (virtual) filename. // In production, they would get copied to the `build` folder. // This loader doesn't use a "test" so it will catch all modules // that fall through the other loaders. { // Exclude `js` files to keep "css" loader working as it injects // its runtime that would otherwise be processed through "file" loader. // Also exclude `html` and `json` extensions so they get processed // by webpacks internal loaders. exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/], type: 'asset/resource', }, // ** STOP ** Are you adding a new loader? // Make sure to add the new loader(s) before the "file" loader. ], }, ].filter(Boolean), }, plugins: [ new webpack.HotModuleReplacementPlugin(), // This gives some necessary context to module not found errors, such as // the requesting resource. new ModuleNotFoundPlugin(paths.appPath), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`. // It is absolutely essential that NODE_ENV is set to production // during a production build. // Otherwise React will be compiled in the very slow development mode. new webpack.DefinePlugin(env.stringified), // Experimental hot reloading for React . // https://github.com/facebook/react/tree/main/packages/react-refresh isEnvDevelopment && shouldUseReactRefresh && new ReactRefreshWebpackPlugin({ overlay: false, }), // Watcher doesn't work well if you mistype casing in a path so we use // a plugin that prints an error when you attempt to do this. // See https://github.com/facebook/create-react-app/issues/240 isEnvDevelopment && new CaseSensitivePathsPlugin(), new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: 'static/css/[name].[contenthash:8].css', chunkFilename: 'static/css/[name].[contenthash:8].chunk.css', }), // Generate a manifest containing the required script / css for each entry. new WebpackManifestPlugin({ fileName: 'entrypoint-manifest.json', publicPath: paths.publicUrlOrPath, generate: (seed, files, entrypoints) => { const entrypointFiles = entrypoints.main.filter( fileName => !fileName.endsWith('.map') ); const processedEntrypoints = {}; for (let key in entrypoints) { processedEntrypoints[key] = { js: entrypoints[key].filter( filename => // Include JS assets but ignore hot updates because they're not // safe to include as async script tags. filename.endsWith('.js') && !filename.endsWith('.hot-update.js') ), css: entrypoints[key].filter(filename => filename.endsWith('.css') ), }; } return processedEntrypoints; }, }), // Moment.js is an extremely popular library that bundles large locale files // by default due to how webpack interprets its code. This is a practical // solution that requires the user to opt into importing specific locales. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack // You can remove this if you don't use Moment.js: new webpack.IgnorePlugin({ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/, }), // TypeScript type checking useTypeScript && new ForkTsCheckerWebpackPlugin({ async: isEnvDevelopment, typescript: { typescriptPath: resolve.sync('typescript', { basedir: paths.appNodeModules, }), configOverwrite: { compilerOptions: { sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, skipLibCheck: true, inlineSourceMap: false, declarationMap: false, noEmit: true, incremental: true, tsBuildInfoFile: paths.appTsBuildInfoFile, }, }, context: paths.appPath, diagnosticOptions: { syntactic: true, }, mode: 'write-references', // profile: true, }, issue: { // This one is specifically to match during CI tests, // as micromatch doesn't match // '../cra-template-typescript/template/src/App.tsx' // otherwise. include: [ {file: '../**/src/**/*.{ts,tsx}'}, {file: '**/src/**/*.{ts,tsx}'}, ], exclude: [ {file: '**/src/**/__tests__/**'}, {file: '**/src/**/?(*.){spec|test}.*'}, {file: '**/src/setupProxy.*'}, {file: '**/src/setupTests.*'}, ], }, logger: { infrastructure: 'silent', }, }), // Fork Start new ReactFlightWebpackPlugin({ isServer: false, clientReferences: { directory: './src', recursive: true, include: /\.(js|ts|jsx|tsx)$/, }, }), // Fork End ].filter(Boolean), experiments: { topLevelAwait: true, }, // Turn off performance processing because we utilize // our own hints via the FileSizeReporter performance: false, }; };
38.096454
104
0.553044
cybersecurity-penetration-testing
'use strict'; var b; var l; if (process.env.NODE_ENV === 'production') { b = require('./cjs/react-dom-server.edge.production.min.js'); l = require('./cjs/react-dom-server-legacy.browser.production.min.js'); } else { b = require('./cjs/react-dom-server.edge.development.js'); l = require('./cjs/react-dom-server-legacy.browser.development.js'); } exports.version = b.version; exports.renderToReadableStream = b.renderToReadableStream; exports.renderToNodeStream = b.renderToNodeStream; exports.renderToStaticNodeStream = b.renderToStaticNodeStream; exports.renderToString = l.renderToString; exports.renderToStaticMarkup = l.renderToStaticMarkup; if (b.resume) { exports.resume = b.resume; }
31
73
0.749644
cybersecurity-penetration-testing
/** * 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. * * @emails react-core */ 'use strict'; const React = require('react'); const ReactDOM = require('react-dom'); const ReactTestUtils = require('react-dom/test-utils'); const StrictMode = React.StrictMode; describe('findDOMNode', () => { it('findDOMNode should return null if passed null', () => { expect(ReactDOM.findDOMNode(null)).toBe(null); }); it('findDOMNode should find dom element', () => { class MyNode extends React.Component { render() { return ( <div> <span>Noise</span> </div> ); } } const myNode = ReactTestUtils.renderIntoDocument(<MyNode />); const myDiv = ReactDOM.findDOMNode(myNode); const mySameDiv = ReactDOM.findDOMNode(myDiv); expect(myDiv.tagName).toBe('DIV'); expect(mySameDiv).toBe(myDiv); }); it('findDOMNode should find dom element after an update from null', () => { function Bar({flag}) { if (flag) { return <span>A</span>; } return null; } class MyNode extends React.Component { render() { return <Bar flag={this.props.flag} />; } } const container = document.createElement('div'); const myNodeA = ReactDOM.render(<MyNode />, container); const a = ReactDOM.findDOMNode(myNodeA); expect(a).toBe(null); const myNodeB = ReactDOM.render(<MyNode flag={true} />, container); expect(myNodeA === myNodeB).toBe(true); const b = ReactDOM.findDOMNode(myNodeB); expect(b.tagName).toBe('SPAN'); }); it('findDOMNode should reject random objects', () => { expect(function () { ReactDOM.findDOMNode({foo: 'bar'}); }).toThrowError('Argument appears to not be a ReactComponent. Keys: foo'); }); it('findDOMNode should reject unmounted objects with render func', () => { class Foo extends React.Component { render() { return <div />; } } const container = document.createElement('div'); const inst = ReactDOM.render(<Foo />, container); ReactDOM.unmountComponentAtNode(container); expect(() => ReactDOM.findDOMNode(inst)).toThrowError( 'Unable to find node on an unmounted component.', ); }); it('findDOMNode should not throw an error when called within a component that is not mounted', () => { class Bar extends React.Component { UNSAFE_componentWillMount() { expect(ReactDOM.findDOMNode(this)).toBeNull(); } render() { return <div />; } } expect(() => ReactTestUtils.renderIntoDocument(<Bar />)).not.toThrow(); }); it('findDOMNode should warn if used to find a host component inside StrictMode', () => { let parent = undefined; let child = undefined; class ContainsStrictModeChild extends React.Component { render() { return ( <StrictMode> <div ref={n => (child = n)} /> </StrictMode> ); } } ReactTestUtils.renderIntoDocument( <ContainsStrictModeChild ref={n => (parent = n)} />, ); let match; expect(() => (match = ReactDOM.findDOMNode(parent))).toErrorDev([ 'Warning: findDOMNode is deprecated in StrictMode. ' + 'findDOMNode was passed an instance of ContainsStrictModeChild which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node' + '\n in div (at **)' + '\n in ContainsStrictModeChild (at **)', ]); expect(match).toBe(child); }); it('findDOMNode should warn if passed a component that is inside StrictMode', () => { let parent = undefined; let child = undefined; class IsInStrictMode extends React.Component { render() { return <div ref={n => (child = n)} />; } } ReactTestUtils.renderIntoDocument( <StrictMode> <IsInStrictMode ref={n => (parent = n)} /> </StrictMode>, ); let match; expect(() => (match = ReactDOM.findDOMNode(parent))).toErrorDev([ 'Warning: findDOMNode is deprecated in StrictMode. ' + 'findDOMNode was passed an instance of IsInStrictMode which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node' + '\n in div (at **)' + '\n in IsInStrictMode (at **)', ]); expect(match).toBe(child); }); });
28.670807
109
0.610553
Broken-Droid-Factory
/** * 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. * * @emails react-core */ 'use strict'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; global.TextDecoder = require('util').TextDecoder; // Don't wait before processing work on the server. // TODO: we can replace this with FlightServer.act(). global.setImmediate = cb => cb(); let act; let use; let clientExports; let turbopackMap; let Stream; let React; let ReactDOMClient; let ReactServerDOMServer; let ReactServerDOMClient; let Suspense; describe('ReactFlightDOM', () => { beforeEach(() => { // For this first reset we are going to load the dom-node version of react-server-dom-turbopack/server // This can be thought of as essentially being the React Server Components scope with react-server // condition jest.resetModules(); // Simulate the condition resolution jest.mock('react-server-dom-turbopack/server', () => require('react-server-dom-turbopack/server.node.unbundled'), ); jest.mock('react', () => require('react/react.shared-subset')); const TurbopackMock = require('./utils/TurbopackMock'); clientExports = TurbopackMock.clientExports; turbopackMap = TurbopackMock.turbopackMap; ReactServerDOMServer = require('react-server-dom-turbopack/server'); // This reset is to load modules for the SSR/Browser scope. jest.resetModules(); __unmockReact(); act = require('internal-test-utils').act; Stream = require('stream'); React = require('react'); use = React.use; Suspense = React.Suspense; ReactDOMClient = require('react-dom/client'); ReactServerDOMClient = require('react-server-dom-turbopack/client'); }); function getTestStream() { const writable = new Stream.PassThrough(); const readable = new ReadableStream({ start(controller) { writable.on('data', chunk => { controller.enqueue(chunk); }); writable.on('end', () => { controller.close(); }); }, }); return { readable, writable, }; } it('should resolve HTML using Node streams', async () => { function Text({children}) { return <span>{children}</span>; } function HTML() { return ( <div> <Text>hello</Text> <Text>world</Text> </div> ); } function App() { const model = { html: <HTML />, }; return model; } const {writable, readable} = getTestStream(); const {pipe} = ReactServerDOMServer.renderToPipeableStream( <App />, turbopackMap, ); pipe(writable); const response = ReactServerDOMClient.createFromReadableStream(readable); const model = await response; expect(model).toEqual({ html: ( <div> <span>hello</span> <span>world</span> </div> ), }); }); it('should resolve the root', async () => { // Model function Text({children}) { return <span>{children}</span>; } function HTML() { return ( <div> <Text>hello</Text> <Text>world</Text> </div> ); } function RootModel() { return { html: <HTML />, }; } // View function Message({response}) { return <section>{use(response).html}</section>; } function App({response}) { return ( <Suspense fallback={<h1>Loading...</h1>}> <Message response={response} /> </Suspense> ); } const {writable, readable} = getTestStream(); const {pipe} = ReactServerDOMServer.renderToPipeableStream( <RootModel />, turbopackMap, ); pipe(writable); const response = ReactServerDOMClient.createFromReadableStream(readable); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App response={response} />); }); expect(container.innerHTML).toBe( '<section><div><span>hello</span><span>world</span></div></section>', ); }); it('should unwrap async module references', async () => { const AsyncModule = Promise.resolve(function AsyncModule({text}) { return 'Async: ' + text; }); const AsyncModule2 = Promise.resolve({ exportName: 'Module', }); function Print({response}) { return <p>{use(response)}</p>; } function App({response}) { return ( <Suspense fallback={<h1>Loading...</h1>}> <Print response={response} /> </Suspense> ); } const AsyncModuleRef = await clientExports(AsyncModule); const AsyncModuleRef2 = await clientExports(AsyncModule2); const {writable, readable} = getTestStream(); const {pipe} = ReactServerDOMServer.renderToPipeableStream( <AsyncModuleRef text={AsyncModuleRef2.exportName} />, turbopackMap, ); pipe(writable); const response = ReactServerDOMClient.createFromReadableStream(readable); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App response={response} />); }); expect(container.innerHTML).toBe('<p>Async: Module</p>'); }); });
25.511962
106
0.617329
cybersecurity-penetration-testing
/** * 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 {EventPriority} from 'react-reconciler/src/ReactEventPriorities'; import type {AnyNativeEvent} from '../events/PluginModuleType'; import type {Fiber, FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import type {Container, SuspenseInstance} from '../client/ReactFiberConfigDOM'; import type {DOMEventName} from '../events/DOMEventNames'; import { isDiscreteEventThatRequiresHydration, clearIfContinuousEvent, queueIfContinuousEvent, } from './ReactDOMEventReplaying'; import {attemptSynchronousHydration} from 'react-reconciler/src/ReactFiberReconciler'; import { getNearestMountedFiber, getContainerFromFiber, getSuspenseInstanceFromFiber, } from 'react-reconciler/src/ReactFiberTreeReflection'; import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags'; import {type EventSystemFlags, IS_CAPTURE_PHASE} from './EventSystemFlags'; import getEventTarget from './getEventTarget'; import { getInstanceFromNode, getClosestInstanceFromNode, } from '../client/ReactDOMComponentTree'; import {dispatchEventForPluginEventSystem} from './DOMPluginEventSystem'; import { getCurrentPriorityLevel as getCurrentSchedulerPriorityLevel, IdlePriority as IdleSchedulerPriority, ImmediatePriority as ImmediateSchedulerPriority, LowPriority as LowSchedulerPriority, NormalPriority as NormalSchedulerPriority, UserBlockingPriority as UserBlockingSchedulerPriority, } from 'react-reconciler/src/Scheduler'; import { DiscreteEventPriority, ContinuousEventPriority, DefaultEventPriority, IdleEventPriority, getCurrentUpdatePriority, setCurrentUpdatePriority, } from 'react-reconciler/src/ReactEventPriorities'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import {isRootDehydrated} from 'react-reconciler/src/ReactFiberShellHydration'; const {ReactCurrentBatchConfig} = ReactSharedInternals; // TODO: can we stop exporting these? let _enabled: boolean = true; // This is exported in FB builds for use by legacy FB layer infra. // We'd like to remove this but it's not clear if this is safe. export function setEnabled(enabled: ?boolean): void { _enabled = !!enabled; } export function isEnabled(): boolean { return _enabled; } export function createEventListenerWrapper( targetContainer: EventTarget, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, ): Function { return dispatchEvent.bind( null, domEventName, eventSystemFlags, targetContainer, ); } export function createEventListenerWrapperWithPriority( targetContainer: EventTarget, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, ): Function { const eventPriority = getEventPriority(domEventName); let listenerWrapper; switch (eventPriority) { case DiscreteEventPriority: listenerWrapper = dispatchDiscreteEvent; break; case ContinuousEventPriority: listenerWrapper = dispatchContinuousEvent; break; case DefaultEventPriority: default: listenerWrapper = dispatchEvent; break; } return listenerWrapper.bind( null, domEventName, eventSystemFlags, targetContainer, ); } function dispatchDiscreteEvent( domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, container: EventTarget, nativeEvent: AnyNativeEvent, ) { const previousPriority = getCurrentUpdatePriority(); const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = null; try { setCurrentUpdatePriority(DiscreteEventPriority); dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; } } function dispatchContinuousEvent( domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, container: EventTarget, nativeEvent: AnyNativeEvent, ) { const previousPriority = getCurrentUpdatePriority(); const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = null; try { setCurrentUpdatePriority(ContinuousEventPriority); dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; } } export function dispatchEvent( domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, nativeEvent: AnyNativeEvent, ): void { if (!_enabled) { return; } let blockedOn = findInstanceBlockingEvent(nativeEvent); if (blockedOn === null) { dispatchEventForPluginEventSystem( domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer, ); clearIfContinuousEvent(domEventName, nativeEvent); return; } if ( queueIfContinuousEvent( blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent, ) ) { nativeEvent.stopPropagation(); return; } // We need to clear only if we didn't queue because // queueing is accumulative. clearIfContinuousEvent(domEventName, nativeEvent); if ( eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName) ) { while (blockedOn !== null) { const fiber = getInstanceFromNode(blockedOn); if (fiber !== null) { attemptSynchronousHydration(fiber); } const nextBlockedOn = findInstanceBlockingEvent(nativeEvent); if (nextBlockedOn === null) { dispatchEventForPluginEventSystem( domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer, ); } if (nextBlockedOn === blockedOn) { break; } blockedOn = nextBlockedOn; } if (blockedOn !== null) { nativeEvent.stopPropagation(); } return; } // This is not replayable so we'll invoke it but without a target, // in case the event system needs to trace it. dispatchEventForPluginEventSystem( domEventName, eventSystemFlags, nativeEvent, null, targetContainer, ); } export function findInstanceBlockingEvent( nativeEvent: AnyNativeEvent, ): null | Container | SuspenseInstance { const nativeEventTarget = getEventTarget(nativeEvent); return findInstanceBlockingTarget(nativeEventTarget); } export let return_targetInst: null | Fiber = null; // Returns a SuspenseInstance or Container if it's blocked. // The return_targetInst field above is conceptually part of the return value. export function findInstanceBlockingTarget( targetNode: Node, ): null | Container | SuspenseInstance { // TODO: Warn if _enabled is false. return_targetInst = null; let targetInst = getClosestInstanceFromNode(targetNode); if (targetInst !== null) { const nearestMounted = getNearestMountedFiber(targetInst); if (nearestMounted === null) { // This tree has been unmounted already. Dispatch without a target. targetInst = null; } else { const tag = nearestMounted.tag; if (tag === SuspenseComponent) { const instance = getSuspenseInstanceFromFiber(nearestMounted); if (instance !== null) { // Queue the event to be replayed later. Abort dispatching since we // don't want this event dispatched twice through the event system. // TODO: If this is the first discrete event in the queue. Schedule an increased // priority for this boundary. return instance; } // This shouldn't happen, something went wrong but to avoid blocking // the whole system, dispatch the event without a target. // TODO: Warn. targetInst = null; } else if (tag === HostRoot) { const root: FiberRoot = nearestMounted.stateNode; if (isRootDehydrated(root)) { // If this happens during a replay something went wrong and it might block // the whole system. return getContainerFromFiber(nearestMounted); } targetInst = null; } else if (nearestMounted !== targetInst) { // If we get an event (ex: img onload) before committing that // component's mount, ignore it for now (that is, treat it as if it was an // event on a non-React tree). We might also consider queueing events and // dispatching them after the mount. targetInst = null; } } } return_targetInst = targetInst; // We're not blocked on anything. return null; } export function getEventPriority(domEventName: DOMEventName): EventPriority { switch (domEventName) { // Used by SimpleEventPlugin: case 'cancel': case 'click': case 'close': case 'contextmenu': case 'copy': case 'cut': case 'auxclick': case 'dblclick': case 'dragend': case 'dragstart': case 'drop': case 'focusin': case 'focusout': case 'input': case 'invalid': case 'keydown': case 'keypress': case 'keyup': case 'mousedown': case 'mouseup': case 'paste': case 'pause': case 'play': case 'pointercancel': case 'pointerdown': case 'pointerup': case 'ratechange': case 'reset': case 'resize': case 'seeked': case 'submit': case 'touchcancel': case 'touchend': case 'touchstart': case 'volumechange': // Used by polyfills: (fall through) case 'change': case 'selectionchange': case 'textInput': case 'compositionstart': case 'compositionend': case 'compositionupdate': // Only enableCreateEventHandleAPI: (fall through) case 'beforeblur': case 'afterblur': // Not used by React but could be by user code: (fall through) case 'beforeinput': case 'blur': case 'fullscreenchange': case 'focus': case 'hashchange': case 'popstate': case 'select': case 'selectstart': return DiscreteEventPriority; case 'drag': case 'dragenter': case 'dragexit': case 'dragleave': case 'dragover': case 'mousemove': case 'mouseout': case 'mouseover': case 'pointermove': case 'pointerout': case 'pointerover': case 'scroll': case 'toggle': case 'touchmove': case 'wheel': // Not used by React but could be by user code: (fall through) case 'mouseenter': case 'mouseleave': case 'pointerenter': case 'pointerleave': return ContinuousEventPriority; case 'message': { // We might be in the Scheduler callback. // Eventually this mechanism will be replaced by a check // of the current priority on the native scheduler. const schedulerPriority = getCurrentSchedulerPriorityLevel(); switch (schedulerPriority) { case ImmediateSchedulerPriority: return DiscreteEventPriority; case UserBlockingSchedulerPriority: return ContinuousEventPriority; case NormalSchedulerPriority: case LowSchedulerPriority: // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration. return DefaultEventPriority; case IdleSchedulerPriority: return IdleEventPriority; default: return DefaultEventPriority; } } default: return DefaultEventPriority; } }
28.552163
90
0.703005
null
/** * 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'; export * from '../ReactFlightServerConfigBundlerCustom'; export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM'; export const supportsRequestStorage = false; export const requestStorage: AsyncLocalStorage<Request> = (null: any); export * from '../ReactFlightServerConfigDebugNoop';
29.157895
73
0.76049
PenetrationTestingScripts
/** * 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 */ describe('Store', () => { let React; let ReactDOM; let ReactDOMClient; let agent; let act; let actAsync; let bridge; let getRendererID; let legacyRender; let store; let withErrorsOrWarningsIgnored; beforeEach(() => { agent = global.agent; bridge = global.bridge; store = global.store; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); const utils = require('./utils'); act = utils.act; actAsync = utils.actAsync; getRendererID = utils.getRendererID; legacyRender = utils.legacyRender; withErrorsOrWarningsIgnored = utils.withErrorsOrWarningsIgnored; }); // @reactVersion >= 18.0 it('should not allow a root node to be collapsed', () => { const Component = () => <div>Hi</div>; act(() => legacyRender(<Component count={4} />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] <Component> `); expect(store.roots).toHaveLength(1); const rootID = store.roots[0]; expect(() => store.toggleIsCollapsed(rootID, true)).toThrow( 'Root nodes cannot be collapsed', ); }); // @reactVersion >= 18.0 it('should properly handle a root with no visible nodes', () => { const Root = ({children}) => children; const container = document.createElement('div'); act(() => legacyRender(<Root>{null}</Root>, container)); expect(store).toMatchInlineSnapshot(` [root] <Root> `); act(() => legacyRender(<div />, container)); expect(store).toMatchInlineSnapshot(`[root]`); }); // This test is not the same cause as what's reported on GitHub, // but the resulting behavior (owner mounting after descendant) is the same. // Thec ase below is admittedly contrived and relies on side effects. // I'mnot yet sure of how to reduce the GitHub reported production case to a test though. // See https://github.com/facebook/react/issues/21445 // @reactVersion >= 18.0 it('should handle when a component mounts before its owner', () => { const promise = new Promise(resolve => {}); let Dynamic = null; const Owner = () => { Dynamic = <Child />; throw promise; }; const Parent = () => { return Dynamic; }; const Child = () => null; const container = document.createElement('div'); act(() => legacyRender( <> <React.Suspense fallback="Loading..."> <Owner /> </React.Suspense> <Parent /> </>, container, ), ); expect(store).toMatchInlineSnapshot(` [root] <Suspense> ▾ <Parent> <Child> `); }); // @reactVersion >= 18.0 it('should handle multibyte character strings', () => { const Component = () => null; Component.displayName = '🟩💜🔵'; const container = document.createElement('div'); act(() => legacyRender(<Component />, container)); expect(store).toMatchInlineSnapshot(` [root] <🟩💜🔵> `); }); describe('StrictMode compliance', () => { it('should mark strict root elements as strict', () => { const App = () => <Component />; const Component = () => null; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container, { unstable_strictMode: true, }); act(() => { root.render(<App />); }); expect(store.getElementAtIndex(0).isStrictModeNonCompliant).toBe(false); expect(store.getElementAtIndex(1).isStrictModeNonCompliant).toBe(false); }); // @reactVersion >= 18.0 it('should mark non strict root elements as not strict', () => { const App = () => <Component />; const Component = () => null; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => { root.render(<App />); }); expect(store.getElementAtIndex(0).isStrictModeNonCompliant).toBe(true); expect(store.getElementAtIndex(1).isStrictModeNonCompliant).toBe(true); }); it('should mark StrictMode subtree elements as strict', () => { const App = () => ( <React.StrictMode> <Component /> </React.StrictMode> ); const Component = () => null; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => { root.render(<App />); }); expect(store.getElementAtIndex(0).isStrictModeNonCompliant).toBe(true); expect(store.getElementAtIndex(1).isStrictModeNonCompliant).toBe(false); }); }); describe('collapseNodesByDefault:false', () => { beforeEach(() => { store.collapseNodesByDefault = false; }); // @reactVersion >= 18.0 it('should support mount and update operations', () => { const Grandparent = ({count}) => ( <React.Fragment> <Parent count={count} /> <Parent count={count} /> </React.Fragment> ); const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const container = document.createElement('div'); act(() => legacyRender(<Grandparent count={4} />, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> <Child key="3"> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> <Child key="3"> `); act(() => legacyRender(<Grandparent count={2} />, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> ▾ <Parent> <Child key="0"> <Child key="1"> `); act(() => ReactDOM.unmountComponentAtNode(container)); expect(store).toMatchInlineSnapshot(``); }); // @reactVersion >= 18.0 it('should support mount and update operations for multiple roots', () => { const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const containerA = document.createElement('div'); const containerB = document.createElement('div'); act(() => { legacyRender(<Parent key="A" count={3} />, containerA); legacyRender(<Parent key="B" count={2} />, containerB); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <Parent key="A"> <Child key="0"> <Child key="1"> <Child key="2"> [root] ▾ <Parent key="B"> <Child key="0"> <Child key="1"> `); act(() => { legacyRender(<Parent key="A" count={4} />, containerA); legacyRender(<Parent key="B" count={1} />, containerB); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <Parent key="A"> <Child key="0"> <Child key="1"> <Child key="2"> <Child key="3"> [root] ▾ <Parent key="B"> <Child key="0"> `); act(() => ReactDOM.unmountComponentAtNode(containerB)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Parent key="A"> <Child key="0"> <Child key="1"> <Child key="2"> <Child key="3"> `); act(() => ReactDOM.unmountComponentAtNode(containerA)); expect(store).toMatchInlineSnapshot(``); }); // @reactVersion >= 18.0 it('should filter DOM nodes from the store tree', () => { const Grandparent = () => ( <div> <div> <Parent /> </div> <Parent /> </div> ); const Parent = () => ( <div> <Child /> </div> ); const Child = () => <div>Hi!</div>; act(() => legacyRender(<Grandparent count={4} />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> ▾ <Parent> <Child> `); }); // @reactVersion >= 18.0 it('should display Suspense nodes properly in various states', () => { const Loading = () => <div>Loading...</div>; const SuspendingComponent = () => { throw new Promise(() => {}); }; const Component = () => { return <div>Hello</div>; }; const Wrapper = ({shouldSuspense}) => ( <React.Fragment> <Component key="Outside" /> <React.Suspense fallback={<Loading />}> {shouldSuspense ? ( <SuspendingComponent /> ) : ( <Component key="Inside" /> )} </React.Suspense> </React.Fragment> ); const container = document.createElement('div'); act(() => legacyRender(<Wrapper shouldSuspense={true} />, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Loading> `); act(() => { legacyRender(<Wrapper shouldSuspense={false} />, container); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Inside"> `); }); // @reactVersion >= 18.0 it('should support nested Suspense nodes', () => { const Component = () => null; const Loading = () => <div>Loading...</div>; const Never = () => { throw new Promise(() => {}); }; const Wrapper = ({ suspendFirst = false, suspendSecond = false, suspendParent = false, }) => ( <React.Fragment> <Component key="Outside" /> <React.Suspense fallback={<Loading key="Parent Fallback" />}> <Component key="Unrelated at Start" /> <React.Suspense fallback={<Loading key="Suspense 1 Fallback" />}> {suspendFirst ? ( <Never /> ) : ( <Component key="Suspense 1 Content" /> )} </React.Suspense> <React.Suspense fallback={<Loading key="Suspense 2 Fallback" />}> {suspendSecond ? ( <Never /> ) : ( <Component key="Suspense 2 Content" /> )} </React.Suspense> <React.Suspense fallback={<Loading key="Suspense 3 Fallback" />}> <Never /> </React.Suspense> {suspendParent && <Never />} <Component key="Unrelated at End" /> </React.Suspense> </React.Fragment> ); const container = document.createElement('div'); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={false} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Component key="Suspense 1 Content"> ▾ <Suspense> <Component key="Suspense 2 Content"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={false} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Loading key="Suspense 1 Fallback"> ▾ <Suspense> <Component key="Suspense 2 Content"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={true} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Component key="Suspense 1 Content"> ▾ <Suspense> <Loading key="Suspense 2 Fallback"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={false} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Loading key="Suspense 1 Fallback"> ▾ <Suspense> <Component key="Suspense 2 Content"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => legacyRender( <Wrapper suspendParent={true} suspendFirst={true} suspendSecond={false} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Loading key="Parent Fallback"> `); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={true} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Loading key="Suspense 1 Fallback"> ▾ <Suspense> <Loading key="Suspense 2 Fallback"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={false} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Component key="Suspense 1 Content"> ▾ <Suspense> <Component key="Suspense 2 Content"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); const rendererID = getRendererID(); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(4), rendererID, forceFallback: true, }), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Loading key="Suspense 1 Fallback"> ▾ <Suspense> <Component key="Suspense 2 Content"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(2), rendererID, forceFallback: true, }), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Loading key="Parent Fallback"> `); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={true} suspendSecond={true} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Loading key="Parent Fallback"> `); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(2), rendererID, forceFallback: false, }), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Loading key="Suspense 1 Fallback"> ▾ <Suspense> <Loading key="Suspense 2 Fallback"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => agent.overrideSuspense({ id: store.getElementIDAtIndex(4), rendererID, forceFallback: false, }), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Loading key="Suspense 1 Fallback"> ▾ <Suspense> <Loading key="Suspense 2 Fallback"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); act(() => legacyRender( <Wrapper suspendParent={false} suspendFirst={false} suspendSecond={false} />, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Unrelated at Start"> ▾ <Suspense> <Component key="Suspense 1 Content"> ▾ <Suspense> <Component key="Suspense 2 Content"> ▾ <Suspense> <Loading key="Suspense 3 Fallback"> <Component key="Unrelated at End"> `); }); it('should display a partially rendered SuspenseList', () => { const Loading = () => <div>Loading...</div>; const SuspendingComponent = () => { throw new Promise(() => {}); }; const Component = () => { return <div>Hello</div>; }; const Wrapper = ({shouldSuspense}) => ( <React.Fragment> <React.unstable_SuspenseList revealOrder="forwards" tail="collapsed"> <Component key="A" /> <React.Suspense fallback={<Loading />}> {shouldSuspense ? <SuspendingComponent /> : <Component key="B" />} </React.Suspense> <Component key="C" /> </React.unstable_SuspenseList> </React.Fragment> ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => { root.render(<Wrapper shouldSuspense={true} />); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> ▾ <SuspenseList> <Component key="A"> ▾ <Suspense> <Loading> `); act(() => { root.render(<Wrapper shouldSuspense={false} />); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> ▾ <SuspenseList> <Component key="A"> ▾ <Suspense> <Component key="B"> <Component key="C"> `); }); // @reactVersion >= 18.0 it('should support collapsing parts of the tree', () => { const Grandparent = ({count}) => ( <React.Fragment> <Parent count={count} /> <Parent count={count} /> </React.Fragment> ); const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; act(() => legacyRender(<Grandparent count={2} />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> ▾ <Parent> <Child key="0"> <Child key="1"> `); const grandparentID = store.getElementIDAtIndex(0); const parentOneID = store.getElementIDAtIndex(1); const parentTwoID = store.getElementIDAtIndex(4); act(() => store.toggleIsCollapsed(parentOneID, true)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▸ <Parent> ▾ <Parent> <Child key="0"> <Child key="1"> `); act(() => store.toggleIsCollapsed(parentTwoID, true)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▸ <Parent> ▸ <Parent> `); act(() => store.toggleIsCollapsed(parentOneID, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> ▸ <Parent> `); act(() => store.toggleIsCollapsed(grandparentID, true)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Grandparent> `); act(() => store.toggleIsCollapsed(grandparentID, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> ▸ <Parent> `); }); // @reactVersion >= 18.0 it('should support reordering of children', () => { const Root = ({children}) => children; const Component = () => null; const Foo = () => [<Component key="0" />]; const Bar = () => [<Component key="0" />, <Component key="1" />]; const foo = <Foo key="foo" />; const bar = <Bar key="bar" />; const container = document.createElement('div'); act(() => legacyRender(<Root>{[foo, bar]}</Root>, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Root> ▾ <Foo key="foo"> <Component key="0"> ▾ <Bar key="bar"> <Component key="0"> <Component key="1"> `); act(() => legacyRender(<Root>{[bar, foo]}</Root>, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Root> ▾ <Bar key="bar"> <Component key="0"> <Component key="1"> ▾ <Foo key="foo"> <Component key="0"> `); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), true)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Root> `); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Root> ▾ <Bar key="bar"> <Component key="0"> <Component key="1"> ▾ <Foo key="foo"> <Component key="0"> `); }); }); describe('collapseNodesByDefault:true', () => { beforeEach(() => { store.collapseNodesByDefault = true; }); // @reactVersion >= 18.0 it('should support mount and update operations', () => { const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const container = document.createElement('div'); act(() => legacyRender( <React.Fragment> <Parent count={1} /> <Parent count={3} /> </React.Fragment>, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▸ <Parent> ▸ <Parent> `); act(() => legacyRender( <React.Fragment> <Parent count={2} /> <Parent count={1} /> </React.Fragment>, container, ), ); expect(store).toMatchInlineSnapshot(` [root] ▸ <Parent> ▸ <Parent> `); act(() => ReactDOM.unmountComponentAtNode(container)); expect(store).toMatchInlineSnapshot(``); }); // @reactVersion >= 18.0 it('should support mount and update operations for multiple roots', () => { const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; const containerA = document.createElement('div'); const containerB = document.createElement('div'); act(() => { legacyRender(<Parent key="A" count={3} />, containerA); legacyRender(<Parent key="B" count={2} />, containerB); }); expect(store).toMatchInlineSnapshot(` [root] ▸ <Parent key="A"> [root] ▸ <Parent key="B"> `); act(() => { legacyRender(<Parent key="A" count={4} />, containerA); legacyRender(<Parent key="B" count={1} />, containerB); }); expect(store).toMatchInlineSnapshot(` [root] ▸ <Parent key="A"> [root] ▸ <Parent key="B"> `); act(() => ReactDOM.unmountComponentAtNode(containerB)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Parent key="A"> `); act(() => ReactDOM.unmountComponentAtNode(containerA)); expect(store).toMatchInlineSnapshot(``); }); // @reactVersion >= 18.0 it('should filter DOM nodes from the store tree', () => { const Grandparent = () => ( <div> <div> <Parent /> </div> <Parent /> </div> ); const Parent = () => ( <div> <Child /> </div> ); const Child = () => <div>Hi!</div>; act(() => legacyRender(<Grandparent count={4} />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] ▸ <Grandparent> `); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▸ <Parent> ▸ <Parent> `); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(1), false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> ▸ <Parent> `); }); // @reactVersion >= 18.0 it('should display Suspense nodes properly in various states', () => { const Loading = () => <div>Loading...</div>; const SuspendingComponent = () => { throw new Promise(() => {}); }; const Component = () => { return <div>Hello</div>; }; const Wrapper = ({shouldSuspense}) => ( <React.Fragment> <Component key="Outside" /> <React.Suspense fallback={<Loading />}> {shouldSuspense ? ( <SuspendingComponent /> ) : ( <Component key="Inside" /> )} </React.Suspense> </React.Fragment> ); const container = document.createElement('div'); act(() => legacyRender(<Wrapper shouldSuspense={true} />, container)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Wrapper> `); // This test isn't meaningful unless we expand the suspended tree act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(2), false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Loading> `); act(() => { legacyRender(<Wrapper shouldSuspense={false} />, container); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> <Component key="Outside"> ▾ <Suspense> <Component key="Inside"> `); }); // @reactVersion >= 18.0 it('should support expanding parts of the tree', () => { const Grandparent = ({count}) => ( <React.Fragment> <Parent count={count} /> <Parent count={count} /> </React.Fragment> ); const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => <div>Hi!</div>; act(() => legacyRender(<Grandparent count={2} />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] ▸ <Grandparent> `); const grandparentID = store.getElementIDAtIndex(0); act(() => store.toggleIsCollapsed(grandparentID, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▸ <Parent> ▸ <Parent> `); const parentOneID = store.getElementIDAtIndex(1); const parentTwoID = store.getElementIDAtIndex(2); act(() => store.toggleIsCollapsed(parentOneID, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> ▸ <Parent> `); act(() => store.toggleIsCollapsed(parentTwoID, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> ▾ <Parent> <Child key="0"> <Child key="1"> `); act(() => store.toggleIsCollapsed(parentOneID, true)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▸ <Parent> ▾ <Parent> <Child key="0"> <Child key="1"> `); act(() => store.toggleIsCollapsed(parentTwoID, true)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▸ <Parent> ▸ <Parent> `); act(() => store.toggleIsCollapsed(grandparentID, true)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Grandparent> `); }); // @reactVersion >= 18.0 it('should support expanding deep parts of the tree', () => { const Wrapper = ({forwardedRef}) => ( <Nested depth={3} forwardedRef={forwardedRef} /> ); const Nested = ({depth, forwardedRef}) => depth > 0 ? ( <Nested depth={depth - 1} forwardedRef={forwardedRef} /> ) : ( <div ref={forwardedRef} /> ); const ref = React.createRef(); act(() => legacyRender( <Wrapper forwardedRef={ref} />, document.createElement('div'), ), ); expect(store).toMatchInlineSnapshot(` [root] ▸ <Wrapper> `); const deepestedNodeID = agent.getIDForNode(ref.current); act(() => store.toggleIsCollapsed(deepestedNodeID, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> ▾ <Nested> ▾ <Nested> ▾ <Nested> <Nested> `); const rootID = store.getElementIDAtIndex(0); act(() => store.toggleIsCollapsed(rootID, true)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Wrapper> `); act(() => store.toggleIsCollapsed(rootID, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> ▾ <Nested> ▾ <Nested> ▾ <Nested> <Nested> `); const id = store.getElementIDAtIndex(1); act(() => store.toggleIsCollapsed(id, true)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> ▸ <Nested> `); act(() => store.toggleIsCollapsed(id, false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Wrapper> ▾ <Nested> ▾ <Nested> ▾ <Nested> <Nested> `); }); // @reactVersion >= 18.0 it('should support reordering of children', () => { const Root = ({children}) => children; const Component = () => null; const Foo = () => [<Component key="0" />]; const Bar = () => [<Component key="0" />, <Component key="1" />]; const foo = <Foo key="foo" />; const bar = <Bar key="bar" />; const container = document.createElement('div'); act(() => legacyRender(<Root>{[foo, bar]}</Root>, container)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Root> `); act(() => legacyRender(<Root>{[bar, foo]}</Root>, container)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Root> `); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Root> ▸ <Bar key="bar"> ▸ <Foo key="foo"> `); act(() => { store.toggleIsCollapsed(store.getElementIDAtIndex(2), false); store.toggleIsCollapsed(store.getElementIDAtIndex(1), false); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <Root> ▾ <Bar key="bar"> <Component key="0"> <Component key="1"> ▾ <Foo key="foo"> <Component key="0"> `); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), true)); expect(store).toMatchInlineSnapshot(` [root] ▸ <Root> `); }); // @reactVersion >= 18.0 it('should not add new nodes when suspense is toggled', () => { const SuspenseTree = () => { return ( <React.Suspense fallback={<Fallback>Loading outer</Fallback>}> <Parent /> </React.Suspense> ); }; const Fallback = () => null; const Parent = () => <Child />; const Child = () => null; act(() => legacyRender(<SuspenseTree />, document.createElement('div'))); expect(store).toMatchInlineSnapshot(` [root] ▸ <SuspenseTree> `); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(0), false)); act(() => store.toggleIsCollapsed(store.getElementIDAtIndex(1), false)); expect(store).toMatchInlineSnapshot(` [root] ▾ <SuspenseTree> ▾ <Suspense> ▸ <Parent> `); const rendererID = getRendererID(); const suspenseID = store.getElementIDAtIndex(1); act(() => agent.overrideSuspense({ id: suspenseID, rendererID, forceFallback: true, }), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <SuspenseTree> ▾ <Suspense> <Fallback> `); act(() => agent.overrideSuspense({ id: suspenseID, rendererID, forceFallback: false, }), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <SuspenseTree> ▾ <Suspense> ▸ <Parent> `); }); }); describe('getIndexOfElementID', () => { beforeEach(() => { store.collapseNodesByDefault = false; }); // @reactVersion >= 18.0 it('should support a single root with a single child', () => { const Grandparent = () => ( <React.Fragment> <Parent /> <Parent /> </React.Fragment> ); const Parent = () => <Child />; const Child = () => null; act(() => legacyRender(<Grandparent />, document.createElement('div'))); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); // @reactVersion >= 18.0 it('should support multiple roots with one children each', () => { const Grandparent = () => <Parent />; const Parent = () => <Child />; const Child = () => null; act(() => { legacyRender(<Grandparent />, document.createElement('div')); legacyRender(<Grandparent />, document.createElement('div')); }); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); // @reactVersion >= 18.0 it('should support a single root with multiple top level children', () => { const Grandparent = () => <Parent />; const Parent = () => <Child />; const Child = () => null; act(() => legacyRender( <React.Fragment> <Grandparent /> <Grandparent /> </React.Fragment>, document.createElement('div'), ), ); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); // @reactVersion >= 18.0 it('should support multiple roots with multiple top level children', () => { const Grandparent = () => <Parent />; const Parent = () => <Child />; const Child = () => null; act(() => { legacyRender( <React.Fragment> <Grandparent /> <Grandparent /> </React.Fragment>, document.createElement('div'), ); legacyRender( <React.Fragment> <Grandparent /> <Grandparent /> </React.Fragment>, document.createElement('div'), ); }); for (let i = 0; i < store.numElements; i++) { expect(store.getIndexOfElementID(store.getElementIDAtIndex(i))).toBe(i); } }); }); // @reactVersion >= 18.0 it('detects and updates profiling support based on the attached roots', () => { const Component = () => null; const containerA = document.createElement('div'); const containerB = document.createElement('div'); expect(store.rootSupportsBasicProfiling).toBe(false); act(() => legacyRender(<Component />, containerA)); expect(store.rootSupportsBasicProfiling).toBe(true); act(() => legacyRender(<Component />, containerB)); act(() => ReactDOM.unmountComponentAtNode(containerA)); expect(store.rootSupportsBasicProfiling).toBe(true); act(() => ReactDOM.unmountComponentAtNode(containerB)); expect(store.rootSupportsBasicProfiling).toBe(false); }); // @reactVersion >= 18.0 it('should properly serialize non-string key values', () => { const Child = () => null; // Bypass React element's automatic stringifying of keys intentionally. // This is pretty hacky. const fauxElement = Object.assign({}, <Child />, {key: 123}); act(() => legacyRender([fauxElement], document.createElement('div'))); expect(store).toMatchInlineSnapshot(` [root] <Child key="123"> `); }); it('should show the right display names for special component types', async () => { const MyComponent = (props, ref) => null; const ForwardRefComponent = React.forwardRef(MyComponent); const MyComponent2 = (props, ref) => null; const ForwardRefComponentWithAnonymousFunction = React.forwardRef(() => ( <MyComponent2 /> )); const MyComponent3 = (props, ref) => null; const ForwardRefComponentWithCustomDisplayName = React.forwardRef(MyComponent3); ForwardRefComponentWithCustomDisplayName.displayName = 'Custom'; const MyComponent4 = (props, ref) => null; const MemoComponent = React.memo(MyComponent4); const MemoForwardRefComponent = React.memo(ForwardRefComponent); const FakeHigherOrderComponent = () => null; FakeHigherOrderComponent.displayName = 'withFoo(withBar(Baz))'; const MemoizedFakeHigherOrderComponent = React.memo( FakeHigherOrderComponent, ); const ForwardRefFakeHigherOrderComponent = React.forwardRef( FakeHigherOrderComponent, ); const MemoizedFakeHigherOrderComponentWithDisplayNameOverride = React.memo( FakeHigherOrderComponent, ); MemoizedFakeHigherOrderComponentWithDisplayNameOverride.displayName = 'memoRefOverride'; const ForwardRefFakeHigherOrderComponentWithDisplayNameOverride = React.forwardRef(FakeHigherOrderComponent); ForwardRefFakeHigherOrderComponentWithDisplayNameOverride.displayName = 'forwardRefOverride'; const App = () => ( <React.Fragment> <MyComponent /> <ForwardRefComponent /> <ForwardRefComponentWithAnonymousFunction /> <ForwardRefComponentWithCustomDisplayName /> <MemoComponent /> <MemoForwardRefComponent /> <FakeHigherOrderComponent /> <MemoizedFakeHigherOrderComponent /> <ForwardRefFakeHigherOrderComponent /> <React.unstable_Cache /> <MemoizedFakeHigherOrderComponentWithDisplayNameOverride /> <ForwardRefFakeHigherOrderComponentWithDisplayNameOverride /> </React.Fragment> ); const container = document.createElement('div'); // Render once to start fetching the lazy component act(() => legacyRender(<App />, container)); await Promise.resolve(); // Render again after it resolves act(() => legacyRender(<App />, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> <MyComponent> <MyComponent> [ForwardRef] ▾ <Anonymous> [ForwardRef] <MyComponent2> <Custom> <MyComponent4> [Memo] ▾ <MyComponent> [Memo] <MyComponent> [ForwardRef] <Baz> [withFoo][withBar] <Baz> [Memo][withFoo][withBar] <Baz> [ForwardRef][withFoo][withBar] <Cache> <memoRefOverride> <forwardRefOverride> `); }); describe('Lazy', () => { async function fakeImport(result) { return {default: result}; } const LazyInnerComponent = () => null; const App = ({renderChildren}) => { if (renderChildren) { return ( <React.Suspense fallback="Loading..."> <LazyComponent /> </React.Suspense> ); } else { return null; } }; let LazyComponent; beforeEach(() => { LazyComponent = React.lazy(() => fakeImport(LazyInnerComponent)); }); // @reactVersion >= 18.0 it('should support Lazy components (legacy render)', async () => { const container = document.createElement('div'); // Render once to start fetching the lazy component act(() => legacyRender(<App renderChildren={true} />, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> <Suspense> `); await Promise.resolve(); // Render again after it resolves act(() => legacyRender(<App renderChildren={true} />, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> ▾ <Suspense> <LazyInnerComponent> `); // Render again to unmount it act(() => legacyRender(<App renderChildren={false} />, container)); expect(store).toMatchInlineSnapshot(` [root] <App> `); }); // @reactVersion >= 18.0 it('should support Lazy components in (createRoot)', async () => { const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); // Render once to start fetching the lazy component act(() => root.render(<App renderChildren={true} />)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> <Suspense> `); await Promise.resolve(); // Render again after it resolves act(() => root.render(<App renderChildren={true} />)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> ▾ <Suspense> <LazyInnerComponent> `); // Render again to unmount it act(() => root.render(<App renderChildren={false} />)); expect(store).toMatchInlineSnapshot(` [root] <App> `); }); // @reactVersion >= 18.0 it('should support Lazy components that are unmounted before they finish loading (legacy render)', async () => { const container = document.createElement('div'); // Render once to start fetching the lazy component act(() => legacyRender(<App renderChildren={true} />, container)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> <Suspense> `); // Render again to unmount it before it finishes loading act(() => legacyRender(<App renderChildren={false} />, container)); expect(store).toMatchInlineSnapshot(` [root] <App> `); }); // @reactVersion >= 18.0 it('should support Lazy components that are unmounted before they finish loading in (createRoot)', async () => { const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); // Render once to start fetching the lazy component act(() => root.render(<App renderChildren={true} />)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> <Suspense> `); // Render again to unmount it before it finishes loading act(() => root.render(<App renderChildren={false} />)); expect(store).toMatchInlineSnapshot(` [root] <App> `); }); }); describe('inline errors and warnings', () => { // @reactVersion >= 18.0 it('during render are counted', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender(<Example />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Example> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender(<Example rerender={1} />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ `); }); // @reactVersion >= 18.0 it('during layout get counted', () => { function Example() { React.useLayoutEffect(() => { console.error('test-only: layout error'); console.warn('test-only: layout warning'); }); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender(<Example />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Example> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender(<Example rerender={1} />, container)); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ `); }); describe('during passive effects', () => { function flushPendingBridgeOperations() { jest.runOnlyPendingTimers(); } // Gross abstraction around pending passive warning/error delay. function flushPendingPassiveErrorAndWarningCounts() { jest.advanceTimersByTime(1000); } // @reactVersion >= 18.0 it('are counted (after a delay)', () => { function Example() { React.useEffect(() => { console.error('test-only: passive error'); console.warn('test-only: passive warning'); }); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => { legacyRender(<Example />, container); }, false); }); flushPendingBridgeOperations(); expect(store).toMatchInlineSnapshot(` [root] <Example> `); // After a delay, passive effects should be committed as well act(flushPendingPassiveErrorAndWarningCounts, false); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Example> ✕⚠ `); act(() => ReactDOM.unmountComponentAtNode(container)); expect(store).toMatchInlineSnapshot(``); }); // @reactVersion >= 18.0 it('are flushed early when there is a new commit', () => { function Example() { React.useEffect(() => { console.error('test-only: passive error'); console.warn('test-only: passive warning'); }); return null; } function Noop() { return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => { legacyRender( <> <Example /> </>, container, ); }, false); flushPendingBridgeOperations(); expect(store).toMatchInlineSnapshot(` [root] <Example> `); // Before warnings and errors have flushed, flush another commit. act(() => { legacyRender( <> <Example /> <Noop /> </>, container, ); }, false); flushPendingBridgeOperations(); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Example> ✕⚠ <Noop> `); }); // After a delay, passive effects should be committed as well act(flushPendingPassiveErrorAndWarningCounts, false); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ <Noop> `); act(() => ReactDOM.unmountComponentAtNode(container)); expect(store).toMatchInlineSnapshot(``); }); }); // @reactVersion >= 18.0 it('from react get counted', () => { const container = document.createElement('div'); function Example() { return [<Child />]; } function Child() { return null; } withErrorsOrWarningsIgnored( ['Warning: Each child in a list should have a unique "key" prop'], () => { act(() => legacyRender(<Example />, container)); }, ); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] ▾ <Example> ✕ <Child> `); }); // @reactVersion >= 18.0 it('can be cleared for the whole app', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender( <React.Fragment> <Example /> <Example /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ <Example> ✕⚠ `); const { clearErrorsAndWarnings, } = require('react-devtools-shared/src/backendAPI'); clearErrorsAndWarnings({bridge, store}); // flush events to the renderer jest.runAllTimers(); expect(store).toMatchInlineSnapshot(` [root] <Example> <Example> `); }); // @reactVersion >= 18.0 it('can be cleared for particular Fiber (only warnings)', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender( <React.Fragment> <Example /> <Example /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ <Example> ✕⚠ `); const id = ((store.getElementIDAtIndex(1): any): number); const rendererID = store.getRendererIDForElement(id); const { clearWarningsForElement, } = require('react-devtools-shared/src/backendAPI'); clearWarningsForElement({bridge, id, rendererID}); // Flush events to the renderer. jest.runAllTimers(); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 1 [root] <Example> ✕⚠ <Example> ✕ `); }); // @reactVersion >= 18.0 it('can be cleared for a particular Fiber (only errors)', () => { function Example() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender( <React.Fragment> <Example /> <Example /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Example> ✕⚠ <Example> ✕⚠ `); const id = ((store.getElementIDAtIndex(1): any): number); const rendererID = store.getRendererIDForElement(id); const { clearErrorsForElement, } = require('react-devtools-shared/src/backendAPI'); clearErrorsForElement({bridge, id, rendererID}); // Flush events to the renderer. jest.runAllTimers(); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <Example> ✕⚠ <Example> ⚠ `); }); // @reactVersion >= 18.0 it('are updated when fibers are removed from the tree', () => { function ComponentWithWarning() { console.warn('test-only: render warning'); return null; } function ComponentWithError() { console.error('test-only: render error'); return null; } function ComponentWithWarningAndError() { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; } const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender( <React.Fragment> <ComponentWithError /> <ComponentWithWarning /> <ComponentWithWarningAndError /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <ComponentWithError> ✕ <ComponentWithWarning> ⚠ <ComponentWithWarningAndError> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender( <React.Fragment> <ComponentWithWarning /> <ComponentWithWarningAndError /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <ComponentWithWarning> ⚠ <ComponentWithWarningAndError> ✕⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender( <React.Fragment> <ComponentWithWarning /> </React.Fragment>, container, ), ); }); expect(store).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] <ComponentWithWarning> ⚠ `); withErrorsOrWarningsIgnored(['test-only:'], () => { act(() => legacyRender(<React.Fragment />, container)); }); expect(store).toMatchInlineSnapshot(`[root]`); expect(store.errorCount).toBe(0); expect(store.warningCount).toBe(0); }); // Regression test for https://github.com/facebook/react/issues/23202 // @reactVersion >= 18.0 it('suspense boundary children should not double unmount and error', async () => { async function fakeImport(result) { return {default: result}; } const ChildA = () => null; const ChildB = () => null; const LazyChildA = React.lazy(() => fakeImport(ChildA)); const LazyChildB = React.lazy(() => fakeImport(ChildB)); function App({renderA}) { return ( <React.Suspense> {renderA ? <LazyChildA /> : <LazyChildB />} </React.Suspense> ); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await actAsync(() => root.render(<App renderA={true} />)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> ▾ <Suspense> <ChildA> `); await actAsync(() => root.render(<App renderA={false} />)); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> ▾ <Suspense> <ChildB> `); }); }); });
27.47892
116
0.508949
PenetrationTestingScripts
'use strict'; /** @flow */ async function clickButton(page, buttonTestName) { await page.evaluate(testName => { const {createTestNameSelector, findAllNodes} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const button = findAllNodes(container, [ createTestNameSelector(testName), ])[0]; button.click(); }, buttonTestName); } async function getElementCount(page, displayName) { return await page.evaluate(listItemText => { const {createTestNameSelector, createTextSelector, findAllNodes} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const rows = findAllNodes(container, [ createTestNameSelector('ComponentTreeListItem'), createTextSelector(listItemText), ]); return rows.length; }, displayName); } async function selectElement(page, displayName, waitForOwnersText) { await page.evaluate(listItemText => { const {createTestNameSelector, createTextSelector, findAllNodes} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const listItem = findAllNodes(container, [ createTestNameSelector('ComponentTreeListItem'), createTextSelector(listItemText), ])[0]; listItem.click(); }, displayName); if (waitForOwnersText) { // Wait for selected element's props to load. await page.waitForFunction( ({titleText, ownersListText}) => { const {createTestNameSelector, findAllNodes} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const title = findAllNodes(container, [ createTestNameSelector('InspectedElement-Title'), ])[0]; const ownersList = findAllNodes(container, [ createTestNameSelector('InspectedElementView-Owners'), ])[0]; return ( title && title.innerText.includes(titleText) && ownersList && ownersList.innerText.includes(ownersListText) ); }, {titleText: displayName, ownersListText: waitForOwnersText} ); } } module.exports = { clickButton, getElementCount, selectElement, };
28.210526
77
0.679135
owtf
/** * 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. * * @emails react-core */ 'use strict'; import {buttonType, buttonsType} from './constants'; import * as domEvents from './domEvents'; import * as domEventSequences from './domEventSequences'; import {hasPointerEvent, setPointerEvent, platform} from './domEnvironment'; import {describeWithPointerEvent, testWithPointerType} from './testHelpers'; const createEventTarget = node => ({ node, /** * Simple events abstraction. */ blur(payload) { node.dispatchEvent(domEvents.blur(payload)); node.dispatchEvent(domEvents.focusOut(payload)); }, click(payload) { node.dispatchEvent(domEvents.click(payload)); }, focus(payload) { node.dispatchEvent(domEvents.focus(payload)); node.dispatchEvent(domEvents.focusIn(payload)); node.focus(); }, keydown(payload) { node.dispatchEvent(domEvents.keydown(payload)); }, keyup(payload) { node.dispatchEvent(domEvents.keyup(payload)); }, scroll(payload) { node.dispatchEvent(domEvents.scroll(payload)); }, virtualclick(payload) { node.dispatchEvent(domEvents.virtualclick(payload)); }, /** * PointerEvent abstraction. * Dispatches the expected sequence of PointerEvents, MouseEvents, and * TouchEvents for a given environment. */ contextmenu(payload, options) { domEventSequences.contextmenu(node, payload, options); }, // node no longer receives events for the pointer pointercancel(payload) { domEventSequences.pointercancel(node, payload); }, // node dispatches down events pointerdown(payload) { domEventSequences.pointerdown(node, payload); }, // node dispatches move events (pointer is not down) pointerhover(payload) { domEventSequences.pointerhover(node, payload); }, // node dispatches move events (pointer is down) pointermove(payload) { domEventSequences.pointermove(node, payload); }, // node dispatches enter & over events pointerenter(payload) { domEventSequences.pointerenter(node, payload); }, // node dispatches exit & leave events pointerexit(payload) { domEventSequences.pointerexit(node, payload); }, // node dispatches up events pointerup(payload) { domEventSequences.pointerup(node, payload); }, /** * Gesture abstractions. * Helpers for event sequences expected in a gesture. * target.tap({ pointerType: 'touch' }) */ tap(payload) { domEventSequences.pointerdown(payload); domEventSequences.pointerup(payload); }, /** * Utilities */ setBoundingClientRect({x, y, width, height}) { node.getBoundingClientRect = function () { return { width, height, left: x, right: x + width, top: y, bottom: y + height, }; }; }, }); const resetActivePointers = domEventSequences.resetActivePointers; export { buttonType, buttonsType, createEventTarget, describeWithPointerEvent, platform, hasPointerEvent, resetActivePointers, setPointerEvent, testWithPointerType, };
25.180328
76
0.693079
cybersecurity-penetration-testing
/** * 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. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ let JSDOM; let React; let ReactDOMClient; let clientAct; let ReactDOMFizzServer; let Stream; let Suspense; let useId; let useState; let document; let writable; let container; let buffer = ''; let hasErrored = false; let fatalError = undefined; let waitForPaint; describe('useId', () => { beforeEach(() => { jest.resetModules(); JSDOM = require('jsdom').JSDOM; React = require('react'); ReactDOMClient = require('react-dom/client'); clientAct = require('internal-test-utils').act; ReactDOMFizzServer = require('react-dom/server'); Stream = require('stream'); Suspense = React.Suspense; useId = React.useId; useState = React.useState; const InternalTestUtils = require('internal-test-utils'); waitForPaint = InternalTestUtils.waitForPaint; // Test Environment const jsdom = new JSDOM( '<!DOCTYPE html><html><head></head><body><div id="container">', { runScripts: 'dangerously', }, ); document = jsdom.window.document; container = document.getElementById('container'); buffer = ''; hasErrored = false; writable = new Stream.PassThrough(); writable.setEncoding('utf8'); writable.on('data', chunk => { buffer += chunk; }); writable.on('error', error => { hasErrored = true; fatalError = error; }); }); async function serverAct(callback) { await callback(); // Await one turn around the event loop. // This assumes that we'll flush everything we have so far. await new Promise(resolve => { setImmediate(resolve); }); if (hasErrored) { throw fatalError; } // JSDOM doesn't support stream HTML parser so we need to give it a proper fragment. // We also want to execute any scripts that are embedded. // We assume that we have now received a proper fragment of HTML. const bufferedContent = buffer; buffer = ''; const fakeBody = document.createElement('body'); fakeBody.innerHTML = bufferedContent; while (fakeBody.firstChild) { const node = fakeBody.firstChild; if (node.nodeName === 'SCRIPT') { const script = document.createElement('script'); script.textContent = node.textContent; fakeBody.removeChild(node); container.appendChild(script); } else { container.appendChild(node); } } } function normalizeTreeIdForTesting(id) { const result = id.match(/:(R|r)([a-z0-9]*)(H([0-9]*))?:/); if (result === undefined) { throw new Error('Invalid id format'); } const [, serverClientPrefix, base32, hookIndex] = result; if (serverClientPrefix.endsWith('r')) { // Client ids aren't stable. For testing purposes, strip out the counter. return ( 'CLIENT_GENERATED_ID' + (hookIndex !== undefined ? ` (${hookIndex})` : '') ); } // Formats the tree id as a binary sequence, so it's easier to visualize // the structure. return ( parseInt(base32, 32).toString(2) + (hookIndex !== undefined ? ` (${hookIndex})` : '') ); } function DivWithId({children}) { const id = normalizeTreeIdForTesting(useId()); return <div id={id}>{children}</div>; } test('basic example', async () => { function App() { return ( <div> <div> <DivWithId /> <DivWithId /> </div> <DivWithId /> </div> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div> <div> <div id="101" /> <div id="1001" /> </div> <div id="10" /> </div> </div> `); }); test('indirections', async () => { function App() { // There are no forks in this tree, but the parent and the child should // have different ids. return ( <DivWithId> <div> <div> <div> <DivWithId /> </div> </div> </div> </DivWithId> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div id="0" > <div> <div> <div> <div id="1" /> </div> </div> </div> </div> </div> `); }); test('StrictMode double rendering', async () => { const {StrictMode} = React; function App() { return ( <StrictMode> <DivWithId /> </StrictMode> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div id="0" /> </div> `); }); test('empty (null) children', async () => { // We don't treat empty children different from non-empty ones, which means // they get allocated a slot when generating ids. There's no inherent reason // to do this; Fiber happens to allocate a fiber for null children that // appear in a list, which is not ideal for performance. For the purposes // of id generation, though, what matters is that Fizz and Fiber // are consistent. function App() { return ( <> {null} <DivWithId /> {null} <DivWithId /> </> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div id="10" /> <div id="100" /> </div> `); }); test('large ids', async () => { // The component in this test outputs a recursive tree of nodes with ids, // where the underlying binary representation is an alternating series of 1s // and 0s. In other words, they are all of the form 101010101. // // Because we use base 32 encoding, the resulting id should consist of // alternating 'a' (01010) and 'l' (10101) characters, except for the the // 'R:' prefix, and the first character after that, which may not correspond // to a complete set of 5 bits. // // Example: :Rclalalalalalalala...: // // We can use this pattern to test large ids that exceed the bitwise // safe range (32 bits). The algorithm should theoretically support ids // of any size. function Child({children}) { const id = useId(); return <div id={id}>{children}</div>; } function App() { let tree = <Child />; for (let i = 0; i < 50; i++) { tree = ( <> <Child /> {tree} </> ); } return tree; } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); const divs = container.querySelectorAll('div'); // Confirm that every id matches the expected pattern for (let i = 0; i < divs.length; i++) { // Example: :Rclalalalalalalala...: expect(divs[i].id).toMatch(/^:R.(((al)*a?)((la)*l?))*:$/); } }); test('multiple ids in a single component', async () => { function App() { const id1 = useId(); const id2 = useId(); const id3 = useId(); return `${id1}, ${id2}, ${id3}`; } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); // We append a suffix to the end of the id to distinguish them expect(container).toMatchInlineSnapshot(` <div id="container" > :R0:, :R0H1:, :R0H2: </div> `); }); test('local render phase updates', async () => { function App({swap}) { const [count, setCount] = useState(0); if (count < 3) { setCount(count + 1); } return useId(); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > :R0: </div> `); }); test('basic incremental hydration', async () => { function App() { return ( <div> <Suspense fallback="Loading..."> <DivWithId label="A" /> <DivWithId label="B" /> </Suspense> <DivWithId label="C" /> </div> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div> <!--$--> <div id="101" /> <div id="1001" /> <!--/$--> <div id="10" /> </div> </div> `); }); test('inserting/deleting siblings outside a dehydrated Suspense boundary', async () => { const span = React.createRef(null); function App({swap}) { // Note: Using a dynamic array so these are treated as insertions and // deletions instead of updates, because Fiber currently allocates a node // even for empty children. const children = [ <DivWithId key="A" />, swap ? <DivWithId key="C" /> : <DivWithId key="B" />, <DivWithId key="D" />, ]; return ( <> {children} <Suspense key="boundary" fallback="Loading..."> <DivWithId /> <span ref={span} /> </Suspense> </> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); const dehydratedSpan = container.getElementsByTagName('span')[0]; await clientAct(async () => { const root = ReactDOMClient.hydrateRoot(container, <App />); await waitForPaint([]); expect(container).toMatchInlineSnapshot(` <div id="container" > <div id="101" /> <div id="1001" /> <div id="1101" /> <!--$--> <div id="110" /> <span /> <!--/$--> </div> `); // The inner boundary hasn't hydrated yet expect(span.current).toBe(null); // Swap B for C root.render(<App swap={true} />); }); // The swap should not have caused a mismatch. expect(container).toMatchInlineSnapshot(` <div id="container" > <div id="101" /> <div id="CLIENT_GENERATED_ID" /> <div id="1101" /> <!--$--> <div id="110" /> <span /> <!--/$--> </div> `); // Should have hydrated successfully expect(span.current).toBe(dehydratedSpan); }); test('inserting/deleting siblings inside a dehydrated Suspense boundary', async () => { const span = React.createRef(null); function App({swap}) { // Note: Using a dynamic array so these are treated as insertions and // deletions instead of updates, because Fiber currently allocates a node // even for empty children. const children = [ <DivWithId key="A" />, swap ? <DivWithId key="C" /> : <DivWithId key="B" />, <DivWithId key="D" />, ]; return ( <Suspense key="boundary" fallback="Loading..."> {children} <span ref={span} /> </Suspense> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); const dehydratedSpan = container.getElementsByTagName('span')[0]; await clientAct(async () => { const root = ReactDOMClient.hydrateRoot(container, <App />); await waitForPaint([]); expect(container).toMatchInlineSnapshot(` <div id="container" > <!--$--> <div id="101" /> <div id="1001" /> <div id="1101" /> <span /> <!--/$--> </div> `); // The inner boundary hasn't hydrated yet expect(span.current).toBe(null); // Swap B for C root.render(<App swap={true} />); }); // The swap should not have caused a mismatch. expect(container).toMatchInlineSnapshot(` <div id="container" > <!--$--> <div id="101" /> <div id="CLIENT_GENERATED_ID" /> <div id="1101" /> <span /> <!--/$--> </div> `); // Should have hydrated successfully expect(span.current).toBe(dehydratedSpan); }); test('identifierPrefix option', async () => { function Child() { const id = useId(); return <div>{id}</div>; } function App({showMore}) { return ( <> <Child /> <Child /> {showMore && <Child />} </> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />, { identifierPrefix: 'custom-prefix-', }); pipe(writable); }); let root; await clientAct(async () => { root = ReactDOMClient.hydrateRoot(container, <App />, { identifierPrefix: 'custom-prefix-', }); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div> :custom-prefix-R1: </div> <div> :custom-prefix-R2: </div> </div> `); // Mount a new, client-only id await clientAct(async () => { root.render(<App showMore={true} />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div> :custom-prefix-R1: </div> <div> :custom-prefix-R2: </div> <div> :custom-prefix-r0: </div> </div> `); }); // https://github.com/vercel/next.js/issues/43033 // re-rendering in strict mode caused the localIdCounter to be reset but it the rerender hook does not // increment it again. This only shows up as a problem for subsequent useId's because it affects child // and sibling counters not the initial one it('does not forget it mounted an id when re-rendering in dev', async () => { function Parent() { const id = useId(); return ( <div> {id} <Child /> </div> ); } function Child() { const id = useId(); return <div>{id}</div>; } function App({showMore}) { return ( <React.StrictMode> <Parent /> </React.StrictMode> ); } await serverAct(async () => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />); pipe(writable); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div> :R0: <!-- --> <div> :R7: </div> </div> </div> `); await clientAct(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container).toMatchInlineSnapshot(` <div id="container" > <div> :R0: <!-- --> <div> :R7: </div> </div> </div> `); }); });
23.693182
104
0.515964
Python-Penetration-Testing-for-Developers
describe('ErrorBoundaryReconciliation', () => { let BrokenRender; let DidCatchErrorBoundary; let GetDerivedErrorBoundary; let React; let ReactFeatureFlags; let ReactTestRenderer; let span; let act; beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; ReactTestRenderer = require('react-test-renderer'); React = require('react'); act = require('internal-test-utils').act; DidCatchErrorBoundary = class extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { return this.state.error ? React.createElement(this.props.fallbackTagName, { prop: 'ErrorBoundary', }) : this.props.children; } }; GetDerivedErrorBoundary = class extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { return this.state.error ? React.createElement(this.props.fallbackTagName, { prop: 'ErrorBoundary', }) : this.props.children; } }; const InvalidType = undefined; BrokenRender = ({fail}) => fail ? <InvalidType /> : <span prop="BrokenRender" />; }); [true, false].forEach(isConcurrent => { async function sharedTest(ErrorBoundary, fallbackTagName) { let renderer; await act(() => { renderer = ReactTestRenderer.create( <ErrorBoundary fallbackTagName={fallbackTagName}> <BrokenRender fail={false} /> </ErrorBoundary>, {isConcurrent: isConcurrent}, ); }); expect(renderer).toMatchRenderedOutput(<span prop="BrokenRender" />); await expect(async () => { await act(() => { renderer.update( <ErrorBoundary fallbackTagName={fallbackTagName}> <BrokenRender fail={true} /> </ErrorBoundary>, ); }); }).toErrorDev(isConcurrent ? ['invalid', 'invalid'] : ['invalid']); const Fallback = fallbackTagName; expect(renderer).toMatchRenderedOutput(<Fallback prop="ErrorBoundary" />); } describe(isConcurrent ? 'concurrent' : 'sync', () => { it('componentDidCatch can recover by rendering an element of the same type', () => sharedTest(DidCatchErrorBoundary, 'span')); it('componentDidCatch can recover by rendering an element of a different type', () => sharedTest(DidCatchErrorBoundary, 'div')); it('getDerivedStateFromError can recover by rendering an element of the same type', () => sharedTest(GetDerivedErrorBoundary, 'span')); it('getDerivedStateFromError can recover by rendering an element of a different type', () => sharedTest(GetDerivedErrorBoundary, 'div')); }); }); });
30.621053
98
0.617383
owtf
const React = window.React; class DrawBox extends React.Component { render() { const boxStyle = { border: '1px solid #d9d9d9', margin: '10px 0 20px', padding: '20px 20px', touchAction: 'none', }; const obstacleStyle = { border: '1px solid #d9d9d9', width: '25%', height: '200px', margin: '12.5%', display: 'inline-block', }; return ( <div style={boxStyle} onPointerOver={this.props.onOver} onPointerOut={this.props.onOut} onPointerEnter={this.props.onEnter} onPointerLeave={this.props.onLeave}> <div style={obstacleStyle} /> <div style={obstacleStyle} /> </div> ); } } export default DrawBox;
20.371429
44
0.564926
PenetrationTestingScripts
#!/usr/bin/env node 'use strict'; const deploy = require('../deploy'); const main = async () => await deploy('chrome'); main();
12.3
48
0.613636
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 5 } }, /*#__PURE__*/_react.default.createElement("p", { __source: { fileName: _jsxFileName, lineNumber: 17, columnNumber: 7 } }, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", { onClick: () => setCount(count + 1), __source: { fileName: _jsxFileName, lineNumber: 18, columnNumber: 7 } }, "Click me")); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkV4YW1wbGUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJzZXRDb3VudCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50LCBzZXRDb3VudF0gPSB1c2VTdGF0ZSgwKTtcblxuICByZXR1cm4gKFxuICAgIDxkaXY+XG4gICAgICA8cD5Zb3UgY2xpY2tlZCB7Y291bnR9IHRpbWVzPC9wPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXsoKSA9PiBzZXRDb3VudChjb3VudCArIDEpfT5DbGljayBtZTwvYnV0dG9uPlxuICAgIDwvZGl2PlxuICApO1xufVxuIl19fV19
78.666667
1,348
0.793947
null
/** * 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. * * @emails react-core * @jest-environment node */ 'use strict'; const ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; const React = require('react'); const ReactTestRenderer = require('react-test-renderer'); const {format: prettyFormat} = require('pretty-format'); // Isolate noop renderer jest.resetModules(); const ReactNoop = require('react-noop-renderer'); const InternalTestUtils = require('internal-test-utils'); const waitForAll = InternalTestUtils.waitForAll; // Kind of hacky, but we nullify all the instances to test the tree structure // with jasmine's deep equality function, and test the instances separate. We // also delete children props because testing them is more annoying and not // really important to verify. function cleanNodeOrArray(node) { if (!node) { return; } if (Array.isArray(node)) { node.forEach(cleanNodeOrArray); return; } if (node && node.instance) { node.instance = null; } if (node && node.props && node.props.children) { // eslint-disable-next-line no-unused-vars const {children, ...props} = node.props; node.props = props; } if (Array.isArray(node.rendered)) { node.rendered.forEach(cleanNodeOrArray); } else if (typeof node.rendered === 'object') { cleanNodeOrArray(node.rendered); } } describe('ReactTestRenderer', () => { it('renders a simple component', () => { function Link() { return <a role="link" />; } const renderer = ReactTestRenderer.create(<Link />); expect(renderer.toJSON()).toEqual({ type: 'a', props: {role: 'link'}, children: null, }); }); it('renders a top-level empty component', () => { function Empty() { return null; } const renderer = ReactTestRenderer.create(<Empty />); expect(renderer.toJSON()).toEqual(null); }); it('exposes a type flag', () => { function Link() { return <a role="link" />; } const renderer = ReactTestRenderer.create(<Link />); const object = renderer.toJSON(); expect(object.$$typeof).toBe(Symbol.for('react.test.json')); // $$typeof should not be enumerable. for (const key in object) { if (object.hasOwnProperty(key)) { expect(key).not.toBe('$$typeof'); } } }); it('can render a composite component', () => { class Component extends React.Component { render() { return ( <div className="purple"> <Child /> </div> ); } } const Child = () => { return <moo />; }; const renderer = ReactTestRenderer.create(<Component />); expect(renderer.toJSON()).toEqual({ type: 'div', props: {className: 'purple'}, children: [{type: 'moo', props: {}, children: null}], }); }); it('renders some basics with an update', () => { let renders = 0; class Component extends React.Component { state = {x: 3}; render() { renders++; return ( <div className="purple"> {this.state.x} <Child /> <Null /> </div> ); } componentDidMount() { this.setState({x: 7}); } } const Child = () => { renders++; return <moo />; }; const Null = () => { renders++; return null; }; const renderer = ReactTestRenderer.create(<Component />); expect(renderer.toJSON()).toEqual({ type: 'div', props: {className: 'purple'}, children: ['7', {type: 'moo', props: {}, children: null}], }); expect(renders).toBe(6); }); it('exposes the instance', () => { class Mouse extends React.Component { constructor() { super(); this.state = {mouse: 'mouse'}; } handleMoose() { this.setState({mouse: 'moose'}); } render() { return <div>{this.state.mouse}</div>; } } const renderer = ReactTestRenderer.create(<Mouse />); expect(renderer.toJSON()).toEqual({ type: 'div', props: {}, children: ['mouse'], }); const mouse = renderer.getInstance(); mouse.handleMoose(); expect(renderer.toJSON()).toEqual({ type: 'div', children: ['moose'], props: {}, }); }); it('updates types', () => { const renderer = ReactTestRenderer.create(<div>mouse</div>); expect(renderer.toJSON()).toEqual({ type: 'div', props: {}, children: ['mouse'], }); renderer.update(<span>mice</span>); expect(renderer.toJSON()).toEqual({ type: 'span', props: {}, children: ['mice'], }); }); it('updates children', () => { const renderer = ReactTestRenderer.create( <div> <span key="a">A</span> <span key="b">B</span> <span key="c">C</span> </div>, ); expect(renderer.toJSON()).toEqual({ type: 'div', props: {}, children: [ {type: 'span', props: {}, children: ['A']}, {type: 'span', props: {}, children: ['B']}, {type: 'span', props: {}, children: ['C']}, ], }); renderer.update( <div> <span key="d">D</span> <span key="c">C</span> <span key="b">B</span> </div>, ); expect(renderer.toJSON()).toEqual({ type: 'div', props: {}, children: [ {type: 'span', props: {}, children: ['D']}, {type: 'span', props: {}, children: ['C']}, {type: 'span', props: {}, children: ['B']}, ], }); }); it('does the full lifecycle', () => { const log = []; class Log extends React.Component { render() { log.push('render ' + this.props.name); return <div />; } componentDidMount() { log.push('mount ' + this.props.name); } componentWillUnmount() { log.push('unmount ' + this.props.name); } } const renderer = ReactTestRenderer.create(<Log key="foo" name="Foo" />); renderer.update(<Log key="bar" name="Bar" />); renderer.unmount(); expect(log).toEqual([ 'render Foo', 'mount Foo', 'render Bar', 'unmount Foo', 'mount Bar', 'unmount Bar', ]); }); it('gives a ref to native components', () => { const log = []; ReactTestRenderer.create(<div ref={r => log.push(r)} />); expect(log).toEqual([null]); }); it('warns correctly for refs on SFCs', () => { function Bar() { return <div>Hello, world</div>; } class Foo extends React.Component { fooRef = React.createRef(); render() { return <Bar ref={this.fooRef} />; } } class Baz extends React.Component { bazRef = React.createRef(); render() { return <div ref={this.bazRef} />; } } ReactTestRenderer.create(<Baz />); expect(() => ReactTestRenderer.create(<Foo />)).toErrorDev( 'Warning: Function components cannot be given refs. Attempts ' + 'to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?\n\n' + 'Check the render method of `Foo`.\n' + ' in Bar (at **)\n' + ' in Foo (at **)', ); }); it('allows an optional createNodeMock function', () => { const mockDivInstance = {appendChild: () => {}}; const mockInputInstance = {focus: () => {}}; const mockListItemInstance = {click: () => {}}; const mockAnchorInstance = {hover: () => {}}; const log = []; class Foo extends React.Component { barRef = React.createRef(); componentDidMount() { log.push(this.barRef.current); } render() { return <a ref={this.barRef}>Hello, world</a>; } } function createNodeMock(element) { switch (element.type) { case 'div': return mockDivInstance; case 'input': return mockInputInstance; case 'li': return mockListItemInstance; case 'a': return mockAnchorInstance; default: return {}; } } ReactTestRenderer.create(<div ref={r => log.push(r)} />, {createNodeMock}); ReactTestRenderer.create(<input ref={r => log.push(r)} />, { createNodeMock, }); ReactTestRenderer.create( <div> <span> <ul> <li ref={r => log.push(r)} /> </ul> <ul> <li ref={r => log.push(r)} /> <li ref={r => log.push(r)} /> </ul> </span> </div>, {createNodeMock, foobar: true}, ); ReactTestRenderer.create(<Foo />, {createNodeMock}); ReactTestRenderer.create(<div ref={r => log.push(r)} />); ReactTestRenderer.create(<div ref={r => log.push(r)} />, {}); expect(log).toEqual([ mockDivInstance, mockInputInstance, mockListItemInstance, mockListItemInstance, mockListItemInstance, mockAnchorInstance, null, null, ]); }); it('supports unmounting when using refs', () => { class Foo extends React.Component { render() { return <div ref={React.createRef()} />; } } const inst = ReactTestRenderer.create(<Foo />, { createNodeMock: () => 'foo', }); expect(() => inst.unmount()).not.toThrow(); }); it('supports unmounting inner instances', () => { let count = 0; class Foo extends React.Component { componentWillUnmount() { count++; } render() { return <div />; } } const inst = ReactTestRenderer.create( <div> <Foo /> </div>, { createNodeMock: () => 'foo', }, ); expect(() => inst.unmount()).not.toThrow(); expect(count).toEqual(1); }); it('supports updates when using refs', () => { const log = []; const createNodeMock = element => { log.push(element.type); return element.type; }; class Foo extends React.Component { render() { return this.props.useDiv ? ( <div ref={React.createRef()} /> ) : ( <span ref={React.createRef()} /> ); } } const inst = ReactTestRenderer.create(<Foo useDiv={true} />, { createNodeMock, }); inst.update(<Foo useDiv={false} />); expect(log).toEqual(['div', 'span']); }); it('supports error boundaries', () => { const log = []; class Angry extends React.Component { render() { log.push('Angry render'); throw new Error('Please, do not render me.'); } componentDidMount() { log.push('Angry componentDidMount'); } componentWillUnmount() { log.push('Angry componentWillUnmount'); } } class Boundary extends React.Component { constructor(props) { super(props); this.state = {error: false}; } render() { log.push('Boundary render'); if (!this.state.error) { return ( <div> <button onClick={this.onClick}>ClickMe</button> <Angry /> </div> ); } else { return <div>Happy Birthday!</div>; } } componentDidMount() { log.push('Boundary componentDidMount'); } componentWillUnmount() { log.push('Boundary componentWillUnmount'); } onClick() { /* do nothing */ } componentDidCatch() { log.push('Boundary componentDidCatch'); this.setState({error: true}); } } const renderer = ReactTestRenderer.create(<Boundary />); expect(renderer.toJSON()).toEqual({ type: 'div', props: {}, children: ['Happy Birthday!'], }); expect(log).toEqual([ 'Boundary render', 'Angry render', 'Boundary componentDidMount', 'Boundary componentDidCatch', 'Boundary render', ]); }); it('can update text nodes', () => { class Component extends React.Component { render() { return <div>{this.props.children}</div>; } } const renderer = ReactTestRenderer.create(<Component>Hi</Component>); expect(renderer.toJSON()).toEqual({ type: 'div', children: ['Hi'], props: {}, }); renderer.update(<Component>{['Hi', 'Bye']}</Component>); expect(renderer.toJSON()).toEqual({ type: 'div', children: ['Hi', 'Bye'], props: {}, }); renderer.update(<Component>Bye</Component>); expect(renderer.toJSON()).toEqual({ type: 'div', children: ['Bye'], props: {}, }); renderer.update(<Component>{42}</Component>); expect(renderer.toJSON()).toEqual({ type: 'div', children: ['42'], props: {}, }); renderer.update( <Component> <div /> </Component>, ); expect(renderer.toJSON()).toEqual({ type: 'div', children: [ { type: 'div', children: null, props: {}, }, ], props: {}, }); }); it('toTree() renders simple components returning host components', () => { const Qoo = () => <span className="Qoo">Hello World!</span>; const renderer = ReactTestRenderer.create(<Qoo />); const tree = renderer.toTree(); cleanNodeOrArray(tree); expect(prettyFormat(tree)).toEqual( prettyFormat({ nodeType: 'component', type: Qoo, props: {}, instance: null, rendered: { nodeType: 'host', type: 'span', props: {className: 'Qoo'}, instance: null, rendered: ['Hello World!'], }, }), ); }); it('toTree() handles nested Fragments', () => { const Foo = () => ( <> <>foo</> </> ); const renderer = ReactTestRenderer.create(<Foo />); const tree = renderer.toTree(); cleanNodeOrArray(tree); expect(prettyFormat(tree)).toEqual( prettyFormat({ nodeType: 'component', type: Foo, instance: null, props: {}, rendered: 'foo', }), ); }); it('toTree() handles null rendering components', () => { class Foo extends React.Component { render() { return null; } } const renderer = ReactTestRenderer.create(<Foo />); const tree = renderer.toTree(); expect(tree.instance).toBeInstanceOf(Foo); cleanNodeOrArray(tree); expect(tree).toEqual({ type: Foo, nodeType: 'component', props: {}, instance: null, rendered: null, }); }); it('toTree() handles simple components that return arrays', () => { const Foo = ({children}) => children; const renderer = ReactTestRenderer.create( <Foo> <div>One</div> <div>Two</div> </Foo>, ); const tree = renderer.toTree(); cleanNodeOrArray(tree); expect(prettyFormat(tree)).toEqual( prettyFormat({ type: Foo, nodeType: 'component', props: {}, instance: null, rendered: [ { instance: null, nodeType: 'host', props: {}, rendered: ['One'], type: 'div', }, { instance: null, nodeType: 'host', props: {}, rendered: ['Two'], type: 'div', }, ], }), ); }); it('toTree() handles complicated tree of arrays', () => { class Foo extends React.Component { render() { return this.props.children; } } const renderer = ReactTestRenderer.create( <div> <Foo> <div>One</div> <div>Two</div> <Foo> <div>Three</div> </Foo> </Foo> <div>Four</div> </div>, ); const tree = renderer.toTree(); cleanNodeOrArray(tree); expect(prettyFormat(tree)).toEqual( prettyFormat({ type: 'div', instance: null, nodeType: 'host', props: {}, rendered: [ { type: Foo, nodeType: 'component', props: {}, instance: null, rendered: [ { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['One'], }, { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['Two'], }, { type: Foo, nodeType: 'component', props: {}, instance: null, rendered: { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['Three'], }, }, ], }, { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['Four'], }, ], }), ); }); it('toTree() handles complicated tree of fragments', () => { const renderer = ReactTestRenderer.create( <> <> <div>One</div> <div>Two</div> <> <div>Three</div> </> </> <div>Four</div> </>, ); const tree = renderer.toTree(); cleanNodeOrArray(tree); expect(prettyFormat(tree)).toEqual( prettyFormat([ { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['One'], }, { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['Two'], }, { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['Three'], }, { type: 'div', nodeType: 'host', props: {}, instance: null, rendered: ['Four'], }, ]), ); }); it('root instance and createNodeMock ref return the same value', () => { const createNodeMock = ref => ({node: ref}); let refInst = null; const renderer = ReactTestRenderer.create( <div ref={ref => (refInst = ref)} />, {createNodeMock}, ); const root = renderer.getInstance(); expect(root).toEqual(refInst); }); it('toTree() renders complicated trees of composites and hosts', () => { // SFC returning host. no children props. const Qoo = () => <span className="Qoo">Hello World!</span>; // SFC returning host. passes through children. const Foo = ({className, children}) => ( <div className={'Foo ' + className}> <span className="Foo2">Literal</span> {children} </div> ); // class composite returning composite. passes through children. class Bar extends React.Component { render() { const {special, children} = this.props; return <Foo className={special ? 'special' : 'normal'}>{children}</Foo>; } } // class composite return composite. no children props. class Bam extends React.Component { render() { return ( <Bar special={true}> <Qoo /> </Bar> ); } } const renderer = ReactTestRenderer.create(<Bam />); const tree = renderer.toTree(); // we test for the presence of instances before nulling them out expect(tree.instance).toBeInstanceOf(Bam); expect(tree.rendered.instance).toBeInstanceOf(Bar); cleanNodeOrArray(tree); expect(prettyFormat(tree)).toEqual( prettyFormat({ type: Bam, nodeType: 'component', props: {}, instance: null, rendered: { type: Bar, nodeType: 'component', props: {special: true}, instance: null, rendered: { type: Foo, nodeType: 'component', props: {className: 'special'}, instance: null, rendered: { type: 'div', nodeType: 'host', props: {className: 'Foo special'}, instance: null, rendered: [ { type: 'span', nodeType: 'host', props: {className: 'Foo2'}, instance: null, rendered: ['Literal'], }, { type: Qoo, nodeType: 'component', props: {}, instance: null, rendered: { type: 'span', nodeType: 'host', props: {className: 'Qoo'}, instance: null, rendered: ['Hello World!'], }, }, ], }, }, }, }), ); }); it('can update text nodes when rendered as root', () => { const renderer = ReactTestRenderer.create(['Hello', 'world']); expect(renderer.toJSON()).toEqual(['Hello', 'world']); renderer.update(42); expect(renderer.toJSON()).toEqual('42'); renderer.update([42, 'world']); expect(renderer.toJSON()).toEqual(['42', 'world']); }); it('can render and update root fragments', () => { const Component = props => props.children; const renderer = ReactTestRenderer.create([ <Component key="a">Hi</Component>, <Component key="b">Bye</Component>, ]); expect(renderer.toJSON()).toEqual(['Hi', 'Bye']); renderer.update(<div />); expect(renderer.toJSON()).toEqual({ type: 'div', children: null, props: {}, }); renderer.update([<div key="a">goodbye</div>, 'world']); expect(renderer.toJSON()).toEqual([ { type: 'div', children: ['goodbye'], props: {}, }, 'world', ]); }); it('supports context providers and consumers', () => { const {Consumer, Provider} = React.createContext('a'); function Child(props) { return props.value; } function App() { return ( <Provider value="b"> <Consumer>{value => <Child value={value} />}</Consumer> </Provider> ); } const renderer = ReactTestRenderer.create(<App />); const child = renderer.root.findByType(Child); expect(child.children).toEqual(['b']); expect(prettyFormat(renderer.toTree())).toEqual( prettyFormat({ instance: null, nodeType: 'component', props: {}, rendered: { instance: null, nodeType: 'component', props: { value: 'b', }, rendered: 'b', type: Child, }, type: App, }), ); }); it('supports modes', () => { function Child(props) { return props.value; } function App(props) { return ( <React.StrictMode> <Child value={props.value} /> </React.StrictMode> ); } const renderer = ReactTestRenderer.create(<App value="a" />); const child = renderer.root.findByType(Child); expect(child.children).toEqual(['a']); expect(prettyFormat(renderer.toTree())).toEqual( prettyFormat({ instance: null, nodeType: 'component', props: { value: 'a', }, rendered: { instance: null, nodeType: 'component', props: { value: 'a', }, rendered: 'a', type: Child, }, type: App, }), ); }); it('supports forwardRef', () => { const InnerRefed = React.forwardRef((props, ref) => ( <div> <span ref={ref} /> </div> )); class App extends React.Component { render() { return <InnerRefed ref={r => (this.ref = r)} />; } } const renderer = ReactTestRenderer.create(<App />); const tree = renderer.toTree(); cleanNodeOrArray(tree); expect(prettyFormat(tree)).toEqual( prettyFormat({ instance: null, nodeType: 'component', props: {}, rendered: { instance: null, nodeType: 'host', props: {}, rendered: [ { instance: null, nodeType: 'host', props: {}, rendered: [], type: 'span', }, ], type: 'div', }, type: App, }), ); }); it('can concurrently render context with a "primary" renderer', async () => { const Context = React.createContext(null); const Indirection = React.Fragment; const App = () => ( <Context.Provider value={null}> <Indirection> <Context.Consumer>{() => null}</Context.Consumer> </Indirection> </Context.Provider> ); ReactNoop.render(<App />); await waitForAll([]); ReactTestRenderer.create(<App />); }); it('calling findByType() with an invalid component will fall back to "Unknown" for component name', () => { const App = () => null; const renderer = ReactTestRenderer.create(<App />); const NonComponent = {}; expect(() => { renderer.root.findByType(NonComponent); }).toThrowError(`No instances found with node type: "Unknown"`); }); });
23.739713
109
0.502901
cybersecurity-penetration-testing
/** * 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. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; import { insertNodesAndExecuteScripts, mergeOptions, stripExternalRuntimeInNodes, withLoadingReadyState, getVisibleChildren, } from '../test-utils/FizzTestUtils'; let JSDOM; let Stream; let Scheduler; let React; let ReactDOM; let ReactDOMClient; let ReactDOMFizzServer; let ReactDOMFizzStatic; let Suspense; let SuspenseList; let useSyncExternalStore; let useSyncExternalStoreWithSelector; let use; let useFormState; let PropTypes; let textCache; let writable; let CSPnonce = null; let container; let buffer = ''; let hasErrored = false; let fatalError = undefined; let renderOptions; let waitFor; let waitForAll; let assertLog; let waitForPaint; let clientAct; let streamingContainer; describe('ReactDOMFizzServer', () => { beforeEach(() => { jest.resetModules(); JSDOM = require('jsdom').JSDOM; const jsdom = new JSDOM( '<!DOCTYPE html><html><head></head><body><div id="container">', { runScripts: 'dangerously', }, ); // We mock matchMedia. for simplicity it only matches 'all' or '' and misses everything else Object.defineProperty(jsdom.window, 'matchMedia', { writable: true, value: jest.fn().mockImplementation(query => ({ matches: query === 'all' || query === '', media: query, })), }); streamingContainer = null; global.window = jsdom.window; global.document = global.window.document; global.navigator = global.window.navigator; global.Node = global.window.Node; global.addEventListener = global.window.addEventListener; global.MutationObserver = global.window.MutationObserver; container = document.getElementById('container'); Scheduler = require('scheduler'); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMFizzServer = require('react-dom/server'); if (__EXPERIMENTAL__) { ReactDOMFizzStatic = require('react-dom/static'); } Stream = require('stream'); Suspense = React.Suspense; use = React.use; if (gate(flags => flags.enableSuspenseList)) { SuspenseList = React.unstable_SuspenseList; } useFormState = ReactDOM.useFormState; PropTypes = require('prop-types'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForPaint = InternalTestUtils.waitForPaint; assertLog = InternalTestUtils.assertLog; clientAct = InternalTestUtils.act; if (gate(flags => flags.source)) { // The `with-selector` module composes the main `use-sync-external-store` // entrypoint. In the compiled artifacts, this is resolved to the `shim` // implementation by our build config, but when running the tests against // the source files, we need to tell Jest how to resolve it. Because this // is a source module, this mock has no affect on the build tests. jest.mock('use-sync-external-store/src/useSyncExternalStore', () => jest.requireActual('react'), ); } useSyncExternalStore = React.useSyncExternalStore; useSyncExternalStoreWithSelector = require('use-sync-external-store/with-selector').useSyncExternalStoreWithSelector; textCache = new Map(); buffer = ''; hasErrored = false; writable = new Stream.PassThrough(); writable.setEncoding('utf8'); writable.on('data', chunk => { buffer += chunk; }); writable.on('error', error => { hasErrored = true; fatalError = error; }); renderOptions = {}; if (gate(flags => flags.enableFizzExternalRuntime)) { renderOptions.unstable_externalRuntimeSrc = 'react-dom-bindings/src/server/ReactDOMServerExternalRuntime.js'; } }); function expectErrors(errorsArr, toBeDevArr, toBeProdArr) { const mappedErrows = errorsArr.map(({error, errorInfo}) => { const stack = errorInfo && errorInfo.componentStack; const digest = error.digest; if (stack) { return [error.message, digest, normalizeCodeLocInfo(stack)]; } else if (digest) { return [error.message, digest]; } return error.message; }); if (__DEV__) { expect(mappedErrows).toEqual(toBeDevArr); } else { expect(mappedErrows).toEqual(toBeProdArr); } } function componentStack(components) { return components .map(component => `\n in ${component} (at **)`) .join(''); } const bodyStartMatch = /<body(?:>| .*?>)/; const headStartMatch = /<head(?:>| .*?>)/; async function act(callback) { await callback(); // Await one turn around the event loop. // This assumes that we'll flush everything we have so far. await new Promise(resolve => { setImmediate(resolve); }); if (hasErrored) { throw fatalError; } // JSDOM doesn't support stream HTML parser so we need to give it a proper fragment. // We also want to execute any scripts that are embedded. // We assume that we have now received a proper fragment of HTML. let bufferedContent = buffer; buffer = ''; if (!bufferedContent) { return; } await withLoadingReadyState(async () => { const bodyMatch = bufferedContent.match(bodyStartMatch); const headMatch = bufferedContent.match(headStartMatch); if (streamingContainer === null) { // This is the first streamed content. We decide here where to insert it. If we get <html>, <head>, or <body> // we abandon the pre-built document and start from scratch. If we get anything else we assume it goes into the // container. This is not really production behavior because you can't correctly stream into a deep div effectively // but it's pragmatic for tests. if ( bufferedContent.startsWith('<head>') || bufferedContent.startsWith('<head ') || bufferedContent.startsWith('<body>') || bufferedContent.startsWith('<body ') ) { // wrap in doctype to normalize the parsing process bufferedContent = '<!DOCTYPE html><html>' + bufferedContent; } else if ( bufferedContent.startsWith('<html>') || bufferedContent.startsWith('<html ') ) { throw new Error( 'Recieved <html> without a <!DOCTYPE html> which is almost certainly a bug in React', ); } if (bufferedContent.startsWith('<!DOCTYPE html>')) { // we can just use the whole document const tempDom = new JSDOM(bufferedContent); // Wipe existing head and body content document.head.innerHTML = ''; document.body.innerHTML = ''; // Copy the <html> attributes over const tempHtmlNode = tempDom.window.document.documentElement; for (let i = 0; i < tempHtmlNode.attributes.length; i++) { const attr = tempHtmlNode.attributes[i]; document.documentElement.setAttribute(attr.name, attr.value); } if (headMatch) { // We parsed a head open tag. we need to copy head attributes and insert future // content into <head> streamingContainer = document.head; const tempHeadNode = tempDom.window.document.head; for (let i = 0; i < tempHeadNode.attributes.length; i++) { const attr = tempHeadNode.attributes[i]; document.head.setAttribute(attr.name, attr.value); } const source = document.createElement('head'); source.innerHTML = tempHeadNode.innerHTML; await insertNodesAndExecuteScripts(source, document.head, CSPnonce); } if (bodyMatch) { // We parsed a body open tag. we need to copy head attributes and insert future // content into <body> streamingContainer = document.body; const tempBodyNode = tempDom.window.document.body; for (let i = 0; i < tempBodyNode.attributes.length; i++) { const attr = tempBodyNode.attributes[i]; document.body.setAttribute(attr.name, attr.value); } const source = document.createElement('body'); source.innerHTML = tempBodyNode.innerHTML; await insertNodesAndExecuteScripts(source, document.body, CSPnonce); } if (!headMatch && !bodyMatch) { throw new Error('expected <head> or <body> after <html>'); } } else { // we assume we are streaming into the default container' streamingContainer = container; const div = document.createElement('div'); div.innerHTML = bufferedContent; await insertNodesAndExecuteScripts(div, container, CSPnonce); } } else if (streamingContainer === document.head) { bufferedContent = '<!DOCTYPE html><html><head>' + bufferedContent; const tempDom = new JSDOM(bufferedContent); const tempHeadNode = tempDom.window.document.head; const source = document.createElement('head'); source.innerHTML = tempHeadNode.innerHTML; await insertNodesAndExecuteScripts(source, document.head, CSPnonce); if (bodyMatch) { streamingContainer = document.body; const tempBodyNode = tempDom.window.document.body; for (let i = 0; i < tempBodyNode.attributes.length; i++) { const attr = tempBodyNode.attributes[i]; document.body.setAttribute(attr.name, attr.value); } const bodySource = document.createElement('body'); bodySource.innerHTML = tempBodyNode.innerHTML; await insertNodesAndExecuteScripts( bodySource, document.body, CSPnonce, ); } } else { const div = document.createElement('div'); div.innerHTML = bufferedContent; await insertNodesAndExecuteScripts(div, streamingContainer, CSPnonce); } }, document); } function resolveText(text) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } } function rejectText(text, error) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'rejected', value: error, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'rejected'; record.value = error; thenable.pings.forEach(t => t()); } } function readText(text) { const record = textCache.get(text); if (record !== undefined) { switch (record.status) { case 'pending': throw record.value; case 'rejected': throw record.value; case 'resolved': return record.value; } } else { 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}) { return text; } function AsyncText({text}) { return readText(text); } function AsyncTextWrapped({as, text}) { const As = as; return <As>{readText(text)}</As>; } function renderToPipeableStream(jsx, options) { // Merge options with renderOptions, which may contain featureFlag specific behavior return ReactDOMFizzServer.renderToPipeableStream( jsx, mergeOptions(options, renderOptions), ); } it('should asynchronously load a lazy component', async () => { const originalConsoleError = console.error; const mockError = jest.fn(); console.error = (...args) => { if (args.length > 1) { if (typeof args[1] === 'object') { mockError(args[0].split('\n')[0]); return; } } mockError(...args.map(normalizeCodeLocInfo)); }; let resolveA; const LazyA = React.lazy(() => { return new Promise(r => { resolveA = r; }); }); let resolveB; const LazyB = React.lazy(() => { return new Promise(r => { resolveB = r; }); }); function TextWithPunctuation({text, punctuation}) { return <Text text={text + punctuation} />; } // This tests that default props of the inner element is resolved. TextWithPunctuation.defaultProps = { punctuation: '!', }; try { await act(() => { const {pipe} = renderToPipeableStream( <div> <div> <Suspense fallback={<Text text="Loading..." />}> <LazyA text="Hello" /> </Suspense> </div> <div> <Suspense fallback={<Text text="Loading..." />}> <LazyB text="world" /> </Suspense> </div> </div>, ); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <div>Loading...</div> <div>Loading...</div> </div>, ); await act(() => { resolveA({default: Text}); }); expect(getVisibleChildren(container)).toEqual( <div> <div>Hello</div> <div>Loading...</div> </div>, ); await act(() => { resolveB({default: TextWithPunctuation}); }); expect(getVisibleChildren(container)).toEqual( <div> <div>Hello</div> <div>world!</div> </div>, ); if (__DEV__) { expect(mockError).toHaveBeenCalledWith( 'Warning: %s: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.%s', 'TextWithPunctuation', '\n in TextWithPunctuation (at **)\n' + ' in Lazy (at **)\n' + ' in Suspense (at **)\n' + ' in div (at **)\n' + ' in div (at **)', ); } else { expect(mockError).not.toHaveBeenCalled(); } } finally { console.error = originalConsoleError; } }); it('#23331: does not warn about hydration mismatches if something suspended in an earlier sibling', async () => { const makeApp = () => { let resolve; const imports = new Promise(r => { resolve = () => r({default: () => <span id="async">async</span>}); }); const Lazy = React.lazy(() => imports); const App = () => ( <div> <Suspense fallback={<span>Loading...</span>}> <Lazy /> <span id="after">after</span> </Suspense> </div> ); return [App, resolve]; }; // Server-side const [App, resolve] = makeApp(); await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <span>Loading...</span> </div>, ); await act(() => { resolve(); }); expect(getVisibleChildren(container)).toEqual( <div> <span id="async">async</span> <span id="after">after</span> </div>, ); // Client-side const [HydrateApp, hydrateResolve] = makeApp(); await act(() => { ReactDOMClient.hydrateRoot(container, <HydrateApp />); }); expect(getVisibleChildren(container)).toEqual( <div> <span id="async">async</span> <span id="after">after</span> </div>, ); await act(() => { hydrateResolve(); }); expect(getVisibleChildren(container)).toEqual( <div> <span id="async">async</span> <span id="after">after</span> </div>, ); }); it('should support nonce for bootstrap and runtime scripts', async () => { CSPnonce = 'R4nd0m'; try { let resolve; const Lazy = React.lazy(() => { return new Promise(r => { resolve = r; }); }); await act(() => { const {pipe} = renderToPipeableStream( <div> <Suspense fallback={<Text text="Loading..." />}> <Lazy text="Hello" /> </Suspense> </div>, { nonce: 'R4nd0m', bootstrapScriptContent: 'function noop(){}', bootstrapScripts: [ 'init.js', {src: 'init2.js', integrity: 'init2hash'}, ], bootstrapModules: [ 'init.mjs', {src: 'init2.mjs', integrity: 'init2hash'}, ], }, ); pipe(writable); }); expect(getVisibleChildren(container)).toEqual([ <link rel="preload" fetchpriority="low" href="init.js" as="script" nonce={CSPnonce} />, <link rel="preload" fetchpriority="low" href="init2.js" as="script" nonce={CSPnonce} integrity="init2hash" />, <link rel="modulepreload" fetchpriority="low" href="init.mjs" nonce={CSPnonce} />, <link rel="modulepreload" fetchpriority="low" href="init2.mjs" nonce={CSPnonce} integrity="init2hash" />, <div>Loading...</div>, ]); // check that there are 6 scripts with a matching nonce: // The runtime script, an inline bootstrap script, two bootstrap scripts and two bootstrap modules expect( Array.from(container.getElementsByTagName('script')).filter( node => node.getAttribute('nonce') === CSPnonce, ).length, ).toEqual(6); await act(() => { resolve({default: Text}); }); expect(getVisibleChildren(container)).toEqual([ <link rel="preload" fetchpriority="low" href="init.js" as="script" nonce={CSPnonce} />, <link rel="preload" fetchpriority="low" href="init2.js" as="script" nonce={CSPnonce} integrity="init2hash" />, <link rel="modulepreload" fetchpriority="low" href="init.mjs" nonce={CSPnonce} />, <link rel="modulepreload" fetchpriority="low" href="init2.mjs" nonce={CSPnonce} integrity="init2hash" />, <div>Hello</div>, ]); } finally { CSPnonce = null; } }); it('should not automatically add nonce to rendered scripts', async () => { CSPnonce = 'R4nd0m'; try { await act(async () => { const {pipe} = renderToPipeableStream( <html> <body> <script nonce={CSPnonce}>{'try { foo() } catch (e) {} ;'}</script> <script nonce={CSPnonce} src="foo" async={true} /> <script src="bar" /> <script src="baz" integrity="qux" async={true} /> <script type="module" src="quux" async={true} /> <script type="module" src="corge" async={true} /> <script type="module" src="grault" integrity="garply" async={true} /> </body> </html>, { nonce: CSPnonce, }, ); pipe(writable); }); expect( stripExternalRuntimeInNodes( document.getElementsByTagName('script'), renderOptions.unstable_externalRuntimeSrc, ).map(n => n.outerHTML), ).toEqual([ `<script nonce="${CSPnonce}" src="foo" async=""></script>`, `<script src="baz" integrity="qux" async=""></script>`, `<script type="module" src="quux" async=""></script>`, `<script type="module" src="corge" async=""></script>`, `<script type="module" src="grault" integrity="garply" async=""></script>`, `<script nonce="${CSPnonce}">try { foo() } catch (e) {} ;</script>`, `<script src="bar"></script>`, ]); } finally { CSPnonce = null; } }); it('should client render a boundary if a lazy component rejects', async () => { let rejectComponent; const LazyComponent = React.lazy(() => { return new Promise((resolve, reject) => { rejectComponent = reject; }); }); function App({isClient}) { return ( <div> <Suspense fallback={<Text text="Loading..." />}> {isClient ? <Text text="Hello" /> : <LazyComponent text="Hello" />} </Suspense> </div> ); } let bootstrapped = false; const errors = []; window.__INIT__ = function () { bootstrapped = true; // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); }; const theError = new Error('Test'); const loggedErrors = []; function onError(x, errorInfo) { loggedErrors.push(x); return 'Hash of (' + x.message + ')'; } const expectedDigest = onError(theError); loggedErrors.length = 0; await act(() => { const {pipe} = renderToPipeableStream(<App isClient={false} />, { bootstrapScriptContent: '__INIT__();', onError, }); pipe(writable); }); expect(loggedErrors).toEqual([]); expect(bootstrapped).toBe(true); await waitForAll([]); // We're still loading because we're waiting for the server to stream more content. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); expect(loggedErrors).toEqual([]); await act(() => { rejectComponent(theError); }); expect(loggedErrors).toEqual([theError]); // We haven't ran the client hydration yet. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // Now we can client render it instead. await waitForAll([]); expectErrors( errors, [ [ theError.message, expectedDigest, componentStack(['Lazy', 'Suspense', 'div', 'App']), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], ], ); // The client rendered HTML is now in place. expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); expect(loggedErrors).toEqual([theError]); }); it('should asynchronously load a lazy element', async () => { let resolveElement; const lazyElement = React.lazy(() => { return new Promise(r => { resolveElement = r; }); }); await act(() => { const {pipe} = renderToPipeableStream( <div> <Suspense fallback={<Text text="Loading..." />}> {lazyElement} </Suspense> </div>, ); pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // Because there is no content inside the Suspense boundary that could've // been written, we expect to not see any additional partial data flushed // yet. expect( stripExternalRuntimeInNodes( container.childNodes, renderOptions.unstable_externalRuntimeSrc, ).length, ).toBe(1); await act(() => { resolveElement({default: <Text text="Hello" />}); }); expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); }); it('should client render a boundary if a lazy element rejects', async () => { let rejectElement; const element = <Text text="Hello" />; const lazyElement = React.lazy(() => { return new Promise((resolve, reject) => { rejectElement = reject; }); }); const theError = new Error('Test'); const loggedErrors = []; function onError(x, errorInfo) { loggedErrors.push(x); return 'hash of (' + x.message + ')'; } const expectedDigest = onError(theError); loggedErrors.length = 0; function App({isClient}) { return ( <div> <Suspense fallback={<Text text="Loading..." />}> {isClient ? element : lazyElement} </Suspense> </div> ); } await act(() => { const {pipe} = renderToPipeableStream( <App isClient={false} />, { onError, }, ); pipe(writable); }); expect(loggedErrors).toEqual([]); const errors = []; // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); // We're still loading because we're waiting for the server to stream more content. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); expect(loggedErrors).toEqual([]); await act(() => { rejectElement(theError); }); expect(loggedErrors).toEqual([theError]); // We haven't ran the client hydration yet. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // Now we can client render it instead. await waitForAll([]); expectErrors( errors, [ [ theError.message, expectedDigest, componentStack(['Lazy', 'Suspense', 'div', 'App']), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], ], ); // The client rendered HTML is now in place. // expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); expect(loggedErrors).toEqual([theError]); }); it('Errors in boundaries should be sent to the client and reported on client render - Error before flushing', async () => { function Indirection({level, children}) { if (level > 0) { return <Indirection level={level - 1}>{children}</Indirection>; } return children; } const theError = new Error('uh oh'); function Erroring({isClient}) { if (isClient) { return 'Hello World'; } throw theError; } function App({isClient}) { return ( <div> <Suspense fallback={<span>loading...</span>}> <Indirection level={2}> <Erroring isClient={isClient} /> </Indirection> </Suspense> </div> ); } const loggedErrors = []; function onError(x) { loggedErrors.push(x); return 'hash(' + x.message + ')'; } const expectedDigest = onError(theError); loggedErrors.length = 0; await act(() => { const {pipe} = renderToPipeableStream( <App />, { onError, }, ); pipe(writable); }); expect(loggedErrors).toEqual([theError]); const errors = []; // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); expect(getVisibleChildren(container)).toEqual(<div>Hello World</div>); expectErrors( errors, [ [ theError.message, expectedDigest, componentStack([ 'Erroring', 'Indirection', 'Indirection', 'Indirection', 'Suspense', 'div', 'App', ]), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], ], ); }); it('Errors in boundaries should be sent to the client and reported on client render - Error after flushing', async () => { let rejectComponent; const LazyComponent = React.lazy(() => { return new Promise((resolve, reject) => { rejectComponent = reject; }); }); function App({isClient}) { return ( <div> <Suspense fallback={<Text text="Loading..." />}> {isClient ? <Text text="Hello" /> : <LazyComponent text="Hello" />} </Suspense> </div> ); } const loggedErrors = []; const theError = new Error('uh oh'); function onError(x) { loggedErrors.push(x); return 'hash(' + x.message + ')'; } const expectedDigest = onError(theError); loggedErrors.length = 0; await act(() => { const {pipe} = renderToPipeableStream( <App />, { onError, }, ); pipe(writable); }); expect(loggedErrors).toEqual([]); const errors = []; // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); await act(() => { rejectComponent(theError); }); expect(loggedErrors).toEqual([theError]); expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // Now we can client render it instead. await waitForAll([]); expectErrors( errors, [ [ theError.message, expectedDigest, componentStack(['Lazy', 'Suspense', 'div', 'App']), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], ], ); // The client rendered HTML is now in place. expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); expect(loggedErrors).toEqual([theError]); }); it('should asynchronously load the suspense boundary', async () => { await act(() => { const {pipe} = renderToPipeableStream( <div> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="Hello World" /> </Suspense> </div>, ); pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); await act(() => { resolveText('Hello World'); }); expect(getVisibleChildren(container)).toEqual(<div>Hello World</div>); }); it('waits for pending content to come in from the server and then hydrates it', async () => { const ref = React.createRef(); function App() { return ( <div> <Suspense fallback="Loading..."> <h1 ref={ref}> <AsyncText text="Hello" /> </h1> </Suspense> </div> ); } let bootstrapped = false; window.__INIT__ = function () { bootstrapped = true; // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App />); }; await act(() => { const {pipe} = renderToPipeableStream(<App />, { bootstrapScriptContent: '__INIT__();', }); pipe(writable); }); // We're still showing a fallback. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // We already bootstrapped. expect(bootstrapped).toBe(true); // Attempt to hydrate the content. await waitForAll([]); // We're still loading because we're waiting for the server to stream more content. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // The server now updates the content in place in the fallback. await act(() => { resolveText('Hello'); }); // The final HTML is now in place. expect(getVisibleChildren(container)).toEqual( <div> <h1>Hello</h1> </div>, ); const h1 = container.getElementsByTagName('h1')[0]; // But it is not yet hydrated. expect(ref.current).toBe(null); await waitForAll([]); // Now it's hydrated. expect(ref.current).toBe(h1); }); it('handles an error on the client if the server ends up erroring', async () => { const ref = React.createRef(); class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <b ref={ref}>{this.state.error.message}</b>; } return this.props.children; } } function App() { return ( <ErrorBoundary> <div> <Suspense fallback="Loading..."> <span ref={ref}> <AsyncText text="This Errors" /> </span> </Suspense> </div> </ErrorBoundary> ); } const loggedErrors = []; // We originally suspend the boundary and start streaming the loading state. await act(() => { const {pipe} = renderToPipeableStream( <App />, { onError(x) { loggedErrors.push(x); }, }, ); pipe(writable); }); // We're still showing a fallback. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); expect(loggedErrors).toEqual([]); // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App />); await waitForAll([]); // We're still loading because we're waiting for the server to stream more content. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); const theError = new Error('Error Message'); await act(() => { rejectText('This Errors', theError); }); expect(loggedErrors).toEqual([theError]); // The server errored, but we still haven't hydrated. We don't know if the // client will succeed yet, so we still show the loading state. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); expect(ref.current).toBe(null); // Flush the hydration. await waitForAll([]); // Hydrating should've generated an error and replaced the suspense boundary. expect(getVisibleChildren(container)).toEqual(<b>Error Message</b>); const b = container.getElementsByTagName('b')[0]; expect(ref.current).toBe(b); }); // @gate enableSuspenseList it('shows inserted items before pending in a SuspenseList as fallbacks while hydrating', async () => { const ref = React.createRef(); // These are hoisted to avoid them from rerendering. const a = ( <Suspense fallback="Loading A"> <span ref={ref}> <AsyncText text="A" /> </span> </Suspense> ); const b = ( <Suspense fallback="Loading B"> <span> <Text text="B" /> </span> </Suspense> ); function App({showMore}) { return ( <SuspenseList revealOrder="forwards"> {a} {b} {showMore ? ( <Suspense fallback="Loading C"> <span>C</span> </Suspense> ) : null} </SuspenseList> ); } // We originally suspend the boundary and start streaming the loading state. await act(() => { const {pipe} = renderToPipeableStream(<App showMore={false} />); pipe(writable); }); const root = ReactDOMClient.hydrateRoot( container, <App showMore={false} />, ); await waitForAll([]); // We're not hydrated yet. expect(ref.current).toBe(null); expect(getVisibleChildren(container)).toEqual([ 'Loading A', // TODO: This is incorrect. It should be "Loading B" but Fizz SuspenseList // isn't implemented fully yet. <span>B</span>, ]); // Add more rows before we've hydrated the first two. root.render(<App showMore={true} />); await waitForAll([]); // We're not hydrated yet. expect(ref.current).toBe(null); // We haven't resolved yet. expect(getVisibleChildren(container)).toEqual([ 'Loading A', // TODO: This is incorrect. It should be "Loading B" but Fizz SuspenseList // isn't implemented fully yet. <span>B</span>, 'Loading C', ]); await act(async () => { await resolveText('A'); }); await waitForAll([]); expect(getVisibleChildren(container)).toEqual([ <span>A</span>, <span>B</span>, <span>C</span>, ]); const span = container.getElementsByTagName('span')[0]; expect(ref.current).toBe(span); }); it('client renders a boundary if it does not resolve before aborting', async () => { function App() { return ( <div> <Suspense fallback="Loading..."> <h1> <AsyncText text="Hello" /> </h1> </Suspense> <main> <Suspense fallback="loading..."> <AsyncText text="World" /> </Suspense> </main> </div> ); } const loggedErrors = []; const expectedDigest = 'Hash for Abort'; function onError(error) { loggedErrors.push(error); return expectedDigest; } let controls; await act(() => { controls = renderToPipeableStream(<App />, {onError}); controls.pipe(writable); }); // We're still showing a fallback. const errors = []; // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); // We're still loading because we're waiting for the server to stream more content. expect(getVisibleChildren(container)).toEqual( <div> Loading...<main>loading...</main> </div>, ); // We abort the server response. await act(() => { controls.abort(); }); // We still can't render it on the client. await waitForAll([]); expectErrors( errors, [ [ 'The server did not finish this Suspense boundary: The render was aborted by the server without a reason.', expectedDigest, // We get the stack of the task when it was aborted which is why we see `h1` componentStack(['h1', 'Suspense', 'div', 'App']), ], [ 'The server did not finish this Suspense boundary: The render was aborted by the server without a reason.', expectedDigest, componentStack(['Suspense', 'main', 'div', 'App']), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], ], ); expect(getVisibleChildren(container)).toEqual( <div> Loading...<main>loading...</main> </div>, ); // We now resolve it on the client. await clientAct(() => { resolveText('Hello'); resolveText('World'); }); assertLog([]); // The client rendered HTML is now in place. expect(getVisibleChildren(container)).toEqual( <div> <h1>Hello</h1> <main>World</main> </div>, ); }); it('should allow for two containers to be written to the same document', async () => { // We create two passthrough streams for each container to write into. // Notably we don't implement a end() call for these. Because we don't want to // close the underlying stream just because one of the streams is done. Instead // we manually close when both are done. const writableA = new Stream.Writable(); writableA._write = (chunk, encoding, next) => { writable.write(chunk, encoding, next); }; const writableB = new Stream.Writable(); writableB._write = (chunk, encoding, next) => { writable.write(chunk, encoding, next); }; await act(() => { const {pipe} = renderToPipeableStream( // We use two nested boundaries to flush out coverage of an old reentrancy bug. <Suspense fallback="Loading..."> <Suspense fallback={<Text text="Loading A..." />}> <> <Text text="This will show A: " /> <div> <AsyncText text="A" /> </div> </> </Suspense> </Suspense>, { identifierPrefix: 'A_', onShellReady() { writableA.write('<div id="container-A">'); pipe(writableA); writableA.write('</div>'); }, }, ); }); await act(() => { const {pipe} = renderToPipeableStream( <Suspense fallback={<Text text="Loading B..." />}> <Text text="This will show B: " /> <div> <AsyncText text="B" /> </div> </Suspense>, { identifierPrefix: 'B_', onShellReady() { writableB.write('<div id="container-B">'); pipe(writableB); writableB.write('</div>'); }, }, ); }); expect(getVisibleChildren(container)).toEqual([ <div id="container-A">Loading A...</div>, <div id="container-B">Loading B...</div>, ]); await act(() => { resolveText('B'); }); expect(getVisibleChildren(container)).toEqual([ <div id="container-A">Loading A...</div>, <div id="container-B"> This will show B: <div>B</div> </div>, ]); await act(() => { resolveText('A'); }); // We're done writing both streams now. writable.end(); expect(getVisibleChildren(container)).toEqual([ <div id="container-A"> This will show A: <div>A</div> </div>, <div id="container-B"> This will show B: <div>B</div> </div>, ]); }); it('can resolve async content in esoteric parents', async () => { function AsyncOption({text}) { return <option>{readText(text)}</option>; } function AsyncCol({className}) { return <col className={readText(className)} />; } function AsyncPath({id}) { return <path id={readText(id)} />; } function AsyncMi({id}) { return <mi id={readText(id)} />; } function App() { return ( <div> <select> <Suspense fallback="Loading..."> <AsyncOption text="Hello" /> </Suspense> </select> <Suspense fallback="Loading..."> <table> <colgroup> <AsyncCol className="World" /> </colgroup> </table> <svg> <g> <AsyncPath id="my-path" /> </g> </svg> <math> <AsyncMi id="my-mi" /> </math> </Suspense> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <select>Loading...</select>Loading... </div>, ); await act(() => { resolveText('Hello'); }); await act(() => { resolveText('World'); }); await act(() => { resolveText('my-path'); resolveText('my-mi'); }); expect(getVisibleChildren(container)).toEqual( <div> <select> <option>Hello</option> </select> <table> <colgroup> <col class="World" /> </colgroup> </table> <svg> <g> <path id="my-path" /> </g> </svg> <math> <mi id="my-mi" /> </math> </div>, ); expect(container.querySelector('#my-path').namespaceURI).toBe( 'http://www.w3.org/2000/svg', ); expect(container.querySelector('#my-mi').namespaceURI).toBe( 'http://www.w3.org/1998/Math/MathML', ); }); it('can resolve async content in table parents', async () => { function AsyncTableBody({className, children}) { return <tbody className={readText(className)}>{children}</tbody>; } function AsyncTableRow({className, children}) { return <tr className={readText(className)}>{children}</tr>; } function AsyncTableCell({text}) { return <td>{readText(text)}</td>; } function App() { return ( <table> <Suspense fallback={ <tbody> <tr> <td>Loading...</td> </tr> </tbody> }> <AsyncTableBody className="A"> <AsyncTableRow className="B"> <AsyncTableCell text="C" /> </AsyncTableRow> </AsyncTableBody> </Suspense> </table> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <table> <tbody> <tr> <td>Loading...</td> </tr> </tbody> </table>, ); await act(() => { resolveText('A'); }); await act(() => { resolveText('B'); }); await act(() => { resolveText('C'); }); expect(getVisibleChildren(container)).toEqual( <table> <tbody class="A"> <tr class="B"> <td>C</td> </tr> </tbody> </table>, ); }); it('can stream into an SVG container', async () => { function AsyncPath({id}) { return <path id={readText(id)} />; } function App() { return ( <g> <Suspense fallback={<text>Loading...</text>}> <AsyncPath id="my-path" /> </Suspense> </g> ); } await act(() => { const {pipe} = renderToPipeableStream( <App />, { namespaceURI: 'http://www.w3.org/2000/svg', onShellReady() { writable.write('<svg>'); pipe(writable); writable.write('</svg>'); }, }, ); }); expect(getVisibleChildren(container)).toEqual( <svg> <g> <text>Loading...</text> </g> </svg>, ); await act(() => { resolveText('my-path'); }); expect(getVisibleChildren(container)).toEqual( <svg> <g> <path id="my-path" /> </g> </svg>, ); expect(container.querySelector('#my-path').namespaceURI).toBe( 'http://www.w3.org/2000/svg', ); }); function normalizeCodeLocInfo(str) { return ( str && String(str).replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) { return '\n in ' + name + ' (at **)'; }) ); } it('should include a component stack across suspended boundaries', async () => { function B() { const children = [readText('Hello'), readText('World')]; // Intentionally trigger a key warning here. return ( <div> {children.map(t => ( <span>{t}</span> ))} </div> ); } function C() { return ( <inCorrectTag> <Text text="Loading" /> </inCorrectTag> ); } function A() { return ( <div> <Suspense fallback={<C />}> <B /> </Suspense> </div> ); } // We can't use the toErrorDev helper here because this is an async act. const originalConsoleError = console.error; const mockError = jest.fn(); console.error = (...args) => { mockError(...args.map(normalizeCodeLocInfo)); }; try { await act(() => { const {pipe} = renderToPipeableStream(<A />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <incorrecttag>Loading</incorrecttag> </div>, ); if (__DEV__) { expect(mockError).toHaveBeenCalledWith( 'Warning: <%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.%s', 'inCorrectTag', '\n' + ' in inCorrectTag (at **)\n' + ' in C (at **)\n' + ' in Suspense (at **)\n' + ' in div (at **)\n' + ' in A (at **)', ); mockError.mockClear(); } else { expect(mockError).not.toHaveBeenCalled(); } await act(() => { resolveText('Hello'); resolveText('World'); }); if (__DEV__) { expect(mockError).toHaveBeenCalledWith( 'Warning: Each child in a list should have a unique "key" prop.%s%s' + ' See https://reactjs.org/link/warning-keys for more information.%s', '\n\nCheck the top-level render call using <div>.', '', '\n' + ' in span (at **)\n' + ' in B (at **)\n' + ' in Suspense (at **)\n' + ' in div (at **)\n' + ' in A (at **)', ); } else { expect(mockError).not.toHaveBeenCalled(); } expect(getVisibleChildren(container)).toEqual( <div> <div> <span>Hello</span> <span>World</span> </div> </div>, ); } finally { console.error = originalConsoleError; } }); // @gate !disableLegacyContext it('should can suspend in a class component with legacy context', async () => { class TestProvider extends React.Component { static childContextTypes = { test: PropTypes.string, }; state = {ctxToSet: null}; static getDerivedStateFromProps(props, state) { return {ctxToSet: props.ctx}; } getChildContext() { return { test: this.state.ctxToSet, }; } render() { return this.props.children; } } class TestConsumer extends React.Component { static contextTypes = { test: PropTypes.string, }; render() { const child = ( <b> <Text text={this.context.test} /> </b> ); if (this.props.prefix) { return [readText(this.props.prefix), child]; } return child; } } await act(() => { const {pipe} = renderToPipeableStream( <TestProvider ctx="A"> <div> <Suspense fallback={[<Text text="Loading: " />, <TestConsumer />]}> <TestProvider ctx="B"> <TestConsumer prefix="Hello: " /> </TestProvider> <TestConsumer /> </Suspense> </div> </TestProvider>, ); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> Loading: <b>A</b> </div>, ); await act(() => { resolveText('Hello: '); }); expect(getVisibleChildren(container)).toEqual( <div> Hello: <b>B</b> <b>A</b> </div>, ); }); it('should resume the context from where it left off', async () => { const ContextA = React.createContext('A0'); const ContextB = React.createContext('B0'); function PrintA() { return ( <ContextA.Consumer>{value => <Text text={value} />}</ContextA.Consumer> ); } class PrintB extends React.Component { static contextType = ContextB; render() { return <Text text={this.context} />; } } function AsyncParent({text, children}) { return ( <> <AsyncText text={text} /> <b>{children}</b> </> ); } await act(() => { const {pipe} = renderToPipeableStream( <div> <PrintA /> <div> <ContextA.Provider value="A0.1"> <Suspense fallback={<Text text="Loading..." />}> <AsyncParent text="Child:"> <PrintA /> </AsyncParent> <PrintB /> </Suspense> </ContextA.Provider> </div> <PrintA /> </div>, ); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> A0<div>Loading...</div>A0 </div>, ); await act(() => { resolveText('Child:'); }); expect(getVisibleChildren(container)).toEqual( <div> A0 <div> Child:<b>A0.1</b>B0 </div> A0 </div>, ); }); it('should recover the outer context when an error happens inside a provider', async () => { const ContextA = React.createContext('A0'); const ContextB = React.createContext('B0'); function PrintA() { return ( <ContextA.Consumer>{value => <Text text={value} />}</ContextA.Consumer> ); } class PrintB extends React.Component { static contextType = ContextB; render() { return <Text text={this.context} />; } } function Throws() { const value = React.useContext(ContextA); throw new Error(value); } const loggedErrors = []; await act(() => { const {pipe} = renderToPipeableStream( <div> <PrintA /> <div> <ContextA.Provider value="A0.1"> <Suspense fallback={ <b> <Text text="Loading..." /> </b> }> <ContextA.Provider value="A0.1.1"> <Throws /> </ContextA.Provider> </Suspense> <PrintB /> </ContextA.Provider> </div> <PrintA /> </div>, { onError(x) { loggedErrors.push(x); }, }, ); pipe(writable); }); expect(loggedErrors.length).toBe(1); expect(loggedErrors[0].message).toEqual('A0.1.1'); expect(getVisibleChildren(container)).toEqual( <div> A0 <div> <b>Loading...</b>B0 </div> A0 </div>, ); }); it('client renders a boundary if it errors before finishing the fallback', async () => { function App({isClient}) { return ( <Suspense fallback="Loading root..."> <div> <Suspense fallback={<AsyncText text="Loading..." />}> <h1> {isClient ? <Text text="Hello" /> : <AsyncText text="Hello" />} </h1> </Suspense> </div> </Suspense> ); } const theError = new Error('Test'); const loggedErrors = []; function onError(x) { loggedErrors.push(x); return `hash of (${x.message})`; } const expectedDigest = onError(theError); loggedErrors.length = 0; let controls; await act(() => { controls = renderToPipeableStream( <App isClient={false} />, { onError, }, ); controls.pipe(writable); }); // We're still showing a fallback. const errors = []; // Attempt to hydrate the content. ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); // We're still loading because we're waiting for the server to stream more content. expect(getVisibleChildren(container)).toEqual('Loading root...'); expect(loggedErrors).toEqual([]); // Error the content, but we don't have a fallback yet. await act(() => { rejectText('Hello', theError); }); expect(loggedErrors).toEqual([theError]); // We still can't render it on the client because we haven't unblocked the parent. await waitForAll([]); expect(getVisibleChildren(container)).toEqual('Loading root...'); // Unblock the loading state await act(() => { resolveText('Loading...'); }); // Now we're able to show the inner boundary. expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // That will let us client render it instead. await waitForAll([]); expectErrors( errors, [ [ theError.message, expectedDigest, componentStack([ 'AsyncText', 'h1', 'Suspense', 'div', 'Suspense', 'App', ]), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], ], ); // The client rendered HTML is now in place. expect(getVisibleChildren(container)).toEqual( <div> <h1>Hello</h1> </div>, ); expect(loggedErrors).toEqual([theError]); }); it('should be able to abort the fallback if the main content finishes first', async () => { await act(() => { const {pipe} = renderToPipeableStream( <Suspense fallback={<Text text="Loading Outer" />}> <div> <Suspense fallback={ <div> <AsyncText text="Loading" /> Inner </div> }> <AsyncText text="Hello" /> </Suspense> </div> </Suspense>, ); pipe(writable); }); expect(getVisibleChildren(container)).toEqual('Loading Outer'); // We should have received a partial segment containing the a partial of the fallback. expect(container.innerHTML).toContain('Inner'); await act(() => { resolveText('Hello'); }); // We should've been able to display the content without waiting for the rest of the fallback. expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); }); // @gate enableSuspenseAvoidThisFallbackFizz it('should respect unstable_avoidThisFallback', async () => { const resolved = { 0: false, 1: false, }; const promiseRes = {}; const promises = { 0: new Promise(res => { promiseRes[0] = () => { resolved[0] = true; res(); }; }), 1: new Promise(res => { promiseRes[1] = () => { resolved[1] = true; res(); }; }), }; const InnerComponent = ({isClient, depth}) => { if (isClient) { // Resuspend after re-rendering on client to check that fallback shows on client throw new Promise(() => {}); } if (!resolved[depth]) { throw promises[depth]; } return ( <div> <Text text={`resolved ${depth}`} /> </div> ); }; function App({isClient}) { return ( <div> <Text text="Non Suspense Content" /> <Suspense fallback={ <span> <Text text="Avoided Fallback" /> </span> } unstable_avoidThisFallback={true}> <InnerComponent isClient={isClient} depth={0} /> <div> <Suspense fallback={<Text text="Fallback" />}> <Suspense fallback={ <span> <Text text="Avoided Fallback2" /> </span> } unstable_avoidThisFallback={true}> <InnerComponent isClient={isClient} depth={1} /> </Suspense> </Suspense> </div> </Suspense> </div> ); } await jest.runAllTimers(); await act(() => { const {pipe} = renderToPipeableStream(<App isClient={false} />); pipe(writable); }); // Nothing is output since root has a suspense with avoidedThisFallback that hasn't resolved expect(getVisibleChildren(container)).toEqual(undefined); expect(container.innerHTML).not.toContain('Avoided Fallback'); // resolve first suspense component with avoidThisFallback await act(() => { promiseRes[0](); }); expect(getVisibleChildren(container)).toEqual( <div> Non Suspense Content <div>resolved 0</div> <div>Fallback</div> </div>, ); expect(container.innerHTML).not.toContain('Avoided Fallback2'); await act(() => { promiseRes[1](); }); expect(getVisibleChildren(container)).toEqual( <div> Non Suspense Content <div>resolved 0</div> <div> <div>resolved 1</div> </div> </div>, ); let root; await act(async () => { root = ReactDOMClient.hydrateRoot(container, <App isClient={false} />); await waitForAll([]); await jest.runAllTimers(); }); // No change after hydration expect(getVisibleChildren(container)).toEqual( <div> Non Suspense Content <div>resolved 0</div> <div> <div>resolved 1</div> </div> </div>, ); await act(async () => { // Trigger update by changing isClient to true root.render(<App isClient={true} />); await waitForAll([]); await jest.runAllTimers(); }); // Now that we've resuspended at the root we show the root fallback expect(getVisibleChildren(container)).toEqual( <div> Non Suspense Content <div style="display: none;">resolved 0</div> <div style="display: none;"> <div>resolved 1</div> </div> <span>Avoided Fallback</span> </div>, ); }); it('calls getServerSnapshot instead of getSnapshot', async () => { const ref = React.createRef(); function getServerSnapshot() { return 'server'; } function getClientSnapshot() { return 'client'; } function subscribe() { return () => {}; } function Child({text}) { Scheduler.log(text); return text; } function App() { const value = useSyncExternalStore( subscribe, getClientSnapshot, getServerSnapshot, ); return ( <div ref={ref}> <Child text={value} /> </div> ); } const loggedErrors = []; await act(() => { const {pipe} = renderToPipeableStream( <Suspense fallback="Loading..."> <App /> </Suspense>, { onError(x) { loggedErrors.push(x); }, }, ); pipe(writable); }); assertLog(['server']); ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('Log recoverable error: ' + error.message); }, }); await expect(async () => { // The first paint switches to client rendering due to mismatch await waitForPaint([ 'client', 'Log recoverable error: Hydration failed because the initial ' + 'UI does not match what was rendered on the server.', 'Log recoverable error: There was an error while hydrating. ' + 'Because the error happened outside of a Suspense boundary, the ' + 'entire root will switch to client rendering.', ]); }).toErrorDev( [ 'Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.', 'Warning: Expected server HTML to contain a matching <div> in <div>.\n' + ' in div (at **)\n' + ' in App (at **)', ], {withoutStack: 1}, ); expect(getVisibleChildren(container)).toEqual(<div>client</div>); }); // The selector implementation uses the lazy ref initialization pattern it('calls getServerSnapshot instead of getSnapshot (with selector and isEqual)', async () => { // Same as previous test, but with a selector that returns a complex object // that is memoized with a custom `isEqual` function. const ref = React.createRef(); function getServerSnapshot() { return {env: 'server', other: 'unrelated'}; } function getClientSnapshot() { return {env: 'client', other: 'unrelated'}; } function selector({env}) { return {env}; } function isEqual(a, b) { return a.env === b.env; } function subscribe() { return () => {}; } function Child({text}) { Scheduler.log(text); return text; } function App() { const {env} = useSyncExternalStoreWithSelector( subscribe, getClientSnapshot, getServerSnapshot, selector, isEqual, ); return ( <div ref={ref}> <Child text={env} /> </div> ); } const loggedErrors = []; await act(() => { const {pipe} = renderToPipeableStream( <Suspense fallback="Loading..."> <App /> </Suspense>, { onError(x) { loggedErrors.push(x); }, }, ); pipe(writable); }); assertLog(['server']); ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('Log recoverable error: ' + error.message); }, }); // The first paint uses the client due to mismatch forcing client render await expect(async () => { // The first paint switches to client rendering due to mismatch await waitForPaint([ 'client', 'Log recoverable error: Hydration failed because the initial ' + 'UI does not match what was rendered on the server.', 'Log recoverable error: There was an error while hydrating. ' + 'Because the error happened outside of a Suspense boundary, the ' + 'entire root will switch to client rendering.', ]); }).toErrorDev( [ 'Warning: An error occurred during hydration. The server HTML was replaced with client content', 'Warning: Expected server HTML to contain a matching <div> in <div>.\n' + ' in div (at **)\n' + ' in App (at **)', ], {withoutStack: 1}, ); expect(getVisibleChildren(container)).toEqual(<div>client</div>); }); it( 'errors during hydration in the shell force a client render at the ' + 'root, and during the client render it recovers', async () => { let isClient = false; function subscribe() { return () => {}; } function getClientSnapshot() { return 'Yay!'; } // At the time of writing, the only API that exposes whether it's currently // hydrating is the `getServerSnapshot` API, so I'm using that here to // simulate an error during hydration. function getServerSnapshot() { if (isClient) { throw new Error('Hydration error'); } return 'Yay!'; } function Child() { const value = useSyncExternalStore( subscribe, getClientSnapshot, getServerSnapshot, ); Scheduler.log(value); return value; } const spanRef = React.createRef(); function App() { return ( <span ref={spanRef}> <Child /> </span> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); assertLog(['Yay!']); const span = container.getElementsByTagName('span')[0]; // Hydrate the tree. Child will throw during hydration, but not when it // falls back to client rendering. isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log(error.message); }, }); // An error logged but instead of surfacing it to the UI, we switched // to client rendering. await expect(async () => { await waitForAll([ 'Yay!', 'Hydration error', 'There was an error while hydrating. Because the error happened ' + 'outside of a Suspense boundary, the entire root will switch ' + 'to client rendering.', ]); }).toErrorDev( 'An error occurred during hydration. The server HTML was replaced', {withoutStack: true}, ); expect(getVisibleChildren(container)).toEqual(<span>Yay!</span>); // The node that's inside the boundary that errored during hydration was // not hydrated. expect(spanRef.current).not.toBe(span); }, ); it('can hydrate uSES in StrictMode with different client and server snapshot (sync)', async () => { function subscribe() { return () => {}; } function getClientSnapshot() { return 'Yay!'; } function getServerSnapshot() { return 'Nay!'; } function App() { const value = useSyncExternalStore( subscribe, getClientSnapshot, getServerSnapshot, ); Scheduler.log(value); return value; } const element = ( <React.StrictMode> <App /> </React.StrictMode> ); await act(async () => { const {pipe} = renderToPipeableStream(element); pipe(writable); }); assertLog(['Nay!']); expect(getVisibleChildren(container)).toEqual('Nay!'); await clientAct(() => { ReactDOM.flushSync(() => { ReactDOMClient.hydrateRoot(container, element); }); }); expect(getVisibleChildren(container)).toEqual('Yay!'); assertLog(['Nay!', 'Yay!']); }); it('can hydrate uSES in StrictMode with different client and server snapshot (concurrent)', async () => { function subscribe() { return () => {}; } function getClientSnapshot() { return 'Yay!'; } function getServerSnapshot() { return 'Nay!'; } function App() { const value = useSyncExternalStore( subscribe, getClientSnapshot, getServerSnapshot, ); Scheduler.log(value); return value; } const element = ( <React.StrictMode> <App /> </React.StrictMode> ); await act(async () => { const {pipe} = renderToPipeableStream(element); pipe(writable); }); assertLog(['Nay!']); expect(getVisibleChildren(container)).toEqual('Nay!'); await clientAct(() => { React.startTransition(() => { ReactDOMClient.hydrateRoot(container, element); }); }); expect(getVisibleChildren(container)).toEqual('Yay!'); assertLog(['Nay!', 'Yay!']); }); it( 'errors during hydration force a client render at the nearest Suspense ' + 'boundary, and during the client render it recovers', async () => { let isClient = false; function subscribe() { return () => {}; } function getClientSnapshot() { return 'Yay!'; } // At the time of writing, the only API that exposes whether it's currently // hydrating is the `getServerSnapshot` API, so I'm using that here to // simulate an error during hydration. function getServerSnapshot() { if (isClient) { throw new Error('Hydration error'); } return 'Yay!'; } function Child() { const value = useSyncExternalStore( subscribe, getClientSnapshot, getServerSnapshot, ); Scheduler.log(value); return value; } const span1Ref = React.createRef(); const span2Ref = React.createRef(); const span3Ref = React.createRef(); function App() { return ( <div> <span ref={span1Ref} /> <Suspense fallback="Loading..."> <span ref={span2Ref}> <Child /> </span> </Suspense> <span ref={span3Ref} /> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); assertLog(['Yay!']); const [span1, span2, span3] = container.getElementsByTagName('span'); // Hydrate the tree. Child will throw during hydration, but not when it // falls back to client rendering. isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log(error.message); }, }); // An error logged but instead of surfacing it to the UI, we switched // to client rendering. await waitForAll([ 'Yay!', 'Hydration error', 'There was an error while hydrating this Suspense boundary. Switched to client rendering.', ]); expect(getVisibleChildren(container)).toEqual( <div> <span /> <span>Yay!</span> <span /> </div>, ); // The node that's inside the boundary that errored during hydration was // not hydrated. expect(span2Ref.current).not.toBe(span2); // But the nodes outside the boundary were. expect(span1Ref.current).toBe(span1); expect(span3Ref.current).toBe(span3); }, ); it( 'errors during hydration force a client render at the nearest Suspense ' + 'boundary, and during the client render it fails again', async () => { // Similar to previous test, but the client render errors, too. We should // be able to capture it with an error boundary. let isClient = false; class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error !== null) { return this.state.error.message; } return this.props.children; } } function Child() { if (isClient) { throw new Error('Oops!'); } Scheduler.log('Yay!'); return 'Yay!'; } const span1Ref = React.createRef(); const span2Ref = React.createRef(); const span3Ref = React.createRef(); function App() { return ( <ErrorBoundary> <span ref={span1Ref} /> <Suspense fallback="Loading..."> <span ref={span2Ref}> <Child /> </span> </Suspense> <span ref={span3Ref} /> </ErrorBoundary> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); assertLog(['Yay!']); // Hydrate the tree. Child will throw during render. isClient = true; const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); // Because we failed to recover from the error, onRecoverableError // shouldn't be called. await waitForAll([]); expect(getVisibleChildren(container)).toEqual('Oops!'); expectErrors(errors, [], []); }, ); // Disabled because of a WWW late mutations regression. // We may want to re-enable this if we figure out why. // @gate FIXME it('does not recreate the fallback if server errors and hydration suspends', async () => { let isClient = false; function Child() { if (isClient) { readText('Yay!'); } else { throw Error('Oops.'); } Scheduler.log('Yay!'); return 'Yay!'; } const fallbackRef = React.createRef(); function App() { return ( <div> <Suspense fallback={<p ref={fallbackRef}>Loading...</p>}> <span> <Child /> </span> </Suspense> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />, { onError(error) { Scheduler.log('[s!] ' + error.message); }, }); pipe(writable); }); assertLog(['[s!] Oops.']); // The server could not complete this boundary, so we'll retry on the client. const serverFallback = container.getElementsByTagName('p')[0]; expect(serverFallback.innerHTML).toBe('Loading...'); // Hydrate the tree. This will suspend. isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('[c!] ' + error.message); }, }); // This should not report any errors yet. await waitForAll([]); expect(getVisibleChildren(container)).toEqual( <div> <p>Loading...</p> </div>, ); // Normally, hydrating after server error would force a clean client render. // However, it suspended so at best we'd only get the same fallback anyway. // We don't want to recreate the same fallback in the DOM again because // that's extra work and would restart animations etc. Check we don't do that. const clientFallback = container.getElementsByTagName('p')[0]; expect(serverFallback).toBe(clientFallback); // When we're able to fully hydrate, we expect a clean client render. await act(() => { resolveText('Yay!'); }); await waitForAll([ 'Yay!', '[c!] The server could not finish this Suspense boundary, ' + 'likely due to an error during server rendering. ' + 'Switched to client rendering.', ]); expect(getVisibleChildren(container)).toEqual( <div> <span>Yay!</span> </div>, ); }); // Disabled because of a WWW late mutations regression. // We may want to re-enable this if we figure out why. // @gate FIXME it( 'does not recreate the fallback if server errors and hydration suspends ' + 'and root receives a transition', async () => { let isClient = false; function Child({color}) { if (isClient) { readText('Yay!'); } else { throw Error('Oops.'); } Scheduler.log('Yay! (' + color + ')'); return 'Yay! (' + color + ')'; } const fallbackRef = React.createRef(); function App({color}) { return ( <div> <Suspense fallback={<p ref={fallbackRef}>Loading...</p>}> <span> <Child color={color} /> </span> </Suspense> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App color="red" />, { onError(error) { Scheduler.log('[s!] ' + error.message); }, }); pipe(writable); }); assertLog(['[s!] Oops.']); // The server could not complete this boundary, so we'll retry on the client. const serverFallback = container.getElementsByTagName('p')[0]; expect(serverFallback.innerHTML).toBe('Loading...'); // Hydrate the tree. This will suspend. isClient = true; const root = ReactDOMClient.hydrateRoot(container, <App color="red" />, { onRecoverableError(error) { Scheduler.log('[c!] ' + error.message); }, }); // This should not report any errors yet. await waitForAll([]); expect(getVisibleChildren(container)).toEqual( <div> <p>Loading...</p> </div>, ); // Normally, hydrating after server error would force a clean client render. // However, it suspended so at best we'd only get the same fallback anyway. // We don't want to recreate the same fallback in the DOM again because // that's extra work and would restart animations etc. Check we don't do that. const clientFallback = container.getElementsByTagName('p')[0]; expect(serverFallback).toBe(clientFallback); // Transition updates shouldn't recreate the fallback either. React.startTransition(() => { root.render(<App color="blue" />); }); await waitForAll([]); jest.runAllTimers(); const clientFallback2 = container.getElementsByTagName('p')[0]; expect(clientFallback2).toBe(serverFallback); // When we're able to fully hydrate, we expect a clean client render. await act(() => { resolveText('Yay!'); }); await waitForAll([ 'Yay! (red)', '[c!] The server could not finish this Suspense boundary, ' + 'likely due to an error during server rendering. ' + 'Switched to client rendering.', 'Yay! (blue)', ]); expect(getVisibleChildren(container)).toEqual( <div> <span>Yay! (blue)</span> </div>, ); }, ); // Disabled because of a WWW late mutations regression. // We may want to re-enable this if we figure out why. // @gate FIXME it( 'recreates the fallback if server errors and hydration suspends but ' + 'client receives new props', async () => { let isClient = false; function Child() { const value = 'Yay!'; if (isClient) { readText(value); } else { throw Error('Oops.'); } Scheduler.log(value); return value; } const fallbackRef = React.createRef(); function App({fallbackText}) { return ( <div> <Suspense fallback={<p ref={fallbackRef}>{fallbackText}</p>}> <span> <Child /> </span> </Suspense> </div> ); } await act(() => { const {pipe} = renderToPipeableStream( <App fallbackText="Loading..." />, { onError(error) { Scheduler.log('[s!] ' + error.message); }, }, ); pipe(writable); }); assertLog(['[s!] Oops.']); const serverFallback = container.getElementsByTagName('p')[0]; expect(serverFallback.innerHTML).toBe('Loading...'); // Hydrate the tree. This will suspend. isClient = true; const root = ReactDOMClient.hydrateRoot( container, <App fallbackText="Loading..." />, { onRecoverableError(error) { Scheduler.log('[c!] ' + error.message); }, }, ); // This should not report any errors yet. await waitForAll([]); expect(getVisibleChildren(container)).toEqual( <div> <p>Loading...</p> </div>, ); // Normally, hydration after server error would force a clean client render. // However, that suspended so at best we'd only get a fallback anyway. // We don't want to replace a fallback with the same fallback because // that's extra work and would restart animations etc. Verify we don't do that. const clientFallback1 = container.getElementsByTagName('p')[0]; expect(serverFallback).toBe(clientFallback1); // However, an update may have changed the fallback props. In that case we have to // actually force it to re-render on the client and throw away the server one. root.render(<App fallbackText="More loading..." />); await waitForAll([]); jest.runAllTimers(); assertLog([ '[c!] The server could not finish this Suspense boundary, ' + 'likely due to an error during server rendering. ' + 'Switched to client rendering.', ]); expect(getVisibleChildren(container)).toEqual( <div> <p>More loading...</p> </div>, ); // This should be a clean render without reusing DOM. const clientFallback2 = container.getElementsByTagName('p')[0]; expect(clientFallback2).not.toBe(clientFallback1); // Verify we can still do a clean content render after. await act(() => { resolveText('Yay!'); }); await waitForAll(['Yay!']); expect(getVisibleChildren(container)).toEqual( <div> <span>Yay!</span> </div>, ); }, ); it( 'errors during hydration force a client render at the nearest Suspense ' + 'boundary, and during the client render it recovers, then a deeper ' + 'child suspends', async () => { let isClient = false; function subscribe() { return () => {}; } function getClientSnapshot() { return 'Yay!'; } // At the time of writing, the only API that exposes whether it's currently // hydrating is the `getServerSnapshot` API, so I'm using that here to // simulate an error during hydration. function getServerSnapshot() { if (isClient) { throw new Error('Hydration error'); } return 'Yay!'; } function Child() { const value = useSyncExternalStore( subscribe, getClientSnapshot, getServerSnapshot, ); if (isClient) { readText(value); } Scheduler.log(value); return value; } const span1Ref = React.createRef(); const span2Ref = React.createRef(); const span3Ref = React.createRef(); function App() { return ( <div> <span ref={span1Ref} /> <Suspense fallback="Loading..."> <span ref={span2Ref}> <Child /> </span> </Suspense> <span ref={span3Ref} /> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); assertLog(['Yay!']); const [span1, span2, span3] = container.getElementsByTagName('span'); // Hydrate the tree. Child will throw during hydration, but not when it // falls back to client rendering. isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log(error.message); }, }); // An error logged but instead of surfacing it to the UI, we switched // to client rendering. await waitForAll([ 'Hydration error', 'There was an error while hydrating this Suspense boundary. Switched ' + 'to client rendering.', ]); expect(getVisibleChildren(container)).toEqual( <div> <span /> Loading... <span /> </div>, ); await clientAct(() => { resolveText('Yay!'); }); assertLog(['Yay!']); expect(getVisibleChildren(container)).toEqual( <div> <span /> <span>Yay!</span> <span /> </div>, ); // The node that's inside the boundary that errored during hydration was // not hydrated. expect(span2Ref.current).not.toBe(span2); // But the nodes outside the boundary were. expect(span1Ref.current).toBe(span1); expect(span3Ref.current).toBe(span3); }, ); it('logs regular (non-hydration) errors when the UI recovers', async () => { let shouldThrow = true; function A() { if (shouldThrow) { Scheduler.log('Oops!'); throw new Error('Oops!'); } Scheduler.log('A'); return 'A'; } function B() { Scheduler.log('B'); return 'B'; } function App() { return ( <> <A /> <B /> </> ); } const root = ReactDOMClient.createRoot(container, { onRecoverableError(error) { Scheduler.log('Logged a recoverable error: ' + error.message); }, }); React.startTransition(() => { root.render(<App />); }); // Partially render A, but yield before the render has finished await waitFor(['Oops!', 'Oops!']); // React will try rendering again synchronously. During the retry, A will // not throw. This simulates a concurrent data race that is fixed by // blocking the main thread. shouldThrow = false; await waitForAll([ // Render again, synchronously 'A', 'B', // Log the error 'Logged a recoverable error: Oops!', ]); // UI looks normal expect(container.textContent).toEqual('AB'); }); it('logs multiple hydration errors in the same render', async () => { let isClient = false; function subscribe() { return () => {}; } function getClientSnapshot() { return 'Yay!'; } function getServerSnapshot() { if (isClient) { throw new Error('Hydration error'); } return 'Yay!'; } function Child({label}) { // This will throw during client hydration. Only reason to use // useSyncExternalStore in this test is because getServerSnapshot has the // ability to observe whether we're hydrating. useSyncExternalStore(subscribe, getClientSnapshot, getServerSnapshot); Scheduler.log(label); return label; } function App() { return ( <> <Suspense fallback="Loading..."> <Child label="A" /> </Suspense> <Suspense fallback="Loading..."> <Child label="B" /> </Suspense> </> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); assertLog(['A', 'B']); // Hydrate the tree. Child will throw during hydration, but not when it // falls back to client rendering. isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll([ 'A', 'B', 'Logged recoverable error: Hydration error', 'Logged recoverable error: There was an error while hydrating this ' + 'Suspense boundary. Switched to client rendering.', 'Logged recoverable error: Hydration error', 'Logged recoverable error: There was an error while hydrating this ' + 'Suspense boundary. Switched to client rendering.', ]); }); // @gate enableServerContext it('supports ServerContext', async () => { let ServerContext; function inlineLazyServerContextInitialization() { if (!ServerContext) { expect(() => { ServerContext = React.createServerContext('ServerContext', 'default'); }).toErrorDev( 'Server Context is deprecated and will soon be removed. ' + 'It was never documented and we have found it not to be useful ' + 'enough to warrant the downside it imposes on all apps.', ); } return ServerContext; } function Foo() { React.useState(); // component stack generation shouldn't reinit inlineLazyServerContextInitialization(); return ( <> <ServerContext.Provider value="hi this is server outer"> <ServerContext.Provider value="hi this is server"> <Bar /> </ServerContext.Provider> <ServerContext.Provider value="hi this is server2"> <Bar /> </ServerContext.Provider> <Bar /> </ServerContext.Provider> <ServerContext.Provider value="hi this is server outer2"> <Bar /> </ServerContext.Provider> <Bar /> </> ); } function Bar() { const context = React.useContext(inlineLazyServerContextInitialization()); return <span>{context}</span>; } await act(() => { const {pipe} = renderToPipeableStream(<Foo />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual([ <span>hi this is server</span>, <span>hi this is server2</span>, <span>hi this is server outer</span>, <span>hi this is server outer2</span>, <span>default</span>, ]); }); it('Supports iterable', async () => { const Immutable = require('immutable'); const mappedJSX = Immutable.fromJS([ {name: 'a', value: 'a'}, {name: 'b', value: 'b'}, ]).map(item => <li key={item.get('value')}>{item.get('name')}</li>); await act(() => { const {pipe} = renderToPipeableStream(<ul>{mappedJSX}</ul>); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <ul> <li>a</li> <li>b</li> </ul>, ); }); it('Supports custom abort reasons with a string', async () => { function App() { return ( <div> <p> <Suspense fallback={'p'}> <AsyncText text={'hello'} /> </Suspense> </p> <span> <Suspense fallback={'span'}> <AsyncText text={'world'} /> </Suspense> </span> </div> ); } let abort; const loggedErrors = []; await act(() => { const {pipe, abort: abortImpl} = renderToPipeableStream(<App />, { onError(error) { // In this test we contrive erroring with strings so we push the error whereas in most // other tests we contrive erroring with Errors and push the message. loggedErrors.push(error); return 'a digest'; }, }); abort = abortImpl; pipe(writable); }); expect(loggedErrors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> <p>p</p> <span>span</span> </div>, ); await act(() => { abort('foobar'); }); expect(loggedErrors).toEqual(['foobar', 'foobar']); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); expectErrors( errors, [ [ 'The server did not finish this Suspense boundary: foobar', 'a digest', componentStack(['Suspense', 'p', 'div', 'App']), ], [ 'The server did not finish this Suspense boundary: foobar', 'a digest', componentStack(['Suspense', 'span', 'div', 'App']), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'a digest', ], [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'a digest', ], ], ); }); it('Supports custom abort reasons with an Error', async () => { function App() { return ( <div> <p> <Suspense fallback={'p'}> <AsyncText text={'hello'} /> </Suspense> </p> <span> <Suspense fallback={'span'}> <AsyncText text={'world'} /> </Suspense> </span> </div> ); } let abort; const loggedErrors = []; await act(() => { const {pipe, abort: abortImpl} = renderToPipeableStream(<App />, { onError(error) { loggedErrors.push(error.message); return 'a digest'; }, }); abort = abortImpl; pipe(writable); }); expect(loggedErrors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> <p>p</p> <span>span</span> </div>, ); await act(() => { abort(new Error('uh oh')); }); expect(loggedErrors).toEqual(['uh oh', 'uh oh']); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); expectErrors( errors, [ [ 'The server did not finish this Suspense boundary: uh oh', 'a digest', componentStack(['Suspense', 'p', 'div', 'App']), ], [ 'The server did not finish this Suspense boundary: uh oh', 'a digest', componentStack(['Suspense', 'span', 'div', 'App']), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'a digest', ], [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'a digest', ], ], ); }); it('warns in dev if you access digest from errorInfo in onRecoverableError', async () => { await act(() => { const {pipe} = renderToPipeableStream( <div> <Suspense fallback={'loading...'}> <AsyncText text={'hello'} /> </Suspense> </div>, { onError(error) { return 'a digest'; }, }, ); rejectText('hello'); pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div>loading...</div>); ReactDOMClient.hydrateRoot( container, <div> <Suspense fallback={'loading...'}>hello</Suspense> </div>, { onRecoverableError(error, errorInfo) { expect(() => { expect(error.digest).toBe('a digest'); expect(errorInfo.digest).toBe('a digest'); }).toErrorDev( 'Warning: You are accessing "digest" from the errorInfo object passed to onRecoverableError.' + ' This property is deprecated and will be removed in a future version of React.' + ' To access the digest of an Error look for this property on the Error instance itself.', {withoutStack: true}, ); }, }, ); await waitForAll([]); }); it('takes an importMap option which emits an "importmap" script in the head', async () => { const importMap = { foo: './path/to/foo.js', }; await act(() => { renderToPipeableStream( <html> <head> <script async={true} src="foo" /> </head> <body> <div>hello world</div> </body> </html>, { importMap, }, ).pipe(writable); }); expect(document.head.innerHTML).toBe( '<script type="importmap">' + JSON.stringify(importMap) + '</script><script async="" src="foo"></script>', ); }); // bugfix: https://github.com/facebook/react/issues/27286 affecting enableCustomElementPropertySupport flag it('can render custom elements with children on ther server', async () => { await act(() => { renderToPipeableStream( <html> <body> <my-element> <div>foo</div> </my-element> </body> </html>, ).pipe(writable); }); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body> <my-element> <div>foo</div> </my-element> </body> </html>, ); }); // https://github.com/facebook/react/issues/27540 // This test is not actually asserting much because there is possibly a bug in the closeing logic for the // Node implementation of Fizz. The close leads to an abort which sets the destination to null before the Float // method has an opportunity to schedule a write. We should fix this probably and once we do this test will start // to fail if the underyling issue of writing after stream completion isn't fixed it('does not try to write to the stream after it has been closed', async () => { async function preloadLate() { await 1; ReactDOM.preconnect('foo'); } function Preload() { preloadLate(); return null; } function App() { return ( <html> <body> <main>hello</main> <Preload /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />).pipe(writable); }); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body> <main>hello</main> </body> </html>, ); }); it('provides headers after initial work if onHeaders option used', async () => { let headers = null; function onHeaders(x) { headers = x; } function Preloads() { ReactDOM.preload('font2', {as: 'font'}); ReactDOM.preload('imagepre2', {as: 'image', fetchPriority: 'high'}); ReactDOM.preconnect('pre2', {crossOrigin: 'use-credentials'}); ReactDOM.prefetchDNS('dns2'); } function Blocked() { readText('blocked'); return ( <> <Preloads /> <img src="image2" /> </> ); } function App() { ReactDOM.preload('font', {as: 'font'}); ReactDOM.preload('imagepre', {as: 'image', fetchPriority: 'high'}); ReactDOM.preconnect('pre', {crossOrigin: 'use-credentials'}); ReactDOM.prefetchDNS('dns'); return ( <html> <body> <img src="image" /> <Blocked /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />, {onHeaders}); }); expect(headers).toEqual({ Link: ` <pre>; rel=preconnect; crossorigin="use-credentials", <dns>; rel=dns-prefetch, <font>; rel=preload; as="font"; crossorigin="", <imagepre>; rel=preload; as="image"; fetchpriority="high", <image>; rel=preload; as="image" ` .replaceAll('\n', '') .trim(), }); }); it('encodes img srcset and sizes into preload header params', async () => { let headers = null; function onHeaders(x) { headers = x; } function App() { ReactDOM.preload('presrc', { as: 'image', fetchPriority: 'high', imageSrcSet: 'presrcset', imageSizes: 'presizes', }); return ( <html> <body> <img src="src" srcSet="srcset" sizes="sizes" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />, {onHeaders}); }); expect(headers).toEqual({ Link: ` <presrc>; rel=preload; as="image"; fetchpriority="high"; imagesrcset="presrcset"; imagesizes="presizes", <src>; rel=preload; as="image"; imagesrcset="srcset"; imagesizes="sizes" ` .replaceAll('\n', '') .trim(), }); }); it('emits nothing for headers if you pipe before work begins', async () => { let headers = null; function onHeaders(x) { headers = x; } function App() { ReactDOM.preload('presrc', { as: 'image', fetchPriority: 'high', imageSrcSet: 'presrcset', imageSizes: 'presizes', }); return ( <html> <body> <img src="src" srcSet="srcset" sizes="sizes" /> </body> </html> ); } await act(() => { renderToPipeableStream(<App />, {onHeaders}).pipe(writable); }); expect(headers).toEqual({}); }); it('stops accumulating new headers once the maxHeadersLength limit is satisifed', async () => { let headers = null; function onHeaders(x) { headers = x; } function App() { ReactDOM.preconnect('foo'); ReactDOM.preconnect('bar'); ReactDOM.preconnect('baz'); return ( <html> <body>hello</body> </html> ); } await act(() => { renderToPipeableStream(<App />, {onHeaders, maxHeadersLength: 44}); }); expect(headers).toEqual({ Link: ` <foo>; rel=preconnect, <bar>; rel=preconnect ` .replaceAll('\n', '') .trim(), }); }); it('logs an error if onHeaders throws but continues the render', async () => { const errors = []; function onError(error) { errors.push(error.message); } function onHeaders(x) { throw new Error('bad onHeaders'); } let pipe; await act(() => { ({pipe} = renderToPipeableStream(<div>hello</div>, {onHeaders, onError})); }); expect(errors).toEqual(['bad onHeaders']); await act(() => { pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div>hello</div>); }); describe('error escaping', () => { it('escapes error hash, message, and component stack values in directly flushed errors (html escaping)', async () => { window.__outlet = {}; const dangerousErrorString = '"></template></div><script>window.__outlet.message="from error"</script><div><template data-foo="'; function Erroring() { throw new Error(dangerousErrorString); } // We can't test newline in component stacks because the stack always takes just one line and we end up // dropping the first part including the \n character Erroring.displayName = 'DangerousName' + dangerousErrorString.replace( 'message="from error"', 'stack="from_stack"', ); function App() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <Erroring /> </Suspense> </div> ); } function onError(x) { return `dangerous hash ${x.message.replace( 'message="from error"', 'hash="from hash"', )}`; } await act(() => { const {pipe} = renderToPipeableStream(<App />, { onError, }); pipe(writable); }); expect(window.__outlet).toEqual({}); }); it('escapes error hash, message, and component stack values in clientRenderInstruction (javascript escaping)', async () => { window.__outlet = {}; const dangerousErrorString = '");window.__outlet.message="from error";</script><script>(() => {})("'; let rejectComponent; const SuspensyErroring = React.lazy(() => { return new Promise((resolve, reject) => { rejectComponent = reject; }); }); // We can't test newline in component stacks because the stack always takes just one line and we end up // dropping the first part including the \n character SuspensyErroring.displayName = 'DangerousName' + dangerousErrorString.replace( 'message="from error"', 'stack="from_stack"', ); function App() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <SuspensyErroring /> </Suspense> </div> ); } function onError(x) { return `dangerous hash ${x.message.replace( 'message="from error"', 'hash="from hash"', )}`; } await act(() => { const {pipe} = renderToPipeableStream(<App />, { onError, }); pipe(writable); }); await act(() => { rejectComponent(new Error(dangerousErrorString)); }); expect(window.__outlet).toEqual({}); }); it('escapes such that attributes cannot be masked', async () => { const dangerousErrorString = '" data-msg="bad message" data-foo="'; const theError = new Error(dangerousErrorString); function Erroring({isClient}) { if (isClient) return 'Hello'; throw theError; } function App({isClient}) { return ( <div> <Suspense fallback={<div>Loading...</div>}> <Erroring isClient={isClient} /> </Suspense> </div> ); } const loggedErrors = []; function onError(x) { loggedErrors.push(x); return x.message.replace('bad message', 'bad hash'); } const expectedDigest = onError(theError); loggedErrors.length = 0; await act(() => { const {pipe} = renderToPipeableStream(<App />, { onError, }); pipe(writable); }); expect(loggedErrors).toEqual([theError]); const errors = []; ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error, errorInfo) { errors.push({error, errorInfo}); }, }); await waitForAll([]); // If escaping were not done we would get a message that says "bad hash" expectErrors( errors, [ [ theError.message, expectedDigest, componentStack(['Erroring', 'Suspense', 'div', 'App']), ], ], [ [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', expectedDigest, ], ], ); }); }); it('accepts an integrity property for bootstrapScripts and bootstrapModules', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <div>hello world</div> </body> </html>, { bootstrapScripts: [ 'foo', { src: 'bar', }, { src: 'baz', integrity: 'qux', }, ], bootstrapModules: [ 'quux', { src: 'corge', }, { src: 'grault', integrity: 'garply', }, ], }, ); pipe(writable); }); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="preload" fetchpriority="low" href="foo" as="script" /> <link rel="preload" fetchpriority="low" href="bar" as="script" /> <link rel="preload" fetchpriority="low" href="baz" as="script" integrity="qux" /> <link rel="modulepreload" fetchpriority="low" href="quux" /> <link rel="modulepreload" fetchpriority="low" href="corge" /> <link rel="modulepreload" fetchpriority="low" href="grault" integrity="garply" /> </head> <body> <div>hello world</div> </body> </html>, ); expect( stripExternalRuntimeInNodes( document.getElementsByTagName('script'), renderOptions.unstable_externalRuntimeSrc, ).map(n => n.outerHTML), ).toEqual([ '<script src="foo" async=""></script>', '<script src="bar" async=""></script>', '<script src="baz" integrity="qux" async=""></script>', '<script type="module" src="quux" async=""></script>', '<script type="module" src="corge" async=""></script>', '<script type="module" src="grault" integrity="garply" async=""></script>', ]); }); it('accepts a crossOrigin property for bootstrapScripts and bootstrapModules', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <div>hello world</div> </body> </html>, { bootstrapScripts: [ 'foo', { src: 'bar', }, { src: 'baz', crossOrigin: '', }, { src: 'qux', crossOrigin: 'defaults-to-empty', }, ], bootstrapModules: [ 'quux', { src: 'corge', }, { src: 'grault', crossOrigin: 'use-credentials', }, ], }, ); pipe(writable); }); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="preload" fetchpriority="low" href="foo" as="script" /> <link rel="preload" fetchpriority="low" href="bar" as="script" /> <link rel="preload" fetchpriority="low" href="baz" as="script" crossorigin="" /> <link rel="preload" fetchpriority="low" href="qux" as="script" crossorigin="" /> <link rel="modulepreload" fetchpriority="low" href="quux" /> <link rel="modulepreload" fetchpriority="low" href="corge" /> <link rel="modulepreload" fetchpriority="low" href="grault" crossorigin="use-credentials" /> </head> <body> <div>hello world</div> </body> </html>, ); expect( stripExternalRuntimeInNodes( document.getElementsByTagName('script'), renderOptions.unstable_externalRuntimeSrc, ).map(n => n.outerHTML), ).toEqual([ '<script src="foo" async=""></script>', '<script src="bar" async=""></script>', '<script src="baz" crossorigin="" async=""></script>', '<script src="qux" crossorigin="" async=""></script>', '<script type="module" src="quux" async=""></script>', '<script type="module" src="corge" async=""></script>', '<script type="module" src="grault" crossorigin="use-credentials" async=""></script>', ]); }); describe('bootstrapScriptContent and importMap escaping', () => { it('the "S" in "</?[Ss]cript" strings are replaced with unicode escaped lowercase s or S depending on case, preserving case sensitivity of nearby characters', async () => { window.__test_outlet = ''; const stringWithScriptsInIt = 'prescription pre<scription pre<Scription pre</scRipTion pre</ScripTion </script><script><!-- <script> -->'; await act(() => { const {pipe} = renderToPipeableStream(<div />, { bootstrapScriptContent: 'window.__test_outlet = "This should have been replaced";var x = "' + stringWithScriptsInIt + '";\nwindow.__test_outlet = x;', }); pipe(writable); }); expect(window.__test_outlet).toMatch(stringWithScriptsInIt); }); it('does not escape \\u2028, or \\u2029 characters', async () => { // these characters are ignored in engines support https://github.com/tc39/proposal-json-superset // in this test with JSDOM the characters are silently dropped and thus don't need to be encoded. // if you send these characters to an older browser they could fail so it is a good idea to // sanitize JSON input of these characters window.__test_outlet = ''; const el = document.createElement('p'); el.textContent = '{"one":1,\u2028\u2029"two":2}'; const stringWithLSAndPSCharacters = el.textContent; await act(() => { const {pipe} = renderToPipeableStream(<div />, { bootstrapScriptContent: 'let x = ' + stringWithLSAndPSCharacters + '; window.__test_outlet = x;', }); pipe(writable); }); const outletString = JSON.stringify(window.__test_outlet); expect(outletString).toBe( stringWithLSAndPSCharacters.replace(/[\u2028\u2029]/g, ''), ); }); it('does not escape <, >, or & characters', async () => { // these characters valid javascript and may be necessary in scripts and won't be interpretted properly // escaped outside of a string context within javascript window.__test_outlet = null; // this boolean expression will be cast to a number due to the bitwise &. we will look for a truthy value (1) below const booleanLogicString = '1 < 2 & 3 > 1'; await act(() => { const {pipe} = renderToPipeableStream(<div />, { bootstrapScriptContent: 'let x = ' + booleanLogicString + '; window.__test_outlet = x;', }); pipe(writable); }); expect(window.__test_outlet).toBe(1); }); it('escapes </[sS]cirpt> in importMaps', async () => { window.__test_outlet_key = ''; window.__test_outlet_value = ''; const jsonWithScriptsInIt = { "keypos</script><script>window.__test_outlet_key = 'pwned'</script><script>": 'value', key: "valuepos</script><script>window.__test_outlet_value = 'pwned'</script><script>", }; await act(() => { const {pipe} = renderToPipeableStream(<div />, { importMap: jsonWithScriptsInIt, }); pipe(writable); }); expect(window.__test_outlet_key).toBe(''); expect(window.__test_outlet_value).toBe(''); }); }); // @gate enableFizzExternalRuntime it('supports option to load runtime as an external script', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <Suspense fallback={'loading...'}> <AsyncText text="Hello" /> </Suspense> </body> </html>, { unstable_externalRuntimeSrc: 'src-of-external-runtime', }, ); pipe(writable); }); // We want the external runtime to be sent in <head> so the script can be // fetched and executed as early as possible. For SSR pages using Suspense, // this script execution would be render blocking. expect( Array.from(document.head.getElementsByTagName('script')).map( n => n.outerHTML, ), ).toEqual(['<script src="src-of-external-runtime" async=""></script>']); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>loading...</body> </html>, ); }); // @gate enableFizzExternalRuntime it('does not send script tags for SSR instructions when using the external runtime', async () => { function App() { return ( <div> <Suspense fallback="Loading..."> <div> <AsyncText text="Hello" /> </div> </Suspense> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); await act(() => { resolveText('Hello'); }); // The only script elements sent should be from unstable_externalRuntimeSrc expect(document.getElementsByTagName('script').length).toEqual(1); }); it('does not send the external runtime for static pages', async () => { await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> <p>hello world!</p> </body> </html>, ); pipe(writable); }); // no scripts should be sent expect(document.getElementsByTagName('script').length).toEqual(0); // the html should be as-is expect(document.documentElement.innerHTML).toEqual( '<head></head><body><p>hello world!</p></body>', ); }); it('#24384: Suspending should halt hydration warnings and not emit any if hydration completes successfully after unsuspending', async () => { const makeApp = () => { let resolve, resolved; const promise = new Promise(r => { resolve = () => { resolved = true; return r(); }; }); function ComponentThatSuspends() { if (!resolved) { throw promise; } return <p>A</p>; } const App = () => { return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <ComponentThatSuspends /> <h2 name="hello">world</h2> </Suspense> </div> ); }; return [App, resolve]; }; const [ServerApp, serverResolve] = makeApp(); await act(() => { const {pipe} = renderToPipeableStream(<ServerApp />); pipe(writable); }); await act(() => { serverResolve(); }); expect(getVisibleChildren(container)).toEqual( <div> <p>A</p> <h2 name="hello">world</h2> </div>, ); const [ClientApp, clientResolve] = makeApp(); ReactDOMClient.hydrateRoot(container, <ClientApp />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll([]); expect(getVisibleChildren(container)).toEqual( <div> <p>A</p> <h2 name="hello">world</h2> </div>, ); // Now that the boundary resolves to it's children the hydration completes and discovers that there is a mismatch requiring // client-side rendering. await clientResolve(); await waitForAll([]); expect(getVisibleChildren(container)).toEqual( <div> <p>A</p> <h2 name="hello">world</h2> </div>, ); }); // @gate enableClientRenderFallbackOnTextMismatch it('#24384: Suspending should halt hydration warnings but still emit hydration warnings after unsuspending if mismatches are genuine', async () => { const makeApp = () => { let resolve, resolved; const promise = new Promise(r => { resolve = () => { resolved = true; return r(); }; }); function ComponentThatSuspends() { if (!resolved) { throw promise; } return <p>A</p>; } const App = ({text}) => { return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <ComponentThatSuspends /> <h2 name={text}>{text}</h2> </Suspense> </div> ); }; return [App, resolve]; }; const [ServerApp, serverResolve] = makeApp(); await act(() => { const {pipe} = renderToPipeableStream(<ServerApp text="initial" />); pipe(writable); }); await act(() => { serverResolve(); }); expect(getVisibleChildren(container)).toEqual( <div> <p>A</p> <h2 name="initial">initial</h2> </div>, ); // The client app is rendered with an intentionally incorrect text. The still Suspended component causes // hydration to fail silently (allowing for cache warming but otherwise skipping this boundary) until it // resolves. const [ClientApp, clientResolve] = makeApp(); ReactDOMClient.hydrateRoot(container, <ClientApp text="replaced" />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll([]); expect(getVisibleChildren(container)).toEqual( <div> <p>A</p> <h2 name="initial">initial</h2> </div>, ); // Now that the boundary resolves to it's children the hydration completes and discovers that there is a mismatch requiring // client-side rendering. await clientResolve(); await expect(async () => { await waitForAll([ 'Logged recoverable error: Text content does not match server-rendered HTML.', 'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.', ]); }).toErrorDev( 'Warning: Text content did not match. Server: "initial" Client: "replaced', ); expect(getVisibleChildren(container)).toEqual( <div> <p>A</p> <h2 name="replaced">replaced</h2> </div>, ); await waitForAll([]); }); // @gate enableClientRenderFallbackOnTextMismatch it('only warns once on hydration mismatch while within a suspense boundary', async () => { const originalConsoleError = console.error; const mockError = jest.fn(); console.error = (...args) => { mockError(...args.map(normalizeCodeLocInfo)); }; const App = ({text}) => { return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <h2>{text}</h2> <h2>{text}</h2> <h2>{text}</h2> </Suspense> </div> ); }; try { await act(() => { const {pipe} = renderToPipeableStream(<App text="initial" />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <h2>initial</h2> <h2>initial</h2> <h2>initial</h2> </div>, ); ReactDOMClient.hydrateRoot(container, <App text="replaced" />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll([ 'Logged recoverable error: Text content does not match server-rendered HTML.', 'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.', ]); expect(getVisibleChildren(container)).toEqual( <div> <h2>replaced</h2> <h2>replaced</h2> <h2>replaced</h2> </div>, ); await waitForAll([]); if (__DEV__) { expect(mockError.mock.calls.length).toBe(1); expect(mockError.mock.calls[0]).toEqual([ 'Warning: Text content did not match. Server: "%s" Client: "%s"%s', 'initial', 'replaced', '\n' + ' in h2 (at **)\n' + ' in Suspense (at **)\n' + ' in div (at **)\n' + ' in App (at **)', ]); } else { expect(mockError.mock.calls.length).toBe(0); } } finally { console.error = originalConsoleError; } }); it('supresses hydration warnings when an error occurs within a Suspense boundary', async () => { let isClient = false; function ThrowWhenHydrating({children}) { // This is a trick to only throw if we're hydrating, because // useSyncExternalStore calls getServerSnapshot instead of the regular // getSnapshot in that case. useSyncExternalStore( () => {}, t => t, () => { if (isClient) { throw new Error('uh oh'); } }, ); return children; } const App = () => { return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <ThrowWhenHydrating> <h1>one</h1> </ThrowWhenHydrating> <h2>two</h2> <h3>{isClient ? 'five' : 'three'}</h3> </Suspense> </div> ); }; await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll([ 'Logged recoverable error: uh oh', 'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.', ]); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>five</h3> </div>, ); await waitForAll([]); }); // @gate __DEV__ it('does not invokeGuardedCallback for errors after the first hydration error', async () => { // We can't use the toErrorDev helper here because this is async. const originalConsoleError = console.error; const mockError = jest.fn(); console.error = (...args) => { if (args.length > 1) { if (typeof args[1] === 'object') { mockError(args[0].split('\n')[0]); return; } } mockError(...args.map(normalizeCodeLocInfo)); }; let isClient = false; function ThrowWhenHydrating({children, message}) { // This is a trick to only throw if we're hydrating, because // useSyncExternalStore calls getServerSnapshot instead of the regular // getSnapshot in that case. useSyncExternalStore( () => {}, t => t, () => { if (isClient) { Scheduler.log('throwing: ' + message); throw new Error(message); } }, ); return children; } const App = () => { return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <ThrowWhenHydrating message="first error"> <h1>one</h1> </ThrowWhenHydrating> <ThrowWhenHydrating message="second error"> <h2>two</h2> </ThrowWhenHydrating> <ThrowWhenHydrating message="third error"> <h3>three</h3> </ThrowWhenHydrating> </Suspense> </div> ); }; try { await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll([ 'throwing: first error', // this repeated first error is the invokeGuardedCallback throw 'throwing: first error', // onRecoverableError because the UI recovered without surfacing the // error to the user. 'Logged recoverable error: first error', 'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.', ]); // These Uncaught error calls are the error reported by the runtime (jsdom here, browser in actual use) // when invokeGuardedCallback is used to replay an error in dev using event dispatching in the document expect(mockError.mock.calls).toEqual([ // we only get one because we suppress invokeGuardedCallback after the first one when hydrating in a // suspense boundary ['Error: Uncaught [Error: first error]'], ]); mockError.mockClear(); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); await waitForAll([]); expect(mockError.mock.calls).toEqual([]); } finally { console.error = originalConsoleError; } }); // @gate __DEV__ it('does not invokeGuardedCallback for errors after a preceding fiber suspends', async () => { // We can't use the toErrorDev helper here because this is async. const originalConsoleError = console.error; const mockError = jest.fn(); console.error = (...args) => { if (args.length > 1) { if (typeof args[1] === 'object') { mockError(args[0].split('\n')[0]); return; } } mockError(...args.map(normalizeCodeLocInfo)); }; let isClient = false; let promise = null; let unsuspend = null; let isResolved = false; function ComponentThatSuspendsOnClient() { if (isClient && !isResolved) { if (promise === null) { promise = new Promise(resolve => { unsuspend = () => { isResolved = true; resolve(); }; }); } Scheduler.log('suspending'); throw promise; } return null; } function ThrowWhenHydrating({children, message}) { // This is a trick to only throw if we're hydrating, because // useSyncExternalStore calls getServerSnapshot instead of the regular // getSnapshot in that case. useSyncExternalStore( () => {}, t => t, () => { if (isClient) { Scheduler.log('throwing: ' + message); throw new Error(message); } }, ); return children; } const App = () => { return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <ComponentThatSuspendsOnClient /> <ThrowWhenHydrating message="first error"> <h1>one</h1> </ThrowWhenHydrating> <ThrowWhenHydrating message="second error"> <h2>two</h2> </ThrowWhenHydrating> <ThrowWhenHydrating message="third error"> <h3>three</h3> </ThrowWhenHydrating> </Suspense> </div> ); }; try { await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll(['suspending']); expect(mockError.mock.calls).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); await unsuspend(); await waitForAll([ 'throwing: first error', 'throwing: first error', 'Logged recoverable error: first error', 'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.', ]); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); } finally { console.error = originalConsoleError; } }); // @gate __DEV__ it('(outdated behavior) suspending after erroring will cause errors previously queued to be silenced until the boundary resolves', async () => { // NOTE: This test was originally written to test a scenario that doesn't happen // anymore. If something errors during hydration, we immediately unwind the // stack and revert to client rendering. I've kept the test around just to // demonstrate what actually happens in this sequence of events. // We can't use the toErrorDev helper here because this is async. const originalConsoleError = console.error; const mockError = jest.fn(); console.error = (...args) => { if (args.length > 1) { if (typeof args[1] === 'object') { mockError(args[0].split('\n')[0]); return; } } mockError(...args.map(normalizeCodeLocInfo)); }; let isClient = false; let promise = null; let unsuspend = null; let isResolved = false; function ComponentThatSuspendsOnClient() { if (isClient && !isResolved) { if (promise === null) { promise = new Promise(resolve => { unsuspend = () => { isResolved = true; resolve(); }; }); } Scheduler.log('suspending'); throw promise; } return null; } function ThrowWhenHydrating({children, message}) { // This is a trick to only throw if we're hydrating, because // useSyncExternalStore calls getServerSnapshot instead of the regular // getSnapshot in that case. useSyncExternalStore( () => {}, t => t, () => { if (isClient) { Scheduler.log('throwing: ' + message); throw new Error(message); } }, ); return children; } const App = () => { return ( <div> <Suspense fallback={<h1>Loading...</h1>}> <ThrowWhenHydrating message="first error"> <h1>one</h1> </ThrowWhenHydrating> <ThrowWhenHydrating message="second error"> <h2>two</h2> </ThrowWhenHydrating> <ComponentThatSuspendsOnClient /> <ThrowWhenHydrating message="third error"> <h3>three</h3> </ThrowWhenHydrating> </Suspense> </div> ); }; try { await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); isClient = true; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { Scheduler.log('Logged recoverable error: ' + error.message); }, }); await waitForAll([ 'throwing: first error', // duplicate because first error is re-done in invokeGuardedCallback 'throwing: first error', 'suspending', 'Logged recoverable error: first error', 'Logged recoverable error: There was an error while hydrating this Suspense boundary. Switched to client rendering.', ]); // These Uncaught error calls are the error reported by the runtime (jsdom here, browser in actual use) // when invokeGuardedCallback is used to replay an error in dev using event dispatching in the document expect(mockError.mock.calls).toEqual([ // we only get one because we suppress invokeGuardedCallback after the first one when hydrating in a // suspense boundary ['Error: Uncaught [Error: first error]'], ]); mockError.mockClear(); expect(getVisibleChildren(container)).toEqual( <div> <h1>Loading...</h1> </div>, ); await clientAct(() => unsuspend()); // Since our client components only throw on the very first render there are no // new throws in this pass assertLog([]); expect(mockError.mock.calls).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> <h1>one</h1> <h2>two</h2> <h3>three</h3> </div>, ); } finally { console.error = originalConsoleError; } }); it('#24578 Hydration errors caused by a suspending component should not become recoverable when nested in an ancestor Suspense that is showing primary content', async () => { // this test failed before because hydration errors on the inner boundary were upgraded to recoverable by // a codepath of the outer boundary function App({isClient}) { return ( <Suspense fallback={'outer'}> <Suspense fallback={'inner'}> <div> {isClient ? <AsyncText text="A" /> : <Text text="A" />} <b>B</b> </div> </Suspense> </Suspense> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); const errors = []; ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> A<b>B</b> </div>, ); resolveText('A'); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> A<b>B</b> </div>, ); }); it('hydration warnings for mismatched text with multiple text nodes caused by suspending should be suppressed', async () => { let resolve; const Lazy = React.lazy(() => { return new Promise(r => { resolve = r; }); }); function App({isClient}) { return ( <div> {isClient ? <Lazy /> : <p>lazy</p>} <p>some {'text'}</p> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); const errors = []; ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> <p>lazy</p> <p>some {'text'}</p> </div>, ); resolve({default: () => <p>lazy</p>}); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> <p>lazy</p> <p>some {'text'}</p> </div>, ); }); // @gate enableFloat it('can emit the preamble even if the head renders asynchronously', async () => { function AsyncNoOutput() { readText('nooutput'); return null; } function AsyncHead() { readText('head'); return ( <head data-foo="foo"> <title>a title</title> </head> ); } function AsyncBody() { readText('body'); return ( <body data-bar="bar"> <link rel="preload" as="style" href="foo" /> hello </body> ); } await act(() => { const {pipe} = renderToPipeableStream( <html data-html="html"> <AsyncNoOutput /> <AsyncHead /> <AsyncBody /> </html>, ); pipe(writable); }); await act(() => { resolveText('body'); }); await act(() => { resolveText('nooutput'); }); await act(() => { resolveText('head'); }); expect(getVisibleChildren(document)).toEqual( <html data-html="html"> <head data-foo="foo"> <link rel="preload" as="style" href="foo" /> <title>a title</title> </head> <body data-bar="bar">hello</body> </html>, ); }); // @gate enableFloat it('holds back body and html closing tags (the postamble) until all pending tasks are completed', async () => { const chunks = []; writable.on('data', chunk => { chunks.push(chunk); }); await act(() => { const {pipe} = renderToPipeableStream( <html> <head /> <body> first <Suspense> <AsyncText text="second" /> </Suspense> </body> </html>, ); pipe(writable); }); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>{'first'}</body> </html>, ); await act(() => { resolveText('second'); }); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body> {'first'} {'second'} </body> </html>, ); expect(chunks.pop()).toEqual('</body></html>'); }); describe('text separators', () => { // To force performWork to start before resolving AsyncText but before piping we need to wait until // after scheduleWork which currently uses setImmediate to delay performWork function afterImmediate() { return new Promise(resolve => { setImmediate(resolve); }); } it('it only includes separators between adjacent text nodes', async () => { function App({name}) { return ( <div> hello<b>world, {name}</b>! </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App name="Foo" />); pipe(writable); }); expect(container.innerHTML).toEqual( '<div>hello<b>world, <!-- -->Foo</b>!</div>', ); const errors = []; ReactDOMClient.hydrateRoot(container, <App name="Foo" />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> hello<b>world, {'Foo'}</b>! </div>, ); }); it('it does not insert text separators even when adjacent text is in a delayed segment', async () => { function App({name}) { return ( <Suspense fallback={'loading...'}> <div id="app-div"> hello <b> world, <AsyncText text={name} /> </b> ! </div> </Suspense> ); } await act(() => { const {pipe} = renderToPipeableStream(<App name="Foo" />); pipe(writable); }); expect(document.getElementById('app-div').outerHTML).toEqual( '<div id="app-div">hello<b>world, <template id="P:1"></template></b>!</div>', ); await act(() => resolveText('Foo')); const div = stripExternalRuntimeInNodes( container.children, renderOptions.unstable_externalRuntimeSrc, )[0]; expect(div.outerHTML).toEqual( '<div id="app-div">hello<b>world, Foo</b>!</div>', ); // there may be either: // - an external runtime script and deleted nodes with data attributes // - extra script nodes containing fizz instructions at the end of container expect( Array.from(container.childNodes).filter(e => e.tagName !== 'SCRIPT') .length, ).toBe(3); expect(div.childNodes.length).toBe(3); const b = div.childNodes[1]; expect(b.childNodes.length).toBe(2); expect(b.childNodes[0]).toMatchInlineSnapshot('world, '); expect(b.childNodes[1]).toMatchInlineSnapshot('Foo'); const errors = []; ReactDOMClient.hydrateRoot(container, <App name="Foo" />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div id="app-div"> hello<b>world, {'Foo'}</b>! </div>, ); }); it('it works with multiple adjacent segments', async () => { function App() { return ( <Suspense fallback={'loading...'}> <div id="app-div"> h<AsyncText text={'ello'} /> w<AsyncText text={'orld'} /> </div> </Suspense> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(document.getElementById('app-div').outerHTML).toEqual( '<div id="app-div">h<template id="P:1"></template>w<template id="P:2"></template></div>', ); await act(() => resolveText('orld')); expect(document.getElementById('app-div').outerHTML).toEqual( '<div id="app-div">h<template id="P:1"></template>world</div>', ); await act(() => resolveText('ello')); expect( stripExternalRuntimeInNodes( container.children, renderOptions.unstable_externalRuntimeSrc, )[0].outerHTML, ).toEqual('<div id="app-div">helloworld</div>'); const errors = []; ReactDOMClient.hydrateRoot(container, <App name="Foo" />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div id="app-div">{['h', 'ello', 'w', 'orld']}</div>, ); }); it('it works when some segments are flushed and others are patched', async () => { function App() { return ( <Suspense fallback={'loading...'}> <div id="app-div"> h<AsyncText text={'ello'} /> w<AsyncText text={'orld'} /> </div> </Suspense> ); } await act(async () => { const {pipe} = renderToPipeableStream(<App />); await afterImmediate(); await act(() => resolveText('ello')); pipe(writable); }); expect(document.getElementById('app-div').outerHTML).toEqual( '<div id="app-div">h<!-- -->ello<!-- -->w<template id="P:1"></template></div>', ); await act(() => resolveText('orld')); expect( stripExternalRuntimeInNodes( container.children, renderOptions.unstable_externalRuntimeSrc, )[0].outerHTML, ).toEqual('<div id="app-div">h<!-- -->ello<!-- -->world</div>'); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div id="app-div">{['h', 'ello', 'w', 'orld']}</div>, ); }); it('it does not prepend a text separators if the segment follows a non-Text Node', async () => { function App() { return ( <Suspense fallback={'loading...'}> <div> hello <b> <AsyncText text={'world'} /> </b> </div> </Suspense> ); } await act(async () => { const {pipe} = renderToPipeableStream(<App />); await afterImmediate(); await act(() => resolveText('world')); pipe(writable); }); expect(container.firstElementChild.outerHTML).toEqual( '<div>hello<b>world<!-- --></b></div>', ); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> hello<b>world</b> </div>, ); }); it('it does not prepend a text separators if the segments first emission is a non-Text Node', async () => { function App() { return ( <Suspense fallback={'loading...'}> <div> hello <AsyncTextWrapped as={'b'} text={'world'} /> </div> </Suspense> ); } await act(async () => { const {pipe} = renderToPipeableStream(<App />); await afterImmediate(); await act(() => resolveText('world')); pipe(writable); }); expect(container.firstElementChild.outerHTML).toEqual( '<div>hello<b>world</b></div>', ); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> hello<b>world</b> </div>, ); }); it('should not insert separators for text inside Suspense boundaries even if they would otherwise be considered text-embedded', async () => { function App() { return ( <Suspense fallback={'loading...'}> <div id="app-div"> start <Suspense fallback={'[loading first]'}> firststart <AsyncText text={'first suspended'} /> firstend </Suspense> <Suspense fallback={'[loading second]'}> secondstart <b> <AsyncText text={'second suspended'} /> </b> </Suspense> end </div> </Suspense> ); } await act(async () => { const {pipe} = renderToPipeableStream(<App />); await afterImmediate(); await act(() => resolveText('world')); pipe(writable); }); expect(document.getElementById('app-div').outerHTML).toEqual( '<div id="app-div">start<!--$?--><template id="B:0"></template>[loading first]<!--/$--><!--$?--><template id="B:1"></template>[loading second]<!--/$-->end</div>', ); await act(() => { resolveText('first suspended'); }); expect(document.getElementById('app-div').outerHTML).toEqual( '<div id="app-div">start<!--$-->firststartfirst suspendedfirstend<!--/$--><!--$?--><template id="B:1"></template>[loading second]<!--/$-->end</div>', ); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div id="app-div"> {'start'} {'firststart'} {'first suspended'} {'firstend'} {'[loading second]'} {'end'} </div>, ); await act(() => { resolveText('second suspended'); }); expect( stripExternalRuntimeInNodes( container.children, renderOptions.unstable_externalRuntimeSrc, )[0].outerHTML, ).toEqual( '<div id="app-div">start<!--$-->firststartfirst suspendedfirstend<!--/$--><!--$-->secondstart<b>second suspended</b><!--/$-->end</div>', ); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div id="app-div"> {'start'} {'firststart'} {'first suspended'} {'firstend'} {'secondstart'} <b>second suspended</b> {'end'} </div>, ); }); it('(only) includes extraneous text separators in segments that complete before flushing, followed by nothing or a non-Text node', async () => { function App() { return ( <div> <Suspense fallback={'text before, nothing after...'}> hello <AsyncText text="world" /> </Suspense> <Suspense fallback={'nothing before or after...'}> <AsyncText text="world" /> </Suspense> <Suspense fallback={'text before, element after...'}> hello <AsyncText text="world" /> <br /> </Suspense> <Suspense fallback={'nothing before, element after...'}> <AsyncText text="world" /> <br /> </Suspense> </div> ); } await act(async () => { const {pipe} = renderToPipeableStream(<App />); await afterImmediate(); await act(() => resolveText('world')); pipe(writable); }); expect(container.innerHTML).toEqual( '<div><!--$-->hello<!-- -->world<!-- --><!--/$--><!--$-->world<!-- --><!--/$--><!--$-->hello<!-- -->world<!-- --><br><!--/$--><!--$-->world<!-- --><br><!--/$--></div>', ); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> {/* first boundary */} {'hello'} {'world'} {/* second boundary */} {'world'} {/* third boundary */} {'hello'} {'world'} <br /> {/* fourth boundary */} {'world'} <br /> </div>, ); }); }); describe('title children', () => { it('should accept a single string child', async () => { // a Single string child function App() { return ( <head> <title>hello</title> </head> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(document.head)).toEqual(<title>hello</title>); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(document.head)).toEqual(<title>hello</title>); }); it('should accept children array of length 1 containing a string', async () => { // a Single string child function App() { return ( <head> <title>{['hello']}</title> </head> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(document.head)).toEqual(<title>hello</title>); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); expect(getVisibleChildren(document.head)).toEqual(<title>hello</title>); }); it('should warn in dev when given an array of length 2 or more', async () => { function App() { return ( <head> <title>{['hello1', 'hello2']}</title> </head> ); } await expect(async () => { await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); }).toErrorDev([ 'React expects the `children` prop of <title> tags to be a string, number, or object with a novel `toString` method but found an Array with length 2 instead. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert `children` of <title> tags to a single string value which is why Arrays of length greater than 1 are not supported. When using JSX it can be commong to combine text nodes and value nodes. For example: <title>hello {nameOfUser}</title>. While not immediately apparent, `children` in this case is an Array with length 2. If your `children` prop is using this form try rewriting it using a template string: <title>{`hello ${nameOfUser}`}</title>.', ]); if (gate(flags => flags.enableFloat)) { expect(getVisibleChildren(document.head)).toEqual(<title />); } else { expect(getVisibleChildren(document.head)).toEqual( <title>{'hello1<!-- -->hello2'}</title>, ); } const errors = []; ReactDOMClient.hydrateRoot(document.head, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); if (gate(flags => flags.enableFloat)) { expect(errors).toEqual([]); // with float, the title doesn't render on the client or on the server expect(getVisibleChildren(document.head)).toEqual(<title />); } else { expect(errors).toEqual( [ gate(flags => flags.enableClientRenderFallbackOnTextMismatch) ? 'Text content does not match server-rendered HTML.' : null, 'Hydration failed because the initial UI does not match what was rendered on the server.', 'There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.', ].filter(Boolean), ); expect(getVisibleChildren(document.head)).toEqual( <title>{['hello1', 'hello2']}</title>, ); } }); it('should warn in dev if you pass a React Component as a child to <title>', async () => { function IndirectTitle() { return 'hello'; } function App() { return ( <head> <title> <IndirectTitle /> </title> </head> ); } if (gate(flags => flags.enableFloat)) { await expect(async () => { await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); }).toErrorDev([ 'React expects the `children` prop of <title> tags to be a string, number, or object with a novel `toString` method but found an object that appears to be a React element which never implements a suitable `toString` method. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags to a single string value which is why rendering React elements is not supported. If the `children` of <title> is a React Component try moving the <title> tag into that component. If the `children` of <title> is some HTML markup change it to be Text only to be valid HTML.', ]); } else { await expect(async () => { await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); }).toErrorDev([ 'A title element received a React element for children. In the browser title Elements can only have Text Nodes as children. If the children being rendered output more than a single text node in aggregate the browser will display markup and comments as text in the title and hydration will likely fail and fall back to client rendering', ]); } if (gate(flags => flags.enableFloat)) { // object titles are toStringed when float is on expect(getVisibleChildren(document.head)).toEqual( <title>{'[object Object]'}</title>, ); } else { expect(getVisibleChildren(document.head)).toEqual(<title>hello</title>); } const errors = []; ReactDOMClient.hydrateRoot(document.head, <App />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); expect(errors).toEqual([]); if (gate(flags => flags.enableFloat)) { // object titles are toStringed when float is on expect(getVisibleChildren(document.head)).toEqual( <title>{'[object Object]'}</title>, ); } else { expect(getVisibleChildren(document.head)).toEqual(<title>hello</title>); } }); }); it('basic use(promise)', async () => { const promiseA = Promise.resolve('A'); const promiseB = Promise.resolve('B'); const promiseC = Promise.resolve('C'); function Async() { return use(promiseA) + use(promiseB) + use(promiseC); } function App() { return ( <Suspense fallback="Loading..."> <Async /> </Suspense> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); // TODO: The `act` implementation in this file doesn't unwrap microtasks // automatically. We can't use the same `act` we use for Fiber tests // because that relies on the mock Scheduler. Doesn't affect any public // API but we might want to fix this for our own internal tests. // // For now, wait for each promise in sequence. await act(async () => { await promiseA; }); await act(async () => { await promiseB; }); await act(async () => { await promiseC; }); expect(getVisibleChildren(container)).toEqual('ABC'); ReactDOMClient.hydrateRoot(container, <App />); await waitForAll([]); expect(getVisibleChildren(container)).toEqual('ABC'); }); // @gate enableServerContext it('basic use(context)', async () => { const ContextA = React.createContext('default'); const ContextB = React.createContext('B'); let ServerContext; expect(() => { ServerContext = React.createServerContext('ServerContext', 'default'); }).toErrorDev( 'Server Context is deprecated and will soon be removed. ' + 'It was never documented and we have found it not to be useful ' + 'enough to warrant the downside it imposes on all apps.', {withoutStack: true}, ); function Client() { return use(ContextA) + use(ContextB); } function ServerComponent() { return use(ServerContext); } function Server() { return ( <ServerContext.Provider value="C"> <ServerComponent /> </ServerContext.Provider> ); } function App() { return ( <> <ContextA.Provider value="A"> <Client /> </ContextA.Provider> <Server /> </> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual(['AB', 'C']); // Hydration uses a different renderer runtime (Fiber instead of Fizz). // We reset _currentRenderer here to not trigger a warning about multiple // renderers concurrently using these contexts ContextA._currentRenderer = null; ServerContext._currentRenderer = null; ReactDOMClient.hydrateRoot(container, <App />); await waitForAll([]); expect(getVisibleChildren(container)).toEqual(['AB', 'C']); }); it('use(promise) in multiple components', async () => { const promiseA = Promise.resolve('A'); const promiseB = Promise.resolve('B'); const promiseC = Promise.resolve('C'); const promiseD = Promise.resolve('D'); function Child({prefix}) { return prefix + use(promiseC) + use(promiseD); } function Parent() { return <Child prefix={use(promiseA) + use(promiseB)} />; } function App() { return ( <Suspense fallback="Loading..."> <Parent /> </Suspense> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); // TODO: The `act` implementation in this file doesn't unwrap microtasks // automatically. We can't use the same `act` we use for Fiber tests // because that relies on the mock Scheduler. Doesn't affect any public // API but we might want to fix this for our own internal tests. // // For now, wait for each promise in sequence. await act(async () => { await promiseA; }); await act(async () => { await promiseB; }); await act(async () => { await promiseC; }); await act(async () => { await promiseD; }); expect(getVisibleChildren(container)).toEqual('ABCD'); ReactDOMClient.hydrateRoot(container, <App />); await waitForAll([]); expect(getVisibleChildren(container)).toEqual('ABCD'); }); it('using a rejected promise will throw', async () => { const promiseA = Promise.resolve('A'); const promiseB = Promise.reject(new Error('Oops!')); const promiseC = Promise.resolve('C'); // Jest/Node will raise an unhandled rejected error unless we await this. It // works fine in the browser, though. await expect(promiseB).rejects.toThrow('Oops!'); function Async() { return use(promiseA) + use(promiseB) + use(promiseC); } class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return this.state.error.message; } return this.props.children; } } function App() { return ( <Suspense fallback="Loading..."> <ErrorBoundary> <Async /> </ErrorBoundary> </Suspense> ); } const reportedServerErrors = []; await act(() => { const {pipe} = renderToPipeableStream(<App />, { onError(error) { reportedServerErrors.push(error); }, }); pipe(writable); }); // TODO: The `act` implementation in this file doesn't unwrap microtasks // automatically. We can't use the same `act` we use for Fiber tests // because that relies on the mock Scheduler. Doesn't affect any public // API but we might want to fix this for our own internal tests. // // For now, wait for each promise in sequence. await act(async () => { await promiseA; }); await act(async () => { await expect(promiseB).rejects.toThrow('Oops!'); }); await act(async () => { await promiseC; }); expect(getVisibleChildren(container)).toEqual('Loading...'); expect(reportedServerErrors.length).toBe(1); expect(reportedServerErrors[0].message).toBe('Oops!'); const reportedClientErrors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { reportedClientErrors.push(error); }, }); await waitForAll([]); expect(getVisibleChildren(container)).toEqual('Oops!'); expect(reportedClientErrors.length).toBe(1); if (__DEV__) { expect(reportedClientErrors[0].message).toBe('Oops!'); } else { expect(reportedClientErrors[0].message).toBe( 'The server could not finish this Suspense boundary, likely due to ' + 'an error during server rendering. Switched to client rendering.', ); } }); it("use a promise that's already been instrumented and resolved", async () => { const thenable = { status: 'fulfilled', value: 'Hi', then() {}, }; // This will never suspend because the thenable already resolved function App() { return use(thenable); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual('Hi'); ReactDOMClient.hydrateRoot(container, <App />); await waitForAll([]); expect(getVisibleChildren(container)).toEqual('Hi'); }); it('unwraps thenable that fulfills synchronously without suspending', async () => { function App() { const thenable = { then(resolve) { // This thenable immediately resolves, synchronously, without waiting // a microtask. resolve('Hi'); }, }; try { return <Text text={use(thenable)} />; } catch { throw new Error( '`use` should not suspend because the thenable resolved synchronously.', ); } } // Because the thenable resolves synchronously, we should be able to finish // rendering synchronously, with no fallback. await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual('Hi'); }); it('promise as node', async () => { const promise = Promise.resolve('Hi'); await act(async () => { const {pipe} = renderToPipeableStream(promise); pipe(writable); }); // TODO: The `act` implementation in this file doesn't unwrap microtasks // automatically. We can't use the same `act` we use for Fiber tests // because that relies on the mock Scheduler. Doesn't affect any public // API but we might want to fix this for our own internal tests. await act(async () => { await promise; }); expect(getVisibleChildren(container)).toEqual('Hi'); }); it('context as node', async () => { const Context = React.createContext('Hi'); await act(async () => { const {pipe} = renderToPipeableStream(Context); pipe(writable); }); expect(getVisibleChildren(container)).toEqual('Hi'); }); it('recursive Usable as node', async () => { const Context = React.createContext('Hi'); const promiseForContext = Promise.resolve(Context); await act(async () => { const {pipe} = renderToPipeableStream(promiseForContext); pipe(writable); }); // TODO: The `act` implementation in this file doesn't unwrap microtasks // automatically. We can't use the same `act` we use for Fiber tests // because that relies on the mock Scheduler. Doesn't affect any public // API but we might want to fix this for our own internal tests. await act(async () => { await promiseForContext; }); expect(getVisibleChildren(container)).toEqual('Hi'); }); // @gate enableFormActions // @gate enableAsyncActions it('useFormState hydrates without a mismatch', async () => { // This is testing an implementation detail: useFormState emits comment // nodes into the SSR stream, so this checks that they are handled correctly // during hydration. async function action(state) { return state; } const childRef = React.createRef(null); function Form() { const [state] = useFormState(action, 0); const text = `Child: ${state}`; return ( <div id="child" ref={childRef}> {text} </div> ); } function App() { return ( <div> <div> <Form /> </div> <span>Sibling</span> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <div> <div id="child">Child: 0</div> </div> <span>Sibling</span> </div>, ); const child = document.getElementById('child'); // Confirm that it hydrates correctly await clientAct(() => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(childRef.current).toBe(child); }); // @gate enableFormActions // @gate enableAsyncActions it("useFormState hydrates without a mismatch if there's a render phase update", async () => { async function action(state) { return state; } const childRef = React.createRef(null); function Form() { const [localState, setLocalState] = React.useState(0); if (localState < 3) { setLocalState(localState + 1); } // Because of the render phase update above, this component is evaluated // multiple times (even during SSR), but it should only emit a single // marker per useFormState instance. const [formState] = useFormState(action, 0); const text = `${readText('Child')}:${formState}:${localState}`; return ( <div id="child" ref={childRef}> {text} </div> ); } function App() { return ( <div> <Suspense fallback="Loading..."> <Form /> </Suspense> <span>Sibling</span> </div> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> Loading...<span>Sibling</span> </div>, ); await act(() => resolveText('Child')); expect(getVisibleChildren(container)).toEqual( <div> <div id="child">Child:0:3</div> <span>Sibling</span> </div>, ); const child = document.getElementById('child'); // Confirm that it hydrates correctly await clientAct(() => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(childRef.current).toBe(child); }); describe('useEffectEvent', () => { // @gate enableUseEffectEventHook it('can server render a component with useEffectEvent', async () => { const ref = React.createRef(); function App() { const [count, setCount] = React.useState(0); const onClick = React.experimental_useEffectEvent(() => { setCount(c => c + 1); }); return ( <button ref={ref} onClick={() => onClick()}> {count} </button> ); } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<button>0</button>); ReactDOMClient.hydrateRoot(container, <App />); await waitForAll([]); expect(getVisibleChildren(container)).toEqual(<button>0</button>); ref.current.dispatchEvent( new window.MouseEvent('click', {bubbles: true}), ); await jest.runAllTimers(); expect(getVisibleChildren(container)).toEqual(<button>1</button>); }); // @gate enableUseEffectEventHook it('throws if useEffectEvent is called during a server render', async () => { const logs = []; function App() { const onRender = React.experimental_useEffectEvent(() => { logs.push('rendered'); }); onRender(); return <p>Hello</p>; } const reportedServerErrors = []; let caughtError; try { await act(() => { const {pipe} = renderToPipeableStream(<App />, { onError(e) { reportedServerErrors.push(e); }, }); pipe(writable); }); } catch (err) { caughtError = err; } expect(logs).toEqual([]); expect(caughtError.message).toContain( "A function wrapped in useEffectEvent can't be called during rendering.", ); expect(reportedServerErrors).toEqual([caughtError]); }); // @gate enableUseEffectEventHook it('does not guarantee useEffectEvent return values during server rendering are distinct', async () => { function App() { const onClick1 = React.experimental_useEffectEvent(() => {}); const onClick2 = React.experimental_useEffectEvent(() => {}); if (onClick1 === onClick2) { return <div />; } else { return <span />; } } await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div />); const errors = []; ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(error) { errors.push(error); }, }); await expect(async () => { await waitForAll([]); }).toErrorDev( [ 'Expected server HTML to contain a matching <span> in <div>', 'An error occurred during hydration', ], {withoutStack: 1}, ); expect(errors.length).toEqual(2); expect(getVisibleChildren(container)).toEqual(<span />); }); }); it('can render scripts with simple children', async () => { await act(async () => { const {pipe} = renderToPipeableStream( <html> <body> <script>{'try { foo() } catch (e) {} ;'}</script> </body> </html>, ); pipe(writable); }); expect(document.documentElement.outerHTML).toEqual( '<html><head></head><body><script>try { foo() } catch (e) {} ;</script></body></html>', ); }); // @gate enableFloat it('warns if script has complex children', async () => { function MyScript() { return 'bar();'; } const originalConsoleError = console.error; const mockError = jest.fn(); console.error = (...args) => { mockError(...args.map(normalizeCodeLocInfo)); }; try { await act(async () => { const {pipe} = renderToPipeableStream( <html> <body> <script>{2}</script> <script> {[ 'try { foo() } catch (e) {} ;', 'try { bar() } catch (e) {} ;', ]} </script> <script> <MyScript /> </script> </body> </html>, ); pipe(writable); }); if (__DEV__) { expect(mockError.mock.calls.length).toBe(3); expect(mockError.mock.calls[0]).toEqual([ 'Warning: A script element was rendered with %s. If script element has children it must be a single string. Consider using dangerouslySetInnerHTML or passing a plain string as children.%s', 'a number for children', componentStack(['script', 'body', 'html']), ]); expect(mockError.mock.calls[1]).toEqual([ 'Warning: A script element was rendered with %s. If script element has children it must be a single string. Consider using dangerouslySetInnerHTML or passing a plain string as children.%s', 'an array for children', componentStack(['script', 'body', 'html']), ]); expect(mockError.mock.calls[2]).toEqual([ 'Warning: A script element was rendered with %s. If script element has children it must be a single string. Consider using dangerouslySetInnerHTML or passing a plain string as children.%s', 'something unexpected for children', componentStack(['script', 'body', 'html']), ]); } else { expect(mockError.mock.calls.length).toBe(0); } } finally { console.error = originalConsoleError; } }); // @gate enablePostpone it('client renders postponed boundaries without erroring', async () => { function Postponed({isClient}) { if (!isClient) { React.unstable_postpone('testing postpone'); } return 'client only'; } function App({isClient}) { return ( <div> <Suspense fallback={'loading...'}> <Postponed isClient={isClient} /> </Suspense> </div> ); } const errors = []; await act(() => { const {pipe} = renderToPipeableStream(<App isClient={false} />, { onError(error) { errors.push(error.message); }, }); pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div>loading...</div>); ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); // Postponing should not be logged as a recoverable error since it's intentional. expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual(<div>client only</div>); }); // @gate enablePostpone it('errors if trying to postpone outside a Suspense boundary', async () => { function Postponed() { React.unstable_postpone('testing postpone'); return 'client only'; } function App() { return ( <div> <Postponed /> </div> ); } const errors = []; const fatalErrors = []; const postponed = []; let written = false; const testWritable = new Stream.Writable(); testWritable._write = (chunk, encoding, next) => { written = true; }; await act(() => { const {pipe} = renderToPipeableStream(<App />, { onPostpone(reason) { postponed.push(reason); }, onError(error) { errors.push(error.message); }, onShellError(error) { fatalErrors.push(error.message); }, }); pipe(testWritable); }); expect(written).toBe(false); // Postponing is not logged as an error but as a postponed reason. expect(errors).toEqual([]); expect(postponed).toEqual(['testing postpone']); // However, it does error the shell. expect(fatalErrors).toEqual(['testing postpone']); }); // @gate enablePostpone it('can postpone in a fallback', async () => { function Postponed({isClient}) { if (!isClient) { React.unstable_postpone('testing postpone'); } return 'loading...'; } const lazyText = React.lazy(async () => { await 0; // causes the fallback to start work return {default: 'Hello'}; }); function App({isClient}) { return ( <div> <Suspense fallback="Outer"> <Suspense fallback={<Postponed isClient={isClient} />}> {lazyText} </Suspense> </Suspense> </div> ); } const errors = []; await act(() => { const {pipe} = renderToPipeableStream(<App isClient={false} />, { onError(error) { errors.push(error.message); }, }); pipe(writable); }); // TODO: This should actually be fully resolved because the value could eventually // resolve on the server even though the fallback couldn't so we should have been // able to render it. expect(getVisibleChildren(container)).toEqual(<div>Outer</div>); ReactDOMClient.hydrateRoot(container, <App isClient={true} />, { onRecoverableError(error) { errors.push(error.message); }, }); await waitForAll([]); // Postponing should not be logged as a recoverable error since it's intentional. expect(errors).toEqual([]); expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); }); it( 'a transition that flows into a dehydrated boundary should not suspend ' + 'if the boundary is showing a fallback', async () => { let setSearch; function App() { const [search, _setSearch] = React.useState('initial query'); setSearch = _setSearch; return ( <div> <div>{search}</div> <div> <Suspense fallback="Loading..."> <AsyncText text="Async" /> </Suspense> </div> </div> ); } // Render the initial HTML, which is showing a fallback. await act(() => { const {pipe} = renderToPipeableStream(<App />); pipe(writable); }); // Start hydrating. await clientAct(() => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(getVisibleChildren(container)).toEqual( <div> <div>initial query</div> <div>Loading...</div> </div>, ); // Before the HTML has streamed in, update the query. The part outside // the fallback should be allowed to finish. await clientAct(() => { React.startTransition(() => setSearch('updated query')); }); expect(getVisibleChildren(container)).toEqual( <div> <div>updated query</div> <div>Loading...</div> </div>, ); }, ); // @gate enablePostpone it('supports postponing in prerender and resuming later', async () => { let prerendering = true; function Postpone() { if (prerendering) { React.unstable_postpone(); } return 'Hello'; } function App() { return ( <div> <Suspense fallback="Loading..."> <Postpone /> </Suspense> </div> ); } const prerendered = await ReactDOMFizzStatic.prerenderToNodeStream(<App />); expect(prerendered.postponed).not.toBe(null); prerendering = false; const resumed = ReactDOMFizzServer.resumeToPipeableStream( <App />, JSON.parse(JSON.stringify(prerendered.postponed)), ); // Create a separate stream so it doesn't close the writable. I.e. simple concat. const preludeWritable = new Stream.PassThrough(); preludeWritable.setEncoding('utf8'); preludeWritable.on('data', chunk => { writable.write(chunk); }); await act(() => { prerendered.prelude.pipe(preludeWritable); }); expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); await act(() => { resumed.pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); }); // @gate enablePostpone it('client renders a component if it errors during resuming', async () => { let prerendering = true; let ssr = true; function PostponeAndError() { if (prerendering) { React.unstable_postpone(); } if (ssr) { throw new Error('server error'); } return 'Hello'; } function Postpone() { if (prerendering) { React.unstable_postpone(); } return 'Hello'; } const lazyPostponeAndError = React.lazy(async () => { return {default: <PostponeAndError />}; }); function ReplayError() { if (prerendering) { return <Postpone />; } if (ssr) { throw new Error('replay error'); } return 'Hello'; } function App() { return ( <div> <Suspense fallback="Loading1"> <PostponeAndError /> </Suspense> <Suspense fallback="Loading2"> <Postpone /> <Suspense fallback="Loading3">{lazyPostponeAndError}</Suspense> </Suspense> <Suspense fallback="Loading4"> <ReplayError /> </Suspense> </div> ); } const prerenderErrors = []; const prerendered = await ReactDOMFizzStatic.prerenderToNodeStream( <App />, { onError(x) { prerenderErrors.push(x.message); }, }, ); expect(prerendered.postponed).not.toBe(null); prerendering = false; const ssrErrors = []; const resumed = ReactDOMFizzServer.resumeToPipeableStream( <App />, JSON.parse(JSON.stringify(prerendered.postponed)), { onError(x) { ssrErrors.push(x.message); }, }, ); // Create a separate stream so it doesn't close the writable. I.e. simple concat. const preludeWritable = new Stream.PassThrough(); preludeWritable.setEncoding('utf8'); preludeWritable.on('data', chunk => { writable.write(chunk); }); await act(() => { prerendered.prelude.pipe(preludeWritable); }); expect(getVisibleChildren(container)).toEqual( <div> {'Loading1'} {'Loading2'} {'Loading4'} </div>, ); await act(() => { resumed.pipe(writable); }); expect(prerenderErrors).toEqual([]); expect(ssrErrors).toEqual(['server error', 'server error', 'replay error']); // Still loading... expect(getVisibleChildren(container)).toEqual( <div> {'Loading1'} {'Hello'} {'Loading3'} {'Loading4'} </div>, ); const recoverableErrors = []; ssr = false; await clientAct(() => { ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(x) { recoverableErrors.push(x.message); }, }); }); expect(recoverableErrors).toEqual( __DEV__ ? ['server error', 'replay error', 'server error'] : [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', ], ); expect(getVisibleChildren(container)).toEqual( <div> {'Hello'} {'Hello'} {'Hello'} {'Hello'} </div>, ); }); // @gate enablePostpone it('client renders a component if we abort before resuming', async () => { let prerendering = true; let ssr = true; const promise = new Promise(() => {}); function PostponeAndSuspend() { if (prerendering) { React.unstable_postpone(); } if (ssr) { React.use(promise); } return 'Hello'; } function Postpone() { if (prerendering) { React.unstable_postpone(); } return 'Hello'; } function DelayedBoundary() { if (!prerendering && ssr) { // We delay discovery of the boundary so we can abort before finding it. React.use(promise); } return ( <Suspense fallback="Loading3"> <Postpone /> </Suspense> ); } function App() { return ( <div> <Suspense fallback="Loading1"> <PostponeAndSuspend /> </Suspense> <Suspense fallback="Loading2"> <Postpone /> </Suspense> <Suspense fallback="Not used"> <DelayedBoundary /> </Suspense> </div> ); } const prerenderErrors = []; const prerendered = await ReactDOMFizzStatic.prerenderToNodeStream( <App />, { onError(x) { prerenderErrors.push(x.message); }, }, ); expect(prerendered.postponed).not.toBe(null); prerendering = false; const ssrErrors = []; const resumed = ReactDOMFizzServer.resumeToPipeableStream( <App />, JSON.parse(JSON.stringify(prerendered.postponed)), { onError(x) { ssrErrors.push(x.message); }, }, ); // Create a separate stream so it doesn't close the writable. I.e. simple concat. const preludeWritable = new Stream.PassThrough(); preludeWritable.setEncoding('utf8'); preludeWritable.on('data', chunk => { writable.write(chunk); }); await act(() => { prerendered.prelude.pipe(preludeWritable); }); expect(getVisibleChildren(container)).toEqual( <div> {'Loading1'} {'Loading2'} {'Loading3'} </div>, ); await act(() => { resumed.pipe(writable); }); const recoverableErrors = []; ssr = false; await clientAct(() => { ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(x) { recoverableErrors.push(x.message); }, }); }); expect(recoverableErrors).toEqual([]); expect(prerenderErrors).toEqual([]); expect(ssrErrors).toEqual([]); // Still loading... expect(getVisibleChildren(container)).toEqual( <div> {'Loading1'} {'Hello'} {'Loading3'} </div>, ); await clientAct(async () => { await act(() => { resumed.abort(new Error('aborted')); }); }); expect(getVisibleChildren(container)).toEqual( <div> {'Hello'} {'Hello'} {'Hello'} </div>, ); expect(prerenderErrors).toEqual([]); expect(ssrErrors).toEqual(['aborted', 'aborted']); expect(recoverableErrors).toEqual( __DEV__ ? [ 'The server did not finish this Suspense boundary: aborted', 'The server did not finish this Suspense boundary: aborted', ] : [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', ], ); }); // @gate enablePostpone it('client renders remaining boundaries below the error in shell', async () => { let prerendering = true; let ssr = true; function Postpone() { if (prerendering) { React.unstable_postpone(); } return 'Hello'; } function ReplayError({children}) { if (!prerendering && ssr) { throw new Error('replay error'); } return children; } function App() { return ( <div> <div> <Suspense fallback="Loading1"> <Postpone /> </Suspense> <ReplayError> <Suspense fallback="Loading2"> <Postpone /> </Suspense> </ReplayError> <Suspense fallback="Loading3"> <Postpone /> </Suspense> </div> <Suspense fallback="Not used"> <div> <Suspense fallback="Loading4"> <Postpone /> </Suspense> </div> </Suspense> <Suspense fallback="Loading5"> <Postpone /> <ReplayError> <Suspense fallback="Loading6"> <Postpone /> </Suspense> </ReplayError> </Suspense> </div> ); } const prerenderErrors = []; const prerendered = await ReactDOMFizzStatic.prerenderToNodeStream( <App />, { onError(x) { prerenderErrors.push(x.message); }, }, ); expect(prerendered.postponed).not.toBe(null); prerendering = false; const ssrErrors = []; const resumed = ReactDOMFizzServer.resumeToPipeableStream( <App />, JSON.parse(JSON.stringify(prerendered.postponed)), { onError(x) { ssrErrors.push(x.message); }, }, ); // Create a separate stream so it doesn't close the writable. I.e. simple concat. const preludeWritable = new Stream.PassThrough(); preludeWritable.setEncoding('utf8'); preludeWritable.on('data', chunk => { writable.write(chunk); }); await act(() => { prerendered.prelude.pipe(preludeWritable); }); expect(getVisibleChildren(container)).toEqual( <div> <div> {'Loading1'} {'Loading2'} {'Loading3'} </div> <div>{'Loading4'}</div> {'Loading5'} </div>, ); await act(() => { resumed.pipe(writable); }); expect(getVisibleChildren(container)).toEqual( <div> <div> {'Hello' /* This was matched and completed before the error */} { 'Loading2' /* This will be client rendered because its parent errored during replay */ } { 'Hello' /* This should be renderable since we matched which previous sibling errored */ } </div> <div> { 'Hello' /* This should be able to resume because it's in a different parent. */ } </div> {'Hello'} {'Loading6' /* The parent could resolve even if the child didn't */} </div>, ); const recoverableErrors = []; ssr = false; await clientAct(() => { ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(x) { recoverableErrors.push(x.message); }, }); }); expect(getVisibleChildren(container)).toEqual( <div> <div> {'Hello'} {'Hello'} {'Hello'} </div> <div>{'Hello'}</div> {'Hello'} {'Hello'} </div>, ); // We should've logged once for each boundary that this affected. expect(prerenderErrors).toEqual([]); expect(ssrErrors).toEqual([ // This error triggered in two replay components. 'replay error', 'replay error', ]); expect(recoverableErrors).toEqual( // It surfaced in two different suspense boundaries. __DEV__ ? [ 'The server did not finish this Suspense boundary: replay error', 'The server did not finish this Suspense boundary: replay error', ] : [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', ], ); }); // @gate enablePostpone it('can client render a boundary after having already postponed', async () => { let prerendering = true; let ssr = true; function Postpone() { if (prerendering) { React.unstable_postpone(); } return 'Hello'; } function ServerError() { if (ssr) { throw new Error('server error'); } return 'World'; } function App() { return ( <div> <Suspense fallback="Loading1"> <Postpone /> <ServerError /> </Suspense> <Suspense fallback="Loading2"> <Postpone /> </Suspense> </div> ); } const prerenderErrors = []; const prerendered = await ReactDOMFizzStatic.prerenderToNodeStream( <App />, { onError(x) { prerenderErrors.push(x.message); }, }, ); expect(prerendered.postponed).not.toBe(null); prerendering = false; const ssrErrors = []; const resumed = ReactDOMFizzServer.resumeToPipeableStream( <App />, JSON.parse(JSON.stringify(prerendered.postponed)), { onError(x) { ssrErrors.push(x.message); }, }, ); const windowErrors = []; function globalError(e) { windowErrors.push(e.message); } window.addEventListener('error', globalError); // Create a separate stream so it doesn't close the writable. I.e. simple concat. const preludeWritable = new Stream.PassThrough(); preludeWritable.setEncoding('utf8'); preludeWritable.on('data', chunk => { writable.write(chunk); }); await act(() => { prerendered.prelude.pipe(preludeWritable); }); expect(windowErrors).toEqual([]); expect(getVisibleChildren(container)).toEqual( <div> {'Loading1'} {'Loading2'} </div>, ); await act(() => { resumed.pipe(writable); }); expect(prerenderErrors).toEqual(['server error']); // Since this errored, we shouldn't have to replay it. expect(ssrErrors).toEqual([]); expect(windowErrors).toEqual([]); // Still loading... expect(getVisibleChildren(container)).toEqual( <div> {'Loading1'} {'Hello'} </div>, ); const recoverableErrors = []; ssr = false; await clientAct(() => { ReactDOMClient.hydrateRoot(container, <App />, { onRecoverableError(x) { recoverableErrors.push(x.message); }, }); }); expect(recoverableErrors).toEqual( __DEV__ ? ['server error'] : [ 'The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.', ], ); expect(getVisibleChildren(container)).toEqual( <div> {'Hello'} {'World'} {'Hello'} </div>, ); expect(windowErrors).toEqual([]); window.removeEventListener('error', globalError); }); // @gate enablePostpone it('can postpone in fallback', async () => { let prerendering = true; function Postpone() { if (prerendering) { React.unstable_postpone(); } return 'Hello'; } let resolve; const promise = new Promise(r => (resolve = r)); function PostponeAndDelay() { if (prerendering) { React.unstable_postpone(); } return React.use(promise); } const Lazy = React.lazy(async () => { await 0; return {default: Postpone}; }); function App() { return ( <div> <Suspense fallback="Outer"> <Suspense fallback={<Postpone />}> <PostponeAndDelay /> World </Suspense> <Suspense fallback={<Postpone />}> <Lazy /> </Suspense> </Suspense> </div> ); } const prerendered = await ReactDOMFizzStatic.prerenderToNodeStream(<App />); expect(prerendered.postponed).not.toBe(null); prerendering = false; // Create a separate stream so it doesn't close the writable. I.e. simple concat. const preludeWritable = new Stream.PassThrough(); preludeWritable.setEncoding('utf8'); preludeWritable.on('data', chunk => { writable.write(chunk); }); await act(() => { prerendered.prelude.pipe(preludeWritable); }); const resumed = await ReactDOMFizzServer.resumeToPipeableStream( <App />, JSON.parse(JSON.stringify(prerendered.postponed)), ); expect(getVisibleChildren(container)).toEqual(<div>Outer</div>); // Read what we've completed so far await act(() => { resumed.pipe(writable); }); // Should have now resolved the postponed loading state, but not the promise expect(getVisibleChildren(container)).toEqual( <div> {'Hello'} {'Hello'} </div>, ); // Resolve the final promise await act(() => { resolve('Hi'); }); expect(getVisibleChildren(container)).toEqual( <div> {'Hi'} {' World'} {'Hello'} </div>, ); }); // @gate enablePostpone it('can discover new suspense boundaries in the resume', async () => { let prerendering = true; let resolveA; const promiseA = new Promise(r => (resolveA = r)); let resolveB; const promiseB = new Promise(r => (resolveB = r)); function WaitA() { return React.use(promiseA); } function WaitB() { return React.use(promiseB); } function Postpone() { if (prerendering) { React.unstable_postpone(); } return ( <span> <Suspense fallback="Loading again..."> <WaitA /> </Suspense> <WaitB /> </span> ); } function App() { return ( <div> <Suspense fallback="Loading..."> <p> <Postpone /> </p> </Suspense> </div> ); } const prerendered = await ReactDOMFizzStatic.prerenderToNodeStream(<App />); expect(prerendered.postponed).not.toBe(null); prerendering = false; // Create a separate stream so it doesn't close the writable. I.e. simple concat. const preludeWritable = new Stream.PassThrough(); preludeWritable.setEncoding('utf8'); preludeWritable.on('data', chunk => { writable.write(chunk); }); await act(() => { prerendered.prelude.pipe(preludeWritable); }); const resumed = await ReactDOMFizzServer.resumeToPipeableStream( <App />, JSON.parse(JSON.stringify(prerendered.postponed)), ); expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // Read what we've completed so far await act(() => { resumed.pipe(writable); }); // Still blocked expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // Resolve the first promise, this unblocks the inner boundary await act(() => { resolveA('Hello'); }); // Still blocked expect(getVisibleChildren(container)).toEqual(<div>Loading...</div>); // Resolve the second promise, this unblocks the outer boundary await act(() => { resolveB('World'); }); expect(getVisibleChildren(container)).toEqual( <div> <p> <span> {'Hello'} {'World'} </span> </p> </div>, ); }); });
26.839376
714
0.543443
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and its 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 {ConsolePatchSettings} from 'react-devtools-shared/src/backend/types'; import {writeConsolePatchSettingsToWindow} from 'react-devtools-shared/src/backend/console'; import {castBool, castBrowserTheme} from 'react-devtools-shared/src/utils'; // Note: all keys should be optional in this type, because users can use newer // versions of React DevTools with older versions of React Native, and the object // provided by React Native may not include all of this type's fields. export type DevToolsSettingsManager = { getConsolePatchSettings: ?() => string, setConsolePatchSettings: ?(key: string) => void, }; export function initializeUsingCachedSettings( devToolsSettingsManager: DevToolsSettingsManager, ) { initializeConsolePatchSettings(devToolsSettingsManager); } function initializeConsolePatchSettings( devToolsSettingsManager: DevToolsSettingsManager, ) { if (devToolsSettingsManager.getConsolePatchSettings == null) { return; } const consolePatchSettingsString = devToolsSettingsManager.getConsolePatchSettings(); if (consolePatchSettingsString == null) { return; } const parsedConsolePatchSettings = parseConsolePatchSettings( consolePatchSettingsString, ); if (parsedConsolePatchSettings == null) { return; } writeConsolePatchSettingsToWindow(parsedConsolePatchSettings); } function parseConsolePatchSettings( consolePatchSettingsString: string, ): ?ConsolePatchSettings { const parsedValue = JSON.parse(consolePatchSettingsString ?? '{}'); const { appendComponentStack, breakOnConsoleErrors, showInlineWarningsAndErrors, hideConsoleLogsInStrictMode, browserTheme, } = parsedValue; return { appendComponentStack: castBool(appendComponentStack) ?? true, breakOnConsoleErrors: castBool(breakOnConsoleErrors) ?? false, showInlineWarningsAndErrors: castBool(showInlineWarningsAndErrors) ?? true, hideConsoleLogsInStrictMode: castBool(hideConsoleLogsInStrictMode) ?? false, browserTheme: castBrowserTheme(browserTheme) ?? 'dark', }; } export function cacheConsolePatchSettings( devToolsSettingsManager: DevToolsSettingsManager, value: ConsolePatchSettings, ): void { if (devToolsSettingsManager.setConsolePatchSettings == null) { return; } devToolsSettingsManager.setConsolePatchSettings(JSON.stringify(value)); }
32.207792
92
0.777778
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react.production.min.js'); } else { module.exports = require('./cjs/react.development.js'); }
22.875
60
0.663158
cybersecurity-penetration-testing
/** * 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. */ // This file is only used for tests. // It lazily loads the implementation so that we get the correct set of host configs. import ReactVersion from 'shared/ReactVersion'; export {ReactVersion as version}; export function renderToReadableStream() { return require('./src/server/react-dom-server.edge').renderToReadableStream.apply( this, arguments, ); } export function renderToNodeStream() { return require('./src/server/react-dom-server.edge').renderToNodeStream.apply( this, arguments, ); } export function renderToStaticNodeStream() { return require('./src/server/react-dom-server.edge').renderToStaticNodeStream.apply( this, arguments, ); } export function renderToString() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToString.apply( this, arguments, ); } export function renderToStaticMarkup() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToStaticMarkup.apply( this, arguments, ); } export function resume() { return require('./src/server/react-dom-server.edge').resume.apply( this, arguments, ); }
23.018182
88
0.722727
diff-droid
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireDefault(require("react")); var _useTheme = _interopRequireDefault(require("./useTheme")); var _jsxFileName = ""; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Component() { const theme = (0, _useTheme.default)(); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 10 } }, "theme: ", theme); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsS0FBSyxHQUFHLHdCQUFkO0FBRUEsc0JBQU87QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsZ0JBQWFBLEtBQWIsQ0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCc7XG5pbXBvcnQgdXNlVGhlbWUgZnJvbSAnLi91c2VUaGVtZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlVGhlbWUoKTtcblxuICByZXR1cm4gPGRpdj50aGVtZToge3RoZW1lfTwvZGl2Pjtcbn1cbiJdLCJ4X3JlYWN0X3NvdXJjZXMiOltbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJ0aGVtZSJdLCJtYXBwaW5ncyI6IkNBQUQ7Y2dCQ0EsQVVEQSJ9XV19
61.846154
1,032
0.861604
owtf
'use client'; import * as React from 'react'; import {useFormState} from 'react-dom'; import Container from './Container.js'; export function Counter({incrementAction}) { const [count, incrementFormAction] = useFormState(incrementAction, 0); return ( <Container> <form> <button formAction={incrementFormAction}>Count: {count}</button> </form> </Container> ); }
21.166667
72
0.670854
cybersecurity-penetration-testing
/** * 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. * * @emails react-core */ let React; let ReactDOM; let ReactDOMClient; let ReactTestUtils; let Scheduler; let act; let container; let assertLog; jest.useRealTimers(); global.IS_REACT_ACT_ENVIRONMENT = true; function sleep(period) { return new Promise(resolve => { setTimeout(() => { resolve(true); }, period); }); } describe('ReactTestUtils.act()', () => { afterEach(() => { jest.restoreAllMocks(); }); // first we run all the tests with concurrent mode if (__EXPERIMENTAL__) { let concurrentRoot = null; const renderConcurrent = (el, dom) => { concurrentRoot = ReactDOMClient.createRoot(dom); if (__DEV__) { act(() => concurrentRoot.render(el)); } else { concurrentRoot.render(el); } }; const unmountConcurrent = _dom => { if (__DEV__) { act(() => { if (concurrentRoot !== null) { concurrentRoot.unmount(); concurrentRoot = null; } }); } else { if (concurrentRoot !== null) { concurrentRoot.unmount(); concurrentRoot = null; } } }; const rerenderConcurrent = el => { act(() => concurrentRoot.render(el)); }; runActTests( 'concurrent mode', renderConcurrent, unmountConcurrent, rerenderConcurrent, ); } // and then in legacy mode let legacyDom = null; function renderLegacy(el, dom) { legacyDom = dom; ReactDOM.render(el, dom); } function unmountLegacy(dom) { legacyDom = null; ReactDOM.unmountComponentAtNode(dom); } function rerenderLegacy(el) { ReactDOM.render(el, legacyDom); } runActTests('legacy mode', renderLegacy, unmountLegacy, rerenderLegacy); describe('unacted effects', () => { function App() { React.useEffect(() => {}, []); return null; } it('does not warn in legacy mode', () => { expect(() => { ReactDOM.render(<App />, document.createElement('div')); }).toErrorDev([]); }); // @gate __DEV__ it('does not warn in concurrent mode', () => { const root = ReactDOMClient.createRoot(document.createElement('div')); act(() => root.render(<App />)); }); }); }); function runActTests(label, render, unmount, rerender) { describe(label, () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactTestUtils = require('react-dom/test-utils'); Scheduler = require('scheduler'); act = ReactTestUtils.act; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { unmount(container); document.body.removeChild(container); }); describe('sync', () => { // @gate __DEV__ it('can use act to flush effects', () => { function App() { React.useEffect(() => { Scheduler.log(100); }); return null; } act(() => { render(<App />, container); }); assertLog([100]); }); // @gate __DEV__ it('flushes effects on every call', async () => { function App() { const [ctr, setCtr] = React.useState(0); React.useEffect(() => { Scheduler.log(ctr); }); return ( <button id="button" onClick={() => setCtr(x => x + 1)}> {ctr} </button> ); } act(() => { render(<App />, container); }); assertLog([0]); const button = container.querySelector('#button'); function click() { button.dispatchEvent(new MouseEvent('click', {bubbles: true})); } await act(async () => { click(); click(); click(); }); // it consolidates the 3 updates, then fires the effect assertLog([3]); await act(async () => click()); assertLog([4]); await act(async () => click()); assertLog([5]); expect(button.innerHTML).toBe('5'); }); // @gate __DEV__ it("should keep flushing effects until they're done", () => { function App() { const [ctr, setCtr] = React.useState(0); React.useEffect(() => { if (ctr < 5) { setCtr(x => x + 1); } }); return ctr; } act(() => { render(<App />, container); }); expect(container.innerHTML).toBe('5'); }); // @gate __DEV__ it('should flush effects only on exiting the outermost act', () => { function App() { React.useEffect(() => { Scheduler.log(0); }); return null; } // let's nest a couple of act() calls act(() => { act(() => { render(<App />, container); }); // the effect wouldn't have yielded yet because // we're still inside an act() scope assertLog([]); }); // but after exiting the last one, effects get flushed assertLog([0]); }); // @gate __DEV__ it('warns if a setState is called outside of act(...)', () => { let setValue = null; function App() { const [value, _setValue] = React.useState(0); setValue = _setValue; return value; } act(() => { render(<App />, container); }); expect(() => setValue(1)).toErrorDev([ 'An update to App inside a test was not wrapped in act(...).', ]); }); // @gate __DEV__ it('warns if a setState is called outside of act(...) after a component threw', () => { let setValue = null; function App({defaultValue}) { if (defaultValue === undefined) { throw new Error('some error'); } const [value, _setValue] = React.useState(defaultValue); setValue = _setValue; return value; } expect(() => { act(() => { render(<App defaultValue={undefined} />, container); }); }).toThrow('some error'); act(() => { rerender(<App defaultValue={0} />, container); }); expect(() => setValue(1)).toErrorDev([ 'An update to App inside a test was not wrapped in act(...).', ]); }); // @gate __DEV__ it('does not warn if IS_REACT_ACT_ENVIRONMENT is set to false', () => { let setState; function App() { const [state, _setState] = React.useState(0); setState = _setState; return state; } act(() => { render(<App />, container); }); // First show that it does warn expect(() => setState(1)).toErrorDev( 'An update to App inside a test was not wrapped in act(...)', ); // Now do the same thing again, but disable with the environment flag const prevIsActEnvironment = global.IS_REACT_ACT_ENVIRONMENT; global.IS_REACT_ACT_ENVIRONMENT = false; try { setState(2); } finally { global.IS_REACT_ACT_ENVIRONMENT = prevIsActEnvironment; } // When the flag is restored to its previous value, it should start // warning again. This shows that React reads the flag each time. expect(() => setState(3)).toErrorDev( 'An update to App inside a test was not wrapped in act(...)', ); }); describe('fake timers', () => { beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); // @gate __DEV__ it('lets a ticker update', () => { function App() { const [toggle, setToggle] = React.useState(0); React.useEffect(() => { const timeout = setTimeout(() => { setToggle(1); }, 200); return () => clearTimeout(timeout); }, []); return toggle; } act(() => { render(<App />, container); }); act(() => { jest.runAllTimers(); }); expect(container.innerHTML).toBe('1'); }); // @gate __DEV__ it('can use the async version to catch microtasks', async () => { function App() { const [toggle, setToggle] = React.useState(0); React.useEffect(() => { // just like the previous test, except we // use a promise and schedule the update // after it resolves sleep(200).then(() => setToggle(1)); }, []); return toggle; } act(() => { render(<App />, container); }); await act(async () => { jest.runAllTimers(); }); expect(container.innerHTML).toBe('1'); }); // @gate __DEV__ it('can handle cascading promises with fake timers', async () => { // this component triggers an effect, that waits a tick, // then sets state. repeats this 5 times. function App() { const [state, setState] = React.useState(0); async function ticker() { await null; setState(x => x + 1); } React.useEffect(() => { ticker(); }, [Math.min(state, 4)]); return state; } await act(async () => { render(<App />, container); }); // all 5 ticks present and accounted for expect(container.innerHTML).toBe('5'); }); // @gate __DEV__ it('flushes immediate re-renders with act', () => { function App() { const [ctr, setCtr] = React.useState(0); React.useEffect(() => { if (ctr === 0) { setCtr(1); } const timeout = setTimeout(() => setCtr(2), 1000); return () => clearTimeout(timeout); }); return ctr; } act(() => { render(<App />, container); // Since effects haven't been flushed yet, this does not advance the timer jest.runAllTimers(); }); expect(container.innerHTML).toBe('1'); act(() => { jest.runAllTimers(); }); expect(container.innerHTML).toBe('2'); }); }); }); describe('asynchronous tests', () => { // @gate __DEV__ it('works with timeouts', async () => { function App() { const [ctr, setCtr] = React.useState(0); function doSomething() { setTimeout(() => { setCtr(1); }, 50); } React.useEffect(() => { doSomething(); }, []); return ctr; } await act(async () => { render(<App />, container); }); expect(container.innerHTML).toBe('0'); // Flush the pending timers await act(async () => { await sleep(100); }); expect(container.innerHTML).toBe('1'); }); // @gate __DEV__ it('flushes microtasks before exiting (async function)', async () => { function App() { const [ctr, setCtr] = React.useState(0); async function someAsyncFunction() { // queue a bunch of promises to be sure they all flush await null; await null; await null; setCtr(1); } React.useEffect(() => { someAsyncFunction(); }, []); return ctr; } await act(async () => { render(<App />, container); }); expect(container.innerHTML).toEqual('1'); }); // @gate __DEV__ it('flushes microtasks before exiting (sync function)', async () => { // Same as previous test, but the callback passed to `act` is not itself // an async function. function App() { const [ctr, setCtr] = React.useState(0); async function someAsyncFunction() { // queue a bunch of promises to be sure they all flush await null; await null; await null; setCtr(1); } React.useEffect(() => { someAsyncFunction(); }, []); return ctr; } await act(() => { render(<App />, container); }); expect(container.innerHTML).toEqual('1'); }); // @gate __DEV__ it('warns if you do not await an act call', async () => { spyOnDevAndProd(console, 'error').mockImplementation(() => {}); act(async () => {}); // it's annoying that we have to wait a tick before this warning comes in await sleep(0); if (__DEV__) { expect(console.error).toHaveBeenCalledTimes(1); expect(console.error.mock.calls[0][0]).toMatch( 'You called act(async () => ...) without await.', ); } }); // @gate __DEV__ it('warns if you try to interleave multiple act calls', async () => { spyOnDevAndProd(console, 'error').mockImplementation(() => {}); await Promise.all([ act(async () => { await sleep(50); }), act(async () => { await sleep(100); }), ]); await sleep(150); if (__DEV__) { expect(console.error).toHaveBeenCalledTimes(2); expect(console.error.mock.calls[0][0]).toMatch( 'You seem to have overlapping act() calls', ); expect(console.error.mock.calls[1][0]).toMatch( 'You seem to have overlapping act() calls', ); } }); // @gate __DEV__ it('async commits and effects are guaranteed to be flushed', async () => { function App() { const [state, setState] = React.useState(0); async function something() { await null; setState(1); } React.useEffect(() => { something(); }, []); React.useEffect(() => { Scheduler.log(state); }); return state; } await act(async () => { render(<App />, container); }); // exiting act() drains effects and microtasks assertLog([0, 1]); expect(container.innerHTML).toBe('1'); }); // @gate __DEV__ it('can handle cascading promises', async () => { // this component triggers an effect, that waits a tick, // then sets state. repeats this 5 times. function App() { const [state, setState] = React.useState(0); async function ticker() { await null; setState(x => x + 1); } React.useEffect(() => { Scheduler.log(state); ticker(); }, [Math.min(state, 4)]); return state; } await act(async () => { render(<App />, container); }); // all 5 ticks present and accounted for assertLog([0, 1, 2, 3, 4]); expect(container.innerHTML).toBe('5'); }); }); describe('error propagation', () => { // @gate __DEV__ it('propagates errors - sync', () => { let err; try { act(() => { throw new Error('some error'); }); } catch (_err) { err = _err; } finally { expect(err instanceof Error).toBe(true); expect(err.message).toBe('some error'); } }); // @gate __DEV__ it('should propagate errors from effects - sync', () => { function App() { React.useEffect(() => { throw new Error('oh no'); }); return null; } let error; try { act(() => { render(<App />, container); }); } catch (_error) { error = _error; } finally { expect(error instanceof Error).toBe(true); expect(error.message).toBe('oh no'); } }); // @gate __DEV__ it('propagates errors - async', async () => { let err; try { await act(async () => { await sleep(100); throw new Error('some error'); }); } catch (_err) { err = _err; } finally { expect(err instanceof Error).toBe(true); expect(err.message).toBe('some error'); } }); // @gate __DEV__ it('should cleanup after errors - sync', () => { function App() { React.useEffect(() => { Scheduler.log('oh yes'); }); return null; } let error; try { act(() => { throw new Error('oh no'); }); } catch (_error) { error = _error; } finally { expect(error instanceof Error).toBe(true); expect(error.message).toBe('oh no'); // should be able to render components after this tho act(() => { render(<App />, container); }); assertLog(['oh yes']); } }); // @gate __DEV__ it('should cleanup after errors - async', async () => { function App() { async function somethingAsync() { await null; Scheduler.log('oh yes'); } React.useEffect(() => { somethingAsync(); }); return null; } let error; try { await act(async () => { await sleep(100); throw new Error('oh no'); }); } catch (_error) { error = _error; } finally { expect(error instanceof Error).toBe(true); expect(error.message).toBe('oh no'); // should be able to render components after this tho await act(async () => { render(<App />, container); }); assertLog(['oh yes']); } }); }); describe('suspense', () => { if (__DEV__ && __EXPERIMENTAL__) { // todo - remove __DEV__ check once we start using testing builds // @gate __DEV__ it('triggers fallbacks if available', async () => { if (label !== 'legacy mode') { // FIXME: Support for Concurrent Root intentionally removed // from the public version of `act`. It will be added back in // a future major version, before the Concurrent Root is released. // Consider skipping all non-Legacy tests in this suite until then. return; } let resolved = false; let resolve; const promise = new Promise(_resolve => { resolve = _resolve; }); function Suspends() { if (resolved) { return 'was suspended'; } throw promise; } function App(props) { return ( <React.Suspense fallback={<span data-test-id="spinner">loading...</span>}> {props.suspend ? <Suspends /> : 'content'} </React.Suspense> ); } // render something so there's content act(() => { render(<App suspend={false} />, container); }); // trigger a suspendy update act(() => { rerender(<App suspend={true} />); }); expect( document.querySelector('[data-test-id=spinner]'), ).not.toBeNull(); // now render regular content again act(() => { rerender(<App suspend={false} />); }); expect(document.querySelector('[data-test-id=spinner]')).toBeNull(); // trigger a suspendy update with a delay React.startTransition(() => { act(() => { rerender(<App suspend={true} />); }); }); if (label === 'concurrent mode') { // In Concurrent Mode, refresh transitions delay indefinitely. expect(document.querySelector('[data-test-id=spinner]')).toBeNull(); } else { // In Legacy Mode, all fallbacks are forced to display, // even during a refresh transition. expect( document.querySelector('[data-test-id=spinner]'), ).not.toBeNull(); } // resolve the promise await act(async () => { resolved = true; resolve(); }); // spinner gone, content showing expect(document.querySelector('[data-test-id=spinner]')).toBeNull(); expect(container.textContent).toBe('was suspended'); }); } }); describe('throw in prod mode', () => { // @gate !__DEV__ it('warns if you try to use act() in prod mode', () => { expect(() => act(() => {})).toThrow( 'act(...) is not supported in production builds of React', ); }); }); }); }
26.640252
93
0.471215
owtf
/* * Copyright (c) Facebook, Inc. and its affiliates. */ module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, 'postcss-flexbugs-fixes': {}, 'postcss-preset-env': { autoprefixer: { flexbox: 'no-2009', }, stage: 3, features: { 'custom-properties': false, }, }, }, }
15.666667
51
0.504298
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); const isDarkMode = useIsDarkMode(); const { foo } = useFoo(); (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 27, columnNumber: 7 } }, "Foo: ", foo), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const [isDarkMode] = (0, _react.useState)(false); (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return isDarkMode; } function useFoo() { (0, _react.useDebugValue)('foo'); return { foo: true }; } //# sourceMappingURL=ComponentWithCustomHook.js.map?foo=bar&param=some_value
36.617647
743
0.636293
Mastering-Machine-Learning-for-Penetration-Testing
/** * 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 {copy} from 'clipboard-js'; import * as React from 'react'; import {ElementTypeHostComponent} from 'react-devtools-shared/src/frontend/types'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import KeyValue from './KeyValue'; import {alphaSortEntries, serializeDataForCopy} from '../utils'; import Store from '../../store'; import styles from './InspectedElementSharedStyles.css'; import type {InspectedElement} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {Element} from 'react-devtools-shared/src/frontend/types'; type Props = { bridge: FrontendBridge, element: Element, inspectedElement: InspectedElement, store: Store, }; export default function InspectedElementStateTree({ bridge, element, inspectedElement, store, }: Props): React.Node { const {state, type} = inspectedElement; // HostSingleton and HostHoistable may have state that we don't want to expose to users const isHostComponent = type === ElementTypeHostComponent; const entries = state != null ? Object.entries(state) : null; const isEmpty = entries === null || entries.length === 0; if (isEmpty || isHostComponent) { return null; } if (entries !== null) { entries.sort(alphaSortEntries); } const handleCopy = () => copy(serializeDataForCopy(((state: any): Object))); return ( <div className={styles.InspectedElementTree}> <div className={styles.HeaderRow}> <div className={styles.Header}>state</div> {!isEmpty && ( <Button onClick={handleCopy} title="Copy to clipboard"> <ButtonIcon type="copy" /> </Button> )} </div> {isEmpty && <div className={styles.Empty}>None</div>} {!isEmpty && (entries: any).map(([name, value]) => ( <KeyValue key={name} alphaSort={true} bridge={bridge} canDeletePaths={true} canEditValues={true} canRenamePaths={true} depth={1} element={element} hidden={false} inspectedElement={inspectedElement} name={name} path={[name]} pathRoot="state" store={store} value={value} /> ))} </div> ); }
27.808989
89
0.630901
PenetrationTestingScripts
const {resolve} = require('path'); const Webpack = require('webpack'); const { DARK_MODE_DIMMED_WARNING_COLOR, DARK_MODE_DIMMED_ERROR_COLOR, DARK_MODE_DIMMED_LOG_COLOR, LIGHT_MODE_DIMMED_WARNING_COLOR, LIGHT_MODE_DIMMED_ERROR_COLOR, LIGHT_MODE_DIMMED_LOG_COLOR, GITHUB_URL, getVersionString, } = require('react-devtools-extensions/utils'); const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils'); const NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV) { console.error('NODE_ENV not set'); process.exit(1); } const builtModulesDir = resolve( __dirname, '..', '..', 'build', 'oss-experimental', ); const __DEV__ = NODE_ENV === 'development'; const DEVTOOLS_VERSION = getVersionString(); const featureFlagTarget = process.env.FEATURE_FLAG_TARGET || 'core/backend-oss'; // This targets RN/Hermes. process.env.BABEL_CONFIG_ADDITIONAL_TARGETS = JSON.stringify({ ie: '11', }); module.exports = { mode: __DEV__ ? 'development' : 'production', devtool: __DEV__ ? 'eval-cheap-module-source-map' : 'source-map', entry: { backend: './src/backend.js', }, output: { path: __dirname + '/dist', filename: '[name].js', // This name is important; standalone references it in order to connect. library: 'ReactDevToolsBackend', libraryTarget: 'umd', }, resolve: { alias: { react: resolve(builtModulesDir, 'react'), 'react-debug-tools': resolve(builtModulesDir, 'react-debug-tools'), 'react-devtools-feature-flags': resolveFeatureFlags(featureFlagTarget), 'react-dom': resolve(builtModulesDir, 'react-dom'), 'react-is': resolve(builtModulesDir, 'react-is'), scheduler: resolve(builtModulesDir, 'scheduler'), }, }, node: { global: false, }, plugins: [ new Webpack.ProvidePlugin({ process: 'process/browser', }), new Webpack.DefinePlugin({ __DEV__, __EXPERIMENTAL__: true, __EXTENSION__: false, __PROFILE__: false, __TEST__: NODE_ENV === 'test', 'process.env.DEVTOOLS_PACKAGE': `"react-devtools-core"`, 'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`, 'process.env.GITHUB_URL': `"${GITHUB_URL}"`, 'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`, 'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`, 'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`, }), ], optimization: { minimize: false, }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader', options: { configFile: resolve( __dirname, '..', 'react-devtools-shared', 'babel.config.js', ), }, }, ], }, };
27.518519
92
0.616109
Python-Penetration-Testing-for-Developers
/** * 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. * * @emails react-core * @jest-environment node */ /* eslint-disable no-func-assign */ 'use strict'; let React; let ReactNoop; let Scheduler; let act; let useEffect; let useLayoutEffect; let assertLog; describe('ReactEffectOrdering', () => { beforeEach(() => { jest.resetModules(); jest.useFakeTimers(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; useEffect = React.useEffect; useLayoutEffect = React.useLayoutEffect; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; }); test('layout unmounts on deletion are fired in parent -> child order', async () => { const root = ReactNoop.createRoot(); function Parent() { useLayoutEffect(() => { return () => Scheduler.log('Unmount parent'); }); return <Child />; } function Child() { useLayoutEffect(() => { return () => Scheduler.log('Unmount child'); }); return 'Child'; } await act(() => { root.render(<Parent />); }); expect(root).toMatchRenderedOutput('Child'); await act(() => { root.render(null); }); assertLog(['Unmount parent', 'Unmount child']); }); test('passive unmounts on deletion are fired in parent -> child order', async () => { const root = ReactNoop.createRoot(); function Parent() { useEffect(() => { return () => Scheduler.log('Unmount parent'); }); return <Child />; } function Child() { useEffect(() => { return () => Scheduler.log('Unmount child'); }); return 'Child'; } await act(() => { root.render(<Parent />); }); expect(root).toMatchRenderedOutput('Child'); await act(() => { root.render(null); }); assertLog(['Unmount parent', 'Unmount child']); }); });
22.139785
87
0.591818
null
/** * 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, filenamey, ...] 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, ); } } }
23.333333
77
0.658354
Hands-On-AWS-Penetration-Testing-with-Kali-Linux
/** * 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 ErrorBoundary from './ErrorBoundary'; export default ErrorBoundary;
20.615385
66
0.721429
null
#!/usr/bin/env node 'use strict'; const {spawn} = require('child_process'); const {join} = require('path'); const ROOT_PATH = join(__dirname, '..', '..'); const reactVersion = process.argv[2]; const inlinePackagePath = join(ROOT_PATH, 'packages', 'react-devtools-inline'); const shellPackagePath = join(ROOT_PATH, 'packages', 'react-devtools-shell'); const screenshotPath = join(ROOT_PATH, 'tmp', 'screenshots'); const {SUCCESSFUL_COMPILATION_MESSAGE} = require( join(shellPackagePath, 'constants.js') ); let buildProcess = null; let serverProcess = null; let testProcess = null; function format(loggable) { return `${loggable}` .split('\n') .filter(line => { return line.trim() !== ''; }) .map(line => ` ${line}`) .join('\n'); } function logBright(loggable) { console.log(`\x1b[1m${loggable}\x1b[0m`); } function logDim(loggable) { const formatted = format(loggable, 2); if (formatted !== '') { console.log(`\x1b[2m${formatted}\x1b[0m`); } } function logError(loggable) { const formatted = format(loggable, 2); if (formatted !== '') { console.error(`\x1b[31m${formatted}\x1b[0m`); } } function buildInlinePackage() { logBright('Building inline packages'); buildProcess = spawn('yarn', ['build'], {cwd: inlinePackagePath}); buildProcess.stdout.on('data', data => { logDim(data); }); buildProcess.stderr.on('data', data => { if (`${data}`.includes('Warning')) { logDim(data); } else { logError(`Error:\n${data}`); exitWithCode(1); } }); buildProcess.on('close', code => { logBright('Inline package built'); runTestShell(); }); } function runTestShell() { const timeoutID = setTimeout(() => { // Assume the test shell server failed to start. logError('Testing shell server failed to start'); exitWithCode(1); }, 60 * 1000); logBright('Starting testing shell server'); if (!reactVersion) { serverProcess = spawn('yarn', ['start'], {cwd: shellPackagePath}); } else { serverProcess = spawn('yarn', ['start'], { cwd: shellPackagePath, env: {...process.env, REACT_VERSION: reactVersion}, }); } serverProcess.stdout.on('data', data => { if (`${data}`.includes(SUCCESSFUL_COMPILATION_MESSAGE)) { logBright('Testing shell server running'); clearTimeout(timeoutID); runEndToEndTests(); } }); serverProcess.stderr.on('data', data => { if (`${data}`.includes('EADDRINUSE')) { // Something is occupying this port; // We could kill the process and restart but probably better to prompt the user to do this. logError('Free up the port and re-run tests:'); logBright(' kill -9 $(lsof -ti:8080)'); exitWithCode(1); } else if (`${data}`.includes('ERROR')) { logError(`Error:\n${data}`); exitWithCode(1); } else { // Non-fatal stuff like Babel optimization warnings etc. logDim(data); } }); } async function runEndToEndTests() { logBright('Running e2e tests'); if (!reactVersion) { testProcess = spawn('yarn', ['test:e2e', `--output=${screenshotPath}`], { cwd: inlinePackagePath, }); } else { testProcess = spawn('yarn', ['test:e2e', `--output=${screenshotPath}`], { cwd: inlinePackagePath, env: {...process.env, REACT_VERSION: reactVersion}, }); } testProcess.stdout.on('data', data => { // Log without formatting because Playwright applies its own formatting. const formatted = format(data); if (formatted !== '') { console.log(formatted); } }); testProcess.stderr.on('data', data => { // Log without formatting because Playwright applies its own formatting. const formatted = format(data); if (formatted !== '') { console.error(formatted); } exitWithCode(1); }); testProcess.on('close', code => { logBright(`Tests completed with code: ${code}`); exitWithCode(code); }); } function exitWithCode(code) { if (buildProcess !== null) { try { logBright('Shutting down build process'); buildProcess.kill(); } catch (error) { logError(error); } } if (serverProcess !== null) { try { logBright('Shutting down shell server process'); serverProcess.kill(); } catch (error) { logError(error); } } if (testProcess !== null) { try { logBright('Shutting down test process'); testProcess.kill(); } catch (error) { logError(error); } } process.exit(code); } buildInlinePackage();
23.111111
97
0.61194
cybersecurity-penetration-testing
/* eslint-disable dot-notation */ // Instruction set for the Fizz external runtime import { clientRenderBoundary, completeBoundary, completeSegment, listenToFormSubmissionsForReplaying, } from './ReactDOMFizzInstructionSetShared'; import {enableFormActions} from 'shared/ReactFeatureFlags'; export {clientRenderBoundary, completeBoundary, completeSegment}; const resourceMap = new Map(); // This function is almost identical to the version used by inline scripts // (ReactDOMFizzInstructionSetInlineSource), with the exception of how we read // completeBoundary and resourceMap export function completeBoundaryWithStyles( suspenseBoundaryID, contentID, stylesheetDescriptors, ) { const precedences = new Map(); const thisDocument = document; let lastResource, node; // Seed the precedence list with existing resources and collect hoistable style tags const nodes = thisDocument.querySelectorAll( 'link[data-precedence],style[data-precedence]', ); const styleTagsToHoist = []; for (let i = 0; (node = nodes[i++]); ) { if (node.getAttribute('media') === 'not all') { styleTagsToHoist.push(node); } else { if (node.tagName === 'LINK') { resourceMap.set(node.getAttribute('href'), node); } precedences.set(node.dataset['precedence'], (lastResource = node)); } } let i = 0; const dependencies = []; let href, precedence, attr, loadingState, resourceEl, media; // Sheets Mode let sheetMode = true; while (true) { if (sheetMode) { // Sheet Mode iterates over the stylesheet arguments and constructs them if new or checks them for // dependency if they already existed const stylesheetDescriptor = stylesheetDescriptors[i++]; if (!stylesheetDescriptor) { // enter <style> Mode sheetMode = false; i = 0; continue; } let avoidInsert = false; let j = 0; href = stylesheetDescriptor[j++]; if ((resourceEl = resourceMap.get(href))) { // We have an already inserted stylesheet. loadingState = resourceEl['_p']; avoidInsert = true; } else { // We haven't already processed this href so we need to construct a stylesheet and hoist it // We construct it here and attach a loadingState. We also check whether it matches // media before we include it in the dependency array. resourceEl = thisDocument.createElement('link'); resourceEl.href = href; resourceEl.rel = 'stylesheet'; resourceEl.dataset['precedence'] = precedence = stylesheetDescriptor[j++]; while ((attr = stylesheetDescriptor[j++])) { resourceEl.setAttribute(attr, stylesheetDescriptor[j++]); } loadingState = resourceEl['_p'] = new Promise((resolve, reject) => { resourceEl.onload = resolve; resourceEl.onerror = reject; }); // Save this resource element so we can bailout if it is used again resourceMap.set(href, resourceEl); } media = resourceEl.getAttribute('media'); if ( loadingState && loadingState['s'] !== 'l' && (!media || window['matchMedia'](media).matches) ) { dependencies.push(loadingState); } if (avoidInsert) { // We have a link that is already in the document. We don't want to fall through to the insert path continue; } } else { // <style> mode iterates over not-yet-hoisted <style> tags with data-precedence and hoists them. resourceEl = styleTagsToHoist[i++]; if (!resourceEl) { // we are done with all style tags break; } precedence = resourceEl.getAttribute('data-precedence'); resourceEl.removeAttribute('media'); } // resourceEl is either a newly constructed <link rel="stylesheet" ...> or a <style> tag requiring hoisting const prior = precedences.get(precedence) || lastResource; if (prior === lastResource) { lastResource = resourceEl; } precedences.set(precedence, resourceEl); // Finally, we insert the newly constructed instance at an appropriate location // in the Document. if (prior) { prior.parentNode.insertBefore(resourceEl, prior.nextSibling); } else { const head = thisDocument.head; head.insertBefore(resourceEl, head.firstChild); } } Promise.all(dependencies).then( completeBoundary.bind(null, suspenseBoundaryID, contentID, ''), completeBoundary.bind( null, suspenseBoundaryID, contentID, 'Resource failed to load', ), ); } if (enableFormActions) { listenToFormSubmissionsForReplaying(); }
31.267123
111
0.653928
Effective-Python-Penetration-Testing
/** * 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 Agent from 'react-devtools-shared/src/backend/agent'; import {destroy as destroyCanvas, draw} from './canvas'; import {getNestedBoundingClientRect} from '../utils'; import type {NativeType} from '../../types'; import type {Rect} from '../utils'; // How long the rect should be shown for? const DISPLAY_DURATION = 250; // What's the longest we are willing to show the overlay for? // This can be important if we're getting a flurry of events (e.g. scroll update). const MAX_DISPLAY_DURATION = 3000; // How long should a rect be considered valid for? const REMEASUREMENT_AFTER_DURATION = 250; // Some environments (e.g. React Native / Hermes) don't support the performance API yet. const getCurrentTime = // $FlowFixMe[method-unbinding] typeof performance === 'object' && typeof performance.now === 'function' ? () => performance.now() : () => Date.now(); export type Data = { count: number, expirationTime: number, lastMeasuredAt: number, rect: Rect | null, }; const nodeToData: Map<NativeType, Data> = new Map(); let agent: Agent = ((null: any): Agent); let drawAnimationFrameID: AnimationFrameID | null = null; let isEnabled: boolean = false; let redrawTimeoutID: TimeoutID | null = null; export function initialize(injectedAgent: Agent): void { agent = injectedAgent; agent.addListener('traceUpdates', traceUpdates); } export function toggleEnabled(value: boolean): void { isEnabled = value; if (!isEnabled) { nodeToData.clear(); if (drawAnimationFrameID !== null) { cancelAnimationFrame(drawAnimationFrameID); drawAnimationFrameID = null; } if (redrawTimeoutID !== null) { clearTimeout(redrawTimeoutID); redrawTimeoutID = null; } destroyCanvas(agent); } } function traceUpdates(nodes: Set<NativeType>): void { if (!isEnabled) { return; } nodes.forEach(node => { const data = nodeToData.get(node); const now = getCurrentTime(); let lastMeasuredAt = data != null ? data.lastMeasuredAt : 0; let rect = data != null ? data.rect : null; if (rect === null || lastMeasuredAt + REMEASUREMENT_AFTER_DURATION < now) { lastMeasuredAt = now; rect = measureNode(node); } nodeToData.set(node, { count: data != null ? data.count + 1 : 1, expirationTime: data != null ? Math.min( now + MAX_DISPLAY_DURATION, data.expirationTime + DISPLAY_DURATION, ) : now + DISPLAY_DURATION, lastMeasuredAt, rect, }); }); if (redrawTimeoutID !== null) { clearTimeout(redrawTimeoutID); redrawTimeoutID = null; } if (drawAnimationFrameID === null) { drawAnimationFrameID = requestAnimationFrame(prepareToDraw); } } function prepareToDraw(): void { drawAnimationFrameID = null; redrawTimeoutID = null; const now = getCurrentTime(); let earliestExpiration = Number.MAX_VALUE; // Remove any items that have already expired. nodeToData.forEach((data, node) => { if (data.expirationTime < now) { nodeToData.delete(node); } else { earliestExpiration = Math.min(earliestExpiration, data.expirationTime); } }); draw(nodeToData, agent); if (earliestExpiration !== Number.MAX_VALUE) { redrawTimeoutID = setTimeout(prepareToDraw, earliestExpiration - now); } } function measureNode(node: Object): Rect | null { if (!node || typeof node.getBoundingClientRect !== 'function') { return null; } const currentWindow = window.__REACT_DEVTOOLS_TARGET_WINDOW__ || window; return getNestedBoundingClientRect(node, currentWindow); }
25.393103
88
0.670413
owtf
import TestCase from '../../TestCase'; const React = window.React; class MouseMovement extends React.Component { state = { movement: {x: 0, y: 0}, }; onMove = event => { this.setState({x: event.movementX, y: event.movementY}); }; render() { const {x, y} = this.state; const boxStyle = { padding: '10px 20px', border: '1px solid #d9d9d9', margin: '10px 0 20px', }; return ( <TestCase title="Mouse Movement" description="We polyfill the movementX and movementY fields." affectedBrowsers="IE, Safari"> <TestCase.Steps> <li>Mouse over the box below</li> </TestCase.Steps> <TestCase.ExpectedResult> The reported values should equal the pixel (integer) difference between mouse movements positions. </TestCase.ExpectedResult> <div style={boxStyle} onMouseMove={this.onMove}> <p>Trace your mouse over this box.</p> <p> Last movement: {x},{y} </p> </div> </TestCase> ); } } export default MouseMovement;
21.857143
73
0.573727
owtf
#!/usr/bin/env node const finalhandler = require('finalhandler'); const http = require('http'); const serveStatic = require('serve-static'); // Serve fixtures folder const serve = serveStatic(__dirname, {index: 'index.html'}); // Create server const server = http.createServer(function onRequest(req, res) { serve(req, res, finalhandler(req, res)); }); // Listen server.listen(3000);
22
63
0.710256
PenetrationTestingScripts
#!/usr/bin/env node 'use strict'; const deploy = require('../deploy'); const main = async () => await deploy('edge'); main();
12.1
46
0.607692
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireDefault(require("react")); var _useTheme = _interopRequireDefault(require("./useTheme")); var _jsxFileName = ""; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Component() { const theme = (0, _useTheme.default)(); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 10 } }, "theme: ", theme); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsS0FBSyxHQUFHLHdCQUFkO0FBRUEsc0JBQU87QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsZ0JBQWFBLEtBQWIsQ0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCc7XG5pbXBvcnQgdXNlVGhlbWUgZnJvbSAnLi91c2VUaGVtZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlVGhlbWUoKTtcblxuICByZXR1cm4gPGRpdj50aGVtZToge3RoZW1lfTwvZGl2Pjtcbn1cbiJdfQ==
57.692308
924
0.850492
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export function useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { // Note: The shim does not use getServerSnapshot, because pre-18 versions of // React do not expose a way to check if we're hydrating. So users of the shim // will need to track that themselves and return the correct value // from `getSnapshot`. return getSnapshot(); }
28.952381
80
0.678344
PenTestScripts
/** * 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. * * @emails react-core * @jest-environment node */ 'use strict'; const heldValues = []; let finalizationCallback; function FinalizationRegistryMock(callback) { finalizationCallback = callback; } FinalizationRegistryMock.prototype.register = function (target, heldValue) { heldValues.push(heldValue); }; global.FinalizationRegistry = FinalizationRegistryMock; function gc() { for (let i = 0; i < heldValues.length; i++) { finalizationCallback(heldValues[i]); } heldValues.length = 0; } let act; let use; let startTransition; let React; let ReactServer; let ReactNoop; let ReactNoopFlightServer; let ReactNoopFlightClient; let ErrorBoundary; let NoErrorExpected; let Scheduler; let assertLog; describe('ReactFlight', () => { beforeEach(() => { jest.resetModules(); jest.mock('react', () => require('react/react.shared-subset')); ReactServer = require('react'); ReactNoopFlightServer = require('react-noop-renderer/flight-server'); // This stores the state so we need to preserve it const flightModules = require('react-noop-renderer/flight-modules'); __unmockReact(); jest.resetModules(); jest.mock('react-noop-renderer/flight-modules', () => flightModules); React = require('react'); startTransition = React.startTransition; use = React.use; ReactNoop = require('react-noop-renderer'); ReactNoopFlightClient = require('react-noop-renderer/flight-client'); act = require('internal-test-utils').act; Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; ErrorBoundary = class extends React.Component { state = {hasError: false, error: null}; static getDerivedStateFromError(error) { return { hasError: true, error, }; } componentDidMount() { expect(this.state.hasError).toBe(true); expect(this.state.error).toBeTruthy(); if (__DEV__) { expect(this.state.error.message).toContain( this.props.expectedMessage, ); expect(this.state.error.digest).toBe('a dev digest'); } else { expect(this.state.error.message).toBe( 'An error occurred in the Server Components render. The specific message is omitted in production' + ' builds to avoid leaking sensitive details. A digest property is included on this error instance which' + ' may provide additional details about the nature of the error.', ); expect(this.state.error.digest).toContain(this.props.expectedMessage); expect(this.state.error.stack).toBe( 'Error: ' + this.state.error.message, ); } } render() { if (this.state.hasError) { return this.state.error.message; } return this.props.children; } }; NoErrorExpected = class extends React.Component { state = {hasError: false, error: null}; static getDerivedStateFromError(error) { return { hasError: true, error, }; } componentDidMount() { expect(this.state.error).toBe(null); expect(this.state.hasError).toBe(false); } render() { if (this.state.hasError) { return this.state.error.message; } return this.props.children; } }; }); afterEach(() => { jest.restoreAllMocks(); }); function createServerContext(globalName, defaultValue, withStack) { let ctx; expect(() => { ctx = React.createServerContext(globalName, defaultValue); }).toErrorDev( 'Server Context is deprecated and will soon be removed. ' + 'It was never documented and we have found it not to be useful ' + 'enough to warrant the downside it imposes on all apps.', {withoutStack: !withStack}, ); return ctx; } function createServerServerContext(globalName, defaultValue, withStack) { let ctx; expect(() => { ctx = ReactServer.createServerContext(globalName, defaultValue); }).toErrorDev( 'Server Context is deprecated and will soon be removed. ' + 'It was never documented and we have found it not to be useful ' + 'enough to warrant the downside it imposes on all apps.', {withoutStack: !withStack}, ); return ctx; } function clientReference(value) { return Object.defineProperties( function () { throw new Error('Cannot call a client function from the server.'); }, { $$typeof: {value: Symbol.for('react.client.reference')}, value: {value: value}, }, ); } it('can render a Server Component', async () => { function Bar({text}) { return text.toUpperCase(); } function Foo() { return { bar: ( <div> <Bar text="a" />, <Bar text="b" /> </div> ), }; } const transport = ReactNoopFlightServer.render({ foo: <Foo />, }); const model = await ReactNoopFlightClient.read(transport); expect(model).toEqual({ foo: { bar: ( <div> {'A'} {', '} {'B'} </div> ), }, }); }); it('can render a Client Component using a module reference and render there', async () => { function UserClient(props) { return ( <span> {props.greeting}, {props.name} </span> ); } const User = clientReference(UserClient); function Greeting({firstName, lastName}) { return <User greeting="Hello" name={firstName + ' ' + lastName} />; } const model = { greeting: <Greeting firstName="Seb" lastName="Smith" />, }; const transport = ReactNoopFlightServer.render(model); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); const greeting = rootModel.greeting; ReactNoop.render(greeting); }); expect(ReactNoop).toMatchRenderedOutput(<span>Hello, Seb Smith</span>); }); it('can render an iterable as an array', async () => { function ItemListClient(props) { return <span>{props.items}</span>; } const ItemList = clientReference(ItemListClient); function Items() { const iterable = { [Symbol.iterator]: function* () { yield 'A'; yield 'B'; yield 'C'; }, }; return <ItemList items={iterable} />; } const model = <Items />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(<span>ABC</span>); }); it('can render undefined', async () => { function Undefined() { return undefined; } const model = <Undefined />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate FIXME it('should transport undefined object values', async () => { function ServerComponent(props) { return 'prop' in props ? `\`prop\` in props as '${props.prop}'` : '`prop` not in props'; } const ClientComponent = clientReference(ServerComponent); const model = ( <> <div> Server: <ServerComponent prop={undefined} /> </div> <div> Client: <ClientComponent prop={undefined} /> </div> </> ); const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput( <> <div>Server: `prop` in props as 'undefined'</div> <div>Client: `prop` in props as 'undefined'</div> </>, ); }); it('can render an empty fragment', async () => { function Empty() { return <React.Fragment />; } const model = <Empty />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(null); }); it('can transport weird numbers', async () => { const nums = [0, -0, Infinity, -Infinity, NaN]; function ComponentClient({prop}) { expect(prop).not.toBe(nums); expect(prop).toEqual(nums); expect(prop.every((p, i) => Object.is(p, nums[i]))).toBe(true); return `prop: ${prop}`; } const Component = clientReference(ComponentClient); const model = <Component prop={nums} />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput( // already checked -0 with expects above 'prop: 0,0,Infinity,-Infinity,NaN', ); }); it('can transport BigInt', async () => { function ComponentClient({prop}) { return `prop: ${prop} (${typeof prop})`; } const Component = clientReference(ComponentClient); const model = <Component prop={90071992547409910000n} />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput( 'prop: 90071992547409910000 (bigint)', ); }); it('can transport Date', async () => { function ComponentClient({prop}) { return `prop: ${prop.toISOString()}`; } const Component = clientReference(ComponentClient); const model = <Component prop={new Date(1234567890123)} />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput('prop: 2009-02-13T23:31:30.123Z'); }); it('can transport Map', async () => { function ComponentClient({prop, selected}) { return ` map: ${prop instanceof Map} size: ${prop.size} greet: ${prop.get('hi').greet} content: ${JSON.stringify(Array.from(prop))} selected: ${prop.get(selected)} `; } const Component = clientReference(ComponentClient); const objKey = {obj: 'key'}; const map = new Map([ ['hi', {greet: 'world'}], [objKey, 123], ]); const model = <Component prop={map} selected={objKey} />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(` map: true size: 2 greet: world content: [["hi",{"greet":"world"}],[{"obj":"key"},123]] selected: 123 `); }); it('can transport Set', async () => { function ComponentClient({prop, selected}) { return ` set: ${prop instanceof Set} size: ${prop.size} hi: ${prop.has('hi')} content: ${JSON.stringify(Array.from(prop))} selected: ${prop.has(selected)} `; } const Component = clientReference(ComponentClient); const objKey = {obj: 'key'}; const set = new Set(['hi', objKey]); const model = <Component prop={set} selected={objKey} />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(` set: true size: 2 hi: true content: ["hi",{"obj":"key"}] selected: true `); }); it('can transport cyclic objects', async () => { function ComponentClient({prop}) { expect(prop.obj.obj.obj).toBe(prop.obj.obj); } const Component = clientReference(ComponentClient); const cyclic = {obj: null}; cyclic.obj = cyclic; const model = <Component prop={cyclic} />; const transport = ReactNoopFlightServer.render(model); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); }); it('can render a lazy component as a shared component on the server', async () => { function SharedComponent({text}) { return ( <div> shared<span>{text}</span> </div> ); } let load = null; const loadSharedComponent = () => { return new Promise(res => { load = () => res({default: SharedComponent}); }); }; const LazySharedComponent = React.lazy(loadSharedComponent); function ServerComponent() { return ( <React.Suspense fallback={'Loading...'}> <LazySharedComponent text={'a'} /> </React.Suspense> ); } const transport = ReactNoopFlightServer.render(<ServerComponent />); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput('Loading...'); await load(); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput( <div> shared<span>a</span> </div>, ); }); it('errors on a Lazy element being used in Component position', async () => { function SharedComponent({text}) { return ( <div> shared<span>{text}</span> </div> ); } let load = null; const LazyElementDisguisedAsComponent = React.lazy(() => { return new Promise(res => { load = () => res({default: <SharedComponent text={'a'} />}); }); }); function ServerComponent() { return ( <React.Suspense fallback={'Loading...'}> <LazyElementDisguisedAsComponent text={'b'} /> </React.Suspense> ); } const transport = ReactNoopFlightServer.render(<ServerComponent />); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput('Loading...'); spyOnDevAndProd(console, 'error').mockImplementation(() => {}); await load(); expect(console.error).toHaveBeenCalledTimes(1); }); it('can render a lazy element', async () => { function SharedComponent({text}) { return ( <div> shared<span>{text}</span> </div> ); } let load = null; const lazySharedElement = React.lazy(() => { return new Promise(res => { load = () => res({default: <SharedComponent text={'a'} />}); }); }); function ServerComponent() { return ( <React.Suspense fallback={'Loading...'}> {lazySharedElement} </React.Suspense> ); } const transport = ReactNoopFlightServer.render(<ServerComponent />); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput('Loading...'); await load(); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput( <div> shared<span>a</span> </div>, ); }); it('errors with lazy value in element position that resolves to Component', async () => { function SharedComponent({text}) { return ( <div> shared<span>{text}</span> </div> ); } let load = null; const componentDisguisedAsElement = React.lazy(() => { return new Promise(res => { load = () => res({default: SharedComponent}); }); }); function ServerComponent() { return ( <React.Suspense fallback={'Loading...'}> {componentDisguisedAsElement} </React.Suspense> ); } const transport = ReactNoopFlightServer.render(<ServerComponent />); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput('Loading...'); spyOnDevAndProd(console, 'error').mockImplementation(() => {}); await load(); expect(console.error).toHaveBeenCalledTimes(1); }); it('can render a lazy module reference', async () => { function ClientComponent() { return <div>I am client</div>; } const ClientComponentReference = clientReference(ClientComponent); let load = null; const loadClientComponentReference = () => { return new Promise(res => { load = () => res({default: ClientComponentReference}); }); }; const LazyClientComponentReference = React.lazy( loadClientComponentReference, ); function ServerComponent() { return ( <React.Suspense fallback={'Loading...'}> <LazyClientComponentReference /> </React.Suspense> ); } const transport = ReactNoopFlightServer.render(<ServerComponent />); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput('Loading...'); await load(); await act(async () => { const rootModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(rootModel); }); expect(ReactNoop).toMatchRenderedOutput(<div>I am client</div>); }); it('should error if a non-serializable value is passed to a host component', async () => { function ClientImpl({children}) { return children; } const Client = clientReference(ClientImpl); function EventHandlerProp() { return ( <div className="foo" onClick={function () {}}> Test </div> ); } function FunctionProp() { return <div>{() => {}}</div>; } function SymbolProp() { return <div foo={Symbol('foo')} />; } const ref = React.createRef(); function RefProp() { return <div ref={ref} />; } function EventHandlerPropClient() { return ( <Client className="foo" onClick={function () {}}> Test </Client> ); } function FunctionPropClient() { return <Client>{() => {}}</Client>; } function SymbolPropClient() { return <Client foo={Symbol('foo')} />; } function RefPropClient() { return <Client ref={ref} />; } const options = { onError(x) { return __DEV__ ? 'a dev digest' : `digest("${x.message}")`; }, }; const event = ReactNoopFlightServer.render(<EventHandlerProp />, options); const fn = ReactNoopFlightServer.render(<FunctionProp />, options); const symbol = ReactNoopFlightServer.render(<SymbolProp />, options); const refs = ReactNoopFlightServer.render(<RefProp />, options); const eventClient = ReactNoopFlightServer.render( <EventHandlerPropClient />, options, ); const fnClient = ReactNoopFlightServer.render( <FunctionPropClient />, options, ); const symbolClient = ReactNoopFlightServer.render( <SymbolPropClient />, options, ); const refsClient = ReactNoopFlightServer.render(<RefPropClient />, options); function Render({promise}) { return use(promise); } await act(() => { startTransition(() => { ReactNoop.render( <> <ErrorBoundary expectedMessage="Event handlers cannot be passed to Client Component props."> <Render promise={ReactNoopFlightClient.read(event)} /> </ErrorBoundary> <ErrorBoundary expectedMessage={ 'Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".' }> <Render promise={ReactNoopFlightClient.read(fn)} /> </ErrorBoundary> <ErrorBoundary expectedMessage="Only global symbols received from Symbol.for(...) can be passed to Client Components."> <Render promise={ReactNoopFlightClient.read(symbol)} /> </ErrorBoundary> <ErrorBoundary expectedMessage="Refs cannot be used in Server Components, nor passed to Client Components."> <Render promise={ReactNoopFlightClient.read(refs)} /> </ErrorBoundary> <ErrorBoundary expectedMessage="Event handlers cannot be passed to Client Component props."> <Render promise={ReactNoopFlightClient.read(eventClient)} /> </ErrorBoundary> <ErrorBoundary expectedMessage={ 'Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".' }> <Render promise={ReactNoopFlightClient.read(fnClient)} /> </ErrorBoundary> <ErrorBoundary expectedMessage="Only global symbols received from Symbol.for(...) can be passed to Client Components."> <Render promise={ReactNoopFlightClient.read(symbolClient)} /> </ErrorBoundary> <ErrorBoundary expectedMessage="Refs cannot be used in Server Components, nor passed to Client Components."> <Render promise={ReactNoopFlightClient.read(refsClient)} /> </ErrorBoundary> </>, ); }); }); }); it('should trigger the inner most error boundary inside a Client Component', async () => { function ServerComponent() { throw new Error('This was thrown in the Server Component.'); } function ClientComponent({children}) { // This should catch the error thrown by the Server Component, even though it has already happened. // We currently need to wrap it in a div because as it's set up right now, a lazy reference will // throw during reconciliation which will trigger the parent of the error boundary. // This is similar to how these will suspend the parent if it's a direct child of a Suspense boundary. // That's a bug. return ( <ErrorBoundary expectedMessage="This was thrown in the Server Component."> <div>{children}</div> </ErrorBoundary> ); } const ClientComponentReference = clientReference(ClientComponent); function Server() { return ( <ClientComponentReference> <ServerComponent /> </ClientComponentReference> ); } const data = ReactNoopFlightServer.render(<Server />, { onError(x) { // ignore }, }); function Client({promise}) { return use(promise); } await act(() => { startTransition(() => { ReactNoop.render( <NoErrorExpected> <Client promise={ReactNoopFlightClient.read(data)} /> </NoErrorExpected>, ); }); }); }); it('should warn in DEV if a toJSON instance is passed to a host component', () => { const obj = { toJSON() { return 123; }, }; expect(() => { const transport = ReactNoopFlightServer.render(<input value={obj} />); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. ' + 'Convert it manually to a simple value before passing it to props.\n' + ' <input value={{toJSON: function}}>\n' + ' ^^^^^^^^^^^^^^^^^^^^', {withoutStack: true}, ); }); it('should warn in DEV if a toJSON instance is passed to a host component child', () => { class MyError extends Error { toJSON() { return 123; } } expect(() => { const transport = ReactNoopFlightServer.render( <div>Womp womp: {new MyError('spaghetti')}</div>, ); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Error objects cannot be rendered as text children. Try formatting it using toString().\n' + ' <div>Womp womp: {Error}</div>\n' + ' ^^^^^^^', {withoutStack: true}, ); }); it('should warn in DEV if a special object is passed to a host component', () => { expect(() => { const transport = ReactNoopFlightServer.render(<input value={Math} />); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Math objects are not supported.\n' + ' <input value={Math}>\n' + ' ^^^^^^', {withoutStack: true}, ); }); it('should warn in DEV if an object with symbols is passed to a host component', () => { expect(() => { const transport = ReactNoopFlightServer.render( <input value={{[Symbol.iterator]: {}}} />, ); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like Symbol.iterator are not supported.', {withoutStack: true}, ); }); it('should warn in DEV if a toJSON instance is passed to a Client Component', () => { const obj = { toJSON() { return 123; }, }; function ClientImpl({value}) { return <div>{value}</div>; } const Client = clientReference(ClientImpl); expect(() => { const transport = ReactNoopFlightServer.render(<Client value={obj} />); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported.', {withoutStack: true}, ); }); it('should warn in DEV if a toJSON instance is passed to a Client Component child', () => { const obj = { toJSON() { return 123; }, }; function ClientImpl({children}) { return <div>{children}</div>; } const Client = clientReference(ClientImpl); expect(() => { const transport = ReactNoopFlightServer.render( <Client>Current date: {obj}</Client>, ); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. ' + 'Convert it manually to a simple value before passing it to props.\n' + ' <>Current date: {{toJSON: function}}</>\n' + ' ^^^^^^^^^^^^^^^^^^^^', {withoutStack: true}, ); }); it('should warn in DEV if a special object is passed to a Client Component', () => { function ClientImpl({value}) { return <div>{value}</div>; } const Client = clientReference(ClientImpl); expect(() => { const transport = ReactNoopFlightServer.render(<Client value={Math} />); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Math objects are not supported.\n' + ' <... value={Math}>\n' + ' ^^^^^^', {withoutStack: true}, ); }); it('should warn in DEV if an object with symbols is passed to a Client Component', () => { function ClientImpl({value}) { return <div>{value}</div>; } const Client = clientReference(ClientImpl); expect(() => { const transport = ReactNoopFlightServer.render( <Client value={{[Symbol.iterator]: {}}} />, ); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like Symbol.iterator are not supported.', {withoutStack: true}, ); }); it('should warn in DEV if a special object is passed to a nested object in Client Component', () => { function ClientImpl({value}) { return <div>{value}</div>; } const Client = clientReference(ClientImpl); expect(() => { const transport = ReactNoopFlightServer.render( <Client value={{hello: Math, title: <h1>hi</h1>}} />, ); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Math objects are not supported.\n' + ' {hello: Math, title: <h1/>}\n' + ' ^^^^', {withoutStack: true}, ); }); it('should warn in DEV if a special object is passed to a nested array in Client Component', () => { function ClientImpl({value}) { return <div>{value}</div>; } const Client = clientReference(ClientImpl); expect(() => { const transport = ReactNoopFlightServer.render( <Client value={['looooong string takes up noise', Math, <h1>hi</h1>]} />, ); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Only plain objects can be passed to Client Components from Server Components. ' + 'Math objects are not supported.\n' + ' [..., Math, <h1/>]\n' + ' ^^^^', {withoutStack: true}, ); }); it('should NOT warn in DEV for key getters', () => { const transport = ReactNoopFlightServer.render(<div key="a" />); ReactNoopFlightClient.read(transport); }); it('should warn in DEV a child is missing keys', () => { function ParentClient({children}) { return children; } const Parent = clientReference(ParentClient); expect(() => { const transport = ReactNoopFlightServer.render( <Parent>{Array(6).fill(<div>no key</div>)}</Parent>, ); ReactNoopFlightClient.read(transport); }).toErrorDev( 'Each child in a list should have a unique "key" prop. ' + 'See https://reactjs.org/link/warning-keys for more information.', ); }); it('should error if a class instance is passed to a host component', () => { class Foo { method() {} } const errors = []; ReactNoopFlightServer.render(<input value={new Foo()} />, { onError(x) { errors.push(x.message); }, }); expect(errors).toEqual([ 'Only plain objects, and a few built-ins, can be passed to Client Components ' + 'from Server Components. Classes or null prototypes are not supported.', ]); }); it('should warn in DEV if a a client reference is passed to useContext()', () => { const Context = React.createContext(); const ClientContext = clientReference(Context); function ServerComponent() { return ReactServer.useContext(ClientContext); } expect(() => { const transport = ReactNoopFlightServer.render(<ServerComponent />); ReactNoopFlightClient.read(transport); }).toErrorDev('Cannot read a Client Context from a Server Component.', { withoutStack: true, }); }); describe('Hooks', () => { function DivWithId({children}) { const id = ReactServer.useId(); return <div prop={id}>{children}</div>; } it('should support useId', async () => { function App() { return ( <> <DivWithId /> <DivWithId /> </> ); } const transport = ReactNoopFlightServer.render(<App />); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput( <> <div prop=":S1:" /> <div prop=":S2:" /> </>, ); }); it('accepts an identifier prefix that prefixes generated ids', async () => { function App() { return ( <> <DivWithId /> <DivWithId /> </> ); } const transport = ReactNoopFlightServer.render(<App />, { identifierPrefix: 'foo', }); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput( <> <div prop=":fooS1:" /> <div prop=":fooS2:" /> </>, ); }); it('[TODO] it does not warn if you render a server element passed to a client module reference twice on the client when using useId', async () => { // @TODO Today if you render a Server Component with useId and pass it to a Client Component and that Client Component renders the element in two or more // places the id used on the server will be duplicated in the client. This is a deviation from the guarantees useId makes for Fizz/Client and is a consequence // of the fact that the Server Component is actually rendered on the server and is reduced to a set of host elements before being passed to the Client component // so the output passed to the Client has no knowledge of the useId use. In the future we would like to add a DEV warning when this happens. For now // we just accept that it is a nuance of useId in Flight function App() { const id = ReactServer.useId(); const div = <div prop={id}>{id}</div>; return <ClientDoublerModuleRef el={div} />; } function ClientDoubler({el}) { Scheduler.log('ClientDoubler'); return ( <> {el} {el} </> ); } const ClientDoublerModuleRef = clientReference(ClientDoubler); const transport = ReactNoopFlightServer.render(<App />); assertLog([]); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); assertLog(['ClientDoubler']); expect(ReactNoop).toMatchRenderedOutput( <> <div prop=":S1:">:S1:</div> <div prop=":S1:">:S1:</div> </>, ); }); }); describe('ServerContext', () => { // @gate enableServerContext it('supports basic createServerContext usage', async () => { const ServerContext = createServerServerContext( 'ServerContext', 'hello from server', ); function Foo() { const context = ReactServer.useContext(ServerContext); return <div>{context}</div>; } const transport = ReactNoopFlightServer.render(<Foo />); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(<div>hello from server</div>); }); // @gate enableServerContext it('propagates ServerContext providers in flight', async () => { const ServerContext = createServerServerContext( 'ServerContext', 'default', ); function Foo() { return ( <div> <ServerContext.Provider value="hi this is server"> <Bar /> </ServerContext.Provider> </div> ); } function Bar() { const context = ReactServer.useContext(ServerContext); return context; } const transport = ReactNoopFlightServer.render(<Foo />); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(<div>hi this is server</div>); }); // @gate enableServerContext it('errors if you try passing JSX through ServerContext value', () => { const ServerContext = createServerServerContext('ServerContext', { foo: { bar: <span>hi this is default</span>, }, }); function Foo() { return ( <div> <ServerContext.Provider value={{ foo: { bar: <span>hi this is server</span>, }, }}> <Bar /> </ServerContext.Provider> </div> ); } function Bar() { const context = ReactServer.useContext(ServerContext); return context.foo.bar; } expect(() => { ReactNoopFlightServer.render(<Foo />); }).toErrorDev('React elements are not allowed in ServerContext', { withoutStack: true, }); }); // @gate enableServerContext it('propagates ServerContext and cleans up the providers in flight', async () => { const ServerContext = createServerServerContext( 'ServerContext', 'default', ); function Foo() { return ( <> <ServerContext.Provider value="hi this is server outer"> <ServerContext.Provider value="hi this is server"> <Bar /> </ServerContext.Provider> <ServerContext.Provider value="hi this is server2"> <Bar /> </ServerContext.Provider> <Bar /> </ServerContext.Provider> <ServerContext.Provider value="hi this is server outer2"> <Bar /> </ServerContext.Provider> <Bar /> </> ); } function Bar() { const context = ReactServer.useContext(ServerContext); return <span>{context}</span>; } const transport = ReactNoopFlightServer.render(<Foo />); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput( <> <span>hi this is server</span> <span>hi this is server2</span> <span>hi this is server outer</span> <span>hi this is server outer2</span> <span>default</span> </>, ); }); // @gate enableServerContext it('propagates ServerContext providers in flight after suspending', async () => { const ServerContext = createServerServerContext( 'ServerContext', 'default', ); function Foo() { return ( <div> <ServerContext.Provider value="hi this is server"> <React.Suspense fallback={'Loading'}> <Bar /> </React.Suspense> </ServerContext.Provider> </div> ); } let resolve; const promise = new Promise(res => { resolve = () => { promise.unsuspend = true; res(); }; }); function Bar() { if (!promise.unsuspend) { Scheduler.log('suspended'); throw promise; } Scheduler.log('rendered'); const context = ReactServer.useContext(ServerContext); return context; } const transport = ReactNoopFlightServer.render(<Foo />); assertLog(['suspended']); await act(async () => { resolve(); await promise; jest.runAllImmediates(); }); assertLog(['rendered']); await act(async () => { ReactNoop.render(await ReactNoopFlightClient.read(transport)); }); expect(ReactNoop).toMatchRenderedOutput(<div>hi this is server</div>); }); // @gate enableServerContext it('serializes ServerContext to client', async () => { const ServerContext = createServerServerContext( 'ServerContext', 'default', ); const ClientContext = createServerContext('ServerContext', 'default'); function ClientBar() { Scheduler.log('ClientBar'); const context = React.useContext(ClientContext); return <span>{context}</span>; } const Bar = clientReference(ClientBar); function Foo() { return ( <ServerContext.Provider value="hi this is server"> <Bar /> </ServerContext.Provider> ); } const model = { foo: <Foo />, }; const transport = ReactNoopFlightServer.render(model); assertLog([]); await act(async () => { const flightModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(flightModel.foo); }); assertLog(['ClientBar']); expect(ReactNoop).toMatchRenderedOutput(<span>hi this is server</span>); expect(() => { createServerContext('ServerContext', 'default'); }).toThrow('ServerContext: ServerContext already defined'); }); // @gate enableServerContext it('takes ServerContext from the client for refetching use cases', async () => { const ServerContext = createServerServerContext( 'ServerContext', 'default', ); function Bar() { return <span>{ReactServer.useContext(ServerContext)}</span>; } const transport = ReactNoopFlightServer.render(<Bar />, { context: [['ServerContext', 'Override']], }); await act(async () => { const flightModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(flightModel); }); expect(ReactNoop).toMatchRenderedOutput(<span>Override</span>); }); // @gate enableServerContext it('sets default initial value when defined lazily on server or client', async () => { let ServerContext; function inlineLazyServerContextInitialization() { if (!ServerContext) { ServerContext = createServerServerContext('ServerContext', 'default'); } return ServerContext; } let ClientContext; function inlineContextInitialization() { if (!ClientContext) { ClientContext = createServerContext('ServerContext', 'default', true); } return ClientContext; } function ClientBaz() { const context = inlineContextInitialization(); const value = React.useContext(context); return <div>{value}</div>; } const Baz = clientReference(ClientBaz); function Bar() { return ( <article> <div> {ReactServer.useContext(inlineLazyServerContextInitialization())} </div> <Baz /> </article> ); } function ServerApp() { const Context = inlineLazyServerContextInitialization(); return ( <> <Context.Provider value="test"> <Bar /> </Context.Provider> <Bar /> </> ); } function ClientApp({serverModel}) { return ( <> {serverModel} <ClientBaz /> </> ); } const transport = ReactNoopFlightServer.render(<ServerApp />); expect(ClientContext).toBe(undefined); // Reset all modules, except flight-modules which keeps the registry of Client Components const flightModules = require('react-noop-renderer/flight-modules'); jest.resetModules(); jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-noop-renderer/flight-modules', () => flightModules); ReactServer = require('react'); ReactNoopFlightServer = require('react-noop-renderer/flight-server'); __unmockReact(); jest.resetModules(); jest.mock('react-noop-renderer/flight-modules', () => flightModules); React = require('react'); ReactNoop = require('react-noop-renderer'); ReactNoopFlightClient = require('react-noop-renderer/flight-client'); act = require('internal-test-utils').act; Scheduler = require('scheduler'); await act(async () => { const serverModel = await ReactNoopFlightClient.read(transport); ReactNoop.render(<ClientApp serverModel={serverModel} />); }); expect(ClientContext).not.toBe(ServerContext); expect(ReactNoop).toMatchRenderedOutput( <> <article> <div>test</div> <div>test</div> </article> <article> <div>default</div> <div>default</div> </article> <div>default</div> </>, ); }); }); // @gate enableTaint it('errors when a tainted object is serialized', async () => { function UserClient({user}) { return <span>{user.name}</span>; } const User = clientReference(UserClient); const user = { name: 'Seb', age: 'rather not say', }; ReactServer.experimental_taintObjectReference( "Don't pass the raw user object to the client", user, ); const errors = []; ReactNoopFlightServer.render(<User user={user} />, { onError(x) { errors.push(x.message); }, }); expect(errors).toEqual(["Don't pass the raw user object to the client"]); }); // @gate enableTaint it('errors with a specific message when a tainted function is serialized', async () => { function UserClient({user}) { return <span>{user.name}</span>; } const User = clientReference(UserClient); function change() {} ReactServer.experimental_taintObjectReference( 'A change handler cannot be passed to a client component', change, ); const errors = []; ReactNoopFlightServer.render(<User onChange={change} />, { onError(x) { errors.push(x.message); }, }); expect(errors).toEqual([ 'A change handler cannot be passed to a client component', ]); }); // @gate enableTaint it('errors when a tainted string is serialized', async () => { function UserClient({user}) { return <span>{user.name}</span>; } const User = clientReference(UserClient); const process = { env: { SECRET: '3e971ecc1485fe78625598bf9b6f85db', }, }; ReactServer.experimental_taintUniqueValue( 'Cannot pass a secret token to the client', process, process.env.SECRET, ); const errors = []; ReactNoopFlightServer.render(<User token={process.env.SECRET} />, { onError(x) { errors.push(x.message); }, }); expect(errors).toEqual(['Cannot pass a secret token to the client']); // This just ensures the process object is kept alive for the life time of // the test since we're simulating a global as an example. expect(process.env.SECRET).toBe('3e971ecc1485fe78625598bf9b6f85db'); }); // @gate enableTaint it('errors when a tainted bigint is serialized', async () => { function UserClient({user}) { return <span>{user.name}</span>; } const User = clientReference(UserClient); const currentUser = { name: 'Seb', token: BigInt('0x3e971ecc1485fe78625598bf9b6f85dc'), }; ReactServer.experimental_taintUniqueValue( 'Cannot pass a secret token to the client', currentUser, currentUser.token, ); function App({user}) { return <User token={user.token} />; } const errors = []; ReactNoopFlightServer.render(<App user={currentUser} />, { onError(x) { errors.push(x.message); }, }); expect(errors).toEqual(['Cannot pass a secret token to the client']); }); // @gate enableTaint && enableBinaryFlight it('errors when a tainted binary value is serialized', async () => { function UserClient({user}) { return <span>{user.name}</span>; } const User = clientReference(UserClient); const currentUser = { name: 'Seb', token: new Uint32Array([0x3e971ecc, 0x1485fe78, 0x625598bf, 0x9b6f85dd]), }; ReactServer.experimental_taintUniqueValue( 'Cannot pass a secret token to the client', currentUser, currentUser.token, ); function App({user}) { const clone = user.token.slice(); return <User token={clone} />; } const errors = []; ReactNoopFlightServer.render(<App user={currentUser} />, { onError(x) { errors.push(x.message); }, }); expect(errors).toEqual(['Cannot pass a secret token to the client']); }); // @gate enableTaint it('keep a tainted value tainted until the end of any pending requests', async () => { function UserClient({user}) { return <span>{user.name}</span>; } const User = clientReference(UserClient); function getUser() { const user = { name: 'Seb', token: '3e971ecc1485fe78625598bf9b6f85db', }; ReactServer.experimental_taintUniqueValue( 'Cannot pass a secret token to the client', user, user.token, ); return user; } function App() { const user = getUser(); const derivedValue = {...user}; // A garbage collection can happen at any time. Even before the end of // this request. This would clean up the user object. gc(); // We should still block the tainted value. return <User user={derivedValue} />; } let errors = []; ReactNoopFlightServer.render(<App />, { onError(x) { errors.push(x.message); }, }); expect(errors).toEqual(['Cannot pass a secret token to the client']); // After the previous requests finishes, the token can be rendered again. errors = []; ReactNoopFlightServer.render( <User user={{token: '3e971ecc1485fe78625598bf9b6f85db'}} />, { onError(x) { errors.push(x.message); }, }, ); expect(errors).toEqual([]); }); });
28.410798
166
0.590262
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-dom-bindings/src/client/ReactFiberConfigDOM';
23.727273
66
0.715867
cybersecurity-penetration-testing
/** * 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 {Lane, Lanes} from './ReactFiberLane'; import { NoLane, SyncLane, InputContinuousLane, DefaultLane, IdleLane, getHighestPriorityLane, includesNonIdleWork, } from './ReactFiberLane'; export opaque type EventPriority = Lane; export const DiscreteEventPriority: EventPriority = SyncLane; export const ContinuousEventPriority: EventPriority = InputContinuousLane; export const DefaultEventPriority: EventPriority = DefaultLane; export const IdleEventPriority: EventPriority = IdleLane; let currentUpdatePriority: EventPriority = NoLane; export function getCurrentUpdatePriority(): EventPriority { return currentUpdatePriority; } export function setCurrentUpdatePriority(newPriority: EventPriority) { currentUpdatePriority = newPriority; } export function runWithPriority<T>(priority: EventPriority, fn: () => T): T { const previousPriority = currentUpdatePriority; try { currentUpdatePriority = priority; return fn(); } finally { currentUpdatePriority = previousPriority; } } export function higherEventPriority( a: EventPriority, b: EventPriority, ): EventPriority { return a !== 0 && a < b ? a : b; } export function lowerEventPriority( a: EventPriority, b: EventPriority, ): EventPriority { return a === 0 || a > b ? a : b; } export function isHigherEventPriority( a: EventPriority, b: EventPriority, ): boolean { return a !== 0 && a < b; } export function lanesToEventPriority(lanes: Lanes): EventPriority { const lane = getHighestPriorityLane(lanes); if (!isHigherEventPriority(DiscreteEventPriority, lane)) { return DiscreteEventPriority; } if (!isHigherEventPriority(ContinuousEventPriority, lane)) { return ContinuousEventPriority; } if (includesNonIdleWork(lane)) { return DefaultEventPriority; } return IdleEventPriority; }
23.60241
77
0.743753
cybersecurity-penetration-testing
/** * 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. * * @emails react-core */ 'use strict'; describe('ReactDOMShorthandCSSPropertyCollision', () => { let act; let React; let ReactDOMClient; beforeEach(() => { jest.resetModules(); act = require('internal-test-utils').act; React = require('react'); ReactDOMClient = require('react-dom/client'); }); it('should warn for conflicting CSS shorthand updates', async () => { const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<div style={{font: 'foo', fontStyle: 'bar'}} />); }); await expect(async () => { await act(() => { root.render(<div style={{font: 'foo'}} />); }); }).toErrorDev( 'Warning: Removing a style property during rerender (fontStyle) ' + 'when a conflicting property is set (font) can lead to styling ' + "bugs. To avoid this, don't mix shorthand and non-shorthand " + 'properties for the same value; instead, replace the shorthand ' + 'with separate values.' + '\n in div (at **)', ); // These updates are OK and don't warn: await act(() => { root.render(<div style={{font: 'qux', fontStyle: 'bar'}} />); }); await act(() => { root.render(<div style={{font: 'foo', fontStyle: 'baz'}} />); }); await expect(async () => { await act(() => { root.render(<div style={{font: 'qux', fontStyle: 'baz'}} />); }); }).toErrorDev( 'Warning: Updating a style property during rerender (font) when ' + 'a conflicting property is set (fontStyle) can lead to styling ' + "bugs. To avoid this, don't mix shorthand and non-shorthand " + 'properties for the same value; instead, replace the shorthand ' + 'with separate values.' + '\n in div (at **)', ); await expect(async () => { await act(() => { root.render(<div style={{fontStyle: 'baz'}} />); }); }).toErrorDev( 'Warning: Removing a style property during rerender (font) when ' + 'a conflicting property is set (fontStyle) can lead to styling ' + "bugs. To avoid this, don't mix shorthand and non-shorthand " + 'properties for the same value; instead, replace the shorthand ' + 'with separate values.' + '\n in div (at **)', ); // A bit of a special case: backgroundPosition isn't technically longhand // (it expands to backgroundPosition{X,Y} but so does background) await act(() => { root.render( <div style={{background: 'yellow', backgroundPosition: 'center'}} />, ); }); await expect(async () => { await act(() => { root.render(<div style={{background: 'yellow'}} />); }); }).toErrorDev( 'Warning: Removing a style property during rerender ' + '(backgroundPosition) when a conflicting property is set ' + "(background) can lead to styling bugs. To avoid this, don't mix " + 'shorthand and non-shorthand properties for the same value; ' + 'instead, replace the shorthand with separate values.' + '\n in div (at **)', ); await act(() => { root.render( <div style={{background: 'yellow', backgroundPosition: 'center'}} />, ); }); // But setting them at the same time is OK: await act(() => { root.render( <div style={{background: 'green', backgroundPosition: 'top'}} />, ); }); await expect(async () => { await act(() => { root.render(<div style={{backgroundPosition: 'top'}} />); }); }).toErrorDev( 'Warning: Removing a style property during rerender (background) ' + 'when a conflicting property is set (backgroundPosition) can lead ' + "to styling bugs. To avoid this, don't mix shorthand and " + 'non-shorthand properties for the same value; instead, replace the ' + 'shorthand with separate values.' + '\n in div (at **)', ); // A bit of an even more special case: borderLeft and borderStyle overlap. await act(() => { root.render( <div style={{borderStyle: 'dotted', borderLeft: '1px solid red'}} />, ); }); await expect(async () => { await act(() => { root.render(<div style={{borderLeft: '1px solid red'}} />); }); }).toErrorDev( 'Warning: Removing a style property during rerender (borderStyle) ' + 'when a conflicting property is set (borderLeft) can lead to ' + "styling bugs. To avoid this, don't mix shorthand and " + 'non-shorthand properties for the same value; instead, replace the ' + 'shorthand with separate values.' + '\n in div (at **)', ); await expect(async () => { await act(() => { root.render( <div style={{borderStyle: 'dashed', borderLeft: '1px solid red'}} />, ); }); }).toErrorDev( 'Warning: Updating a style property during rerender (borderStyle) ' + 'when a conflicting property is set (borderLeft) can lead to ' + "styling bugs. To avoid this, don't mix shorthand and " + 'non-shorthand properties for the same value; instead, replace the ' + 'shorthand with separate values.' + '\n in div (at **)', ); // But setting them at the same time is OK: await act(() => { root.render( <div style={{borderStyle: 'dotted', borderLeft: '2px solid red'}} />, ); }); await expect(async () => { await act(() => { root.render(<div style={{borderStyle: 'dotted'}} />); }); }).toErrorDev( 'Warning: Removing a style property during rerender (borderLeft) ' + 'when a conflicting property is set (borderStyle) can lead to ' + "styling bugs. To avoid this, don't mix shorthand and " + 'non-shorthand properties for the same value; instead, replace the ' + 'shorthand with separate values.' + '\n in div (at **)', ); }); });
35.289017
79
0.573682
PenetrationTestingScripts
/** * 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 typeof ReactTestRenderer from 'react-test-renderer'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type Store from 'react-devtools-shared/src/devtools/store'; import type { DispatcherContext, StateContext, } from 'react-devtools-shared/src/devtools/views/Components/TreeContext'; describe('TreeListContext', () => { let React; let ReactDOM; let TestRenderer: ReactTestRenderer; let bridge: FrontendBridge; let legacyRender; let store: Store; let utils; let withErrorsOrWarningsIgnored; let BridgeContext; let StoreContext; let TreeContext; let dispatch: DispatcherContext; let state: StateContext; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); legacyRender = utils.legacyRender; withErrorsOrWarningsIgnored = utils.withErrorsOrWarningsIgnored; bridge = global.bridge; store = global.store; store.collapseNodesByDefault = false; React = require('react'); ReactDOM = require('react-dom'); TestRenderer = utils.requireTestRenderer(); BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext; StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext; TreeContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext'); }); afterEach(() => { // Reset between tests dispatch = ((null: any): DispatcherContext); state = ((null: any): StateContext); }); const Capture = () => { dispatch = React.useContext(TreeContext.TreeDispatcherContext); state = React.useContext(TreeContext.TreeStateContext); return null; }; const Contexts = () => { return ( <BridgeContext.Provider value={bridge}> <StoreContext.Provider value={store}> <TreeContext.TreeContextController> <Capture /> </TreeContext.TreeContextController> </StoreContext.Provider> </BridgeContext.Provider> ); }; describe('tree state', () => { it('should select the next and previous elements in the tree', () => { const Grandparent = () => <Parent />; const Parent = () => ( <React.Fragment> <Child /> <Child /> </React.Fragment> ); const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> <Child> `); // Test stepping through to the end utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Parent> <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → ▾ <Parent> <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> → <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> → <Child> `); // Test stepping back to the beginning utils.act(() => dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> → <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → ▾ <Parent> <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Parent> <Child> <Child> `); // Test wrap around behavior utils.act(() => dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> → <Child> `); utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Parent> <Child> <Child> `); }); it('should select child elements', () => { const Grandparent = () => ( <React.Fragment> <Parent /> <Parent /> </React.Fragment> ); const Parent = () => ( <React.Fragment> <Child /> <Child /> </React.Fragment> ); const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> <Child> ▾ <Parent> <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 0})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Parent> <Child> <Child> ▾ <Parent> <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → ▾ <Parent> <Child> <Child> ▾ <Parent> <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> → <Child> <Child> ▾ <Parent> <Child> <Child> `); // There are no more children to select, so this should be a no-op utils.act(() => dispatch({type: 'SELECT_CHILD_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> → <Child> <Child> ▾ <Parent> <Child> <Child> `); }); it('should select parent elements and then collapse', () => { const Grandparent = () => ( <React.Fragment> <Parent /> <Parent /> </React.Fragment> ); const Parent = () => ( <React.Fragment> <Child /> <Child /> </React.Fragment> ); const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> <Child> ▾ <Parent> <Child> <Child> `); const lastChildID = store.getElementIDAtIndex(store.numElements - 1); // Select the last child utils.act(() => dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: lastChildID}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> <Child> ▾ <Parent> <Child> → <Child> `); // Select its parent utils.act(() => dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> <Child> → ▾ <Parent> <Child> <Child> `); // Select grandparent utils.act(() => dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Parent> <Child> <Child> ▾ <Parent> <Child> <Child> `); // No-op utils.act(() => dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Parent> <Child> <Child> ▾ <Parent> <Child> <Child> `); const previousState = state; // There are no more ancestors to select, so this should be a no-op utils.act(() => dispatch({type: 'SELECT_PARENT_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toEqual(previousState); }); it('should clear selection if the selected element is unmounted', async () => { const Grandparent = props => props.children || null; const Parent = props => props.children || null; const Child = () => null; const container = document.createElement('div'); utils.act(() => legacyRender( <Grandparent> <Parent> <Child /> <Child /> </Parent> </Grandparent>, container, ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> <Child> `); // Select the second child utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 3})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> → <Child> `); // Remove the child (which should auto-select the parent) await utils.actAsync(() => legacyRender( <Grandparent> <Parent /> </Grandparent>, container, ), ); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → <Parent> `); // Unmount the root (so that nothing is selected) await utils.actAsync(() => ReactDOM.unmountComponentAtNode(container)); expect(state).toMatchInlineSnapshot(``); }); it('should navigate next/previous sibling and skip over children in between', () => { const Grandparent = () => ( <React.Fragment> <Parent numChildren={1} /> <Parent numChildren={3} /> <Parent numChildren={2} /> </React.Fragment> ); const Parent = ({numChildren}) => new Array(numChildren) .fill(true) .map((_, index) => <Child key={index} />); const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); const firstParentID = ((store.getElementIDAtIndex(1): any): number); utils.act(() => dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: firstParentID}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → ▾ <Parent> <Child key="0"> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_NEXT_SIBLING_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> → ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_NEXT_SIBLING_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> → ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_NEXT_SIBLING_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → ▾ <Parent> <Child key="0"> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_PREVIOUS_SIBLING_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> → ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_PREVIOUS_SIBLING_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> → ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_PREVIOUS_SIBLING_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → ▾ <Parent> <Child key="0"> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_PREVIOUS_SIBLING_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> → ▾ <Parent> <Child key="0"> <Child key="1"> `); }); it('should navigate the owner hierarchy', () => { const Wrapper = ({children}) => children; const Grandparent = () => ( <React.Fragment> <Wrapper> <Parent numChildren={1} /> </Wrapper> <Wrapper> <Parent numChildren={3} /> </Wrapper> <Wrapper> <Parent numChildren={2} /> </Wrapper> </React.Fragment> ); const Parent = ({numChildren}) => new Array(numChildren) .fill(true) .map((_, index) => <Child key={index} />); const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); const childID = ((store.getElementIDAtIndex(7): any): number); utils.act(() => dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: childID}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> → <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); // Basic navigation test utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> → ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); // Noop (since we're at the root already) utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> → ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> → <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); // Noop (since we're at the leaf node) utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> → <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); // Other navigational actions should clear out the temporary owner chain. utils.act(() => dispatch({type: 'SELECT_PREVIOUS_ELEMENT_IN_TREE'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> → <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); // Start a new tree on parent const parentID = ((store.getElementIDAtIndex(5): any): number); utils.act(() => dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: parentID}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> → ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); // Noop (since we're at the top) utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_PREVIOUS_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> → ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); // Noop (since we're at the leaf of this owner tree) // It should not be possible to navigate beyond the owner chain leaf. utils.act(() => dispatch({type: 'SELECT_OWNER_LIST_NEXT_ELEMENT_IN_TREE'}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Wrapper> ▾ <Parent> <Child key="0"> ▾ <Wrapper> → ▾ <Parent> <Child key="0"> <Child key="1"> <Child key="2"> ▾ <Wrapper> ▾ <Parent> <Child key="0"> <Child key="1"> `); }); }); describe('search state', () => { it('should find elements matching search text', () => { const Foo = () => null; const Bar = () => null; const Baz = () => null; const Qux = () => null; Qux.displayName = `withHOC(${Qux.name})`; utils.act(() => legacyRender( <React.Fragment> <Foo /> <Bar /> <Baz /> <Qux /> </React.Fragment>, document.createElement('div'), ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Bar> <Baz> <Qux> [withHOC] `); // NOTE: multi-match utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Bar> <Baz> <Qux> [withHOC] `); // NOTE: single match utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'f'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → <Foo> <Bar> <Baz> <Qux> [withHOC] `); // NOTE: no match utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'y'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] → <Foo> <Bar> <Baz> <Qux> [withHOC] `); // NOTE: HOC match utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'w'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Bar> <Baz> → <Qux> [withHOC] `); }); it('should select the next and previous items within the search results', () => { const Foo = () => null; const Bar = () => null; const Baz = () => null; utils.act(() => legacyRender( <React.Fragment> <Foo /> <Baz /> <Bar /> <Baz /> </React.Fragment>, document.createElement('div'), ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Baz> <Bar> <Baz> `); // search for "ba" utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Baz> <Bar> <Baz> `); // go to second result utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Baz> → <Bar> <Baz> `); // go to third result utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Baz> <Bar> → <Baz> `); // go to second result utils.act(() => dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Baz> → <Bar> <Baz> `); // go to first result utils.act(() => dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Baz> <Bar> <Baz> `); // wrap to last result utils.act(() => dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Baz> <Bar> → <Baz> `); // wrap to first result utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Baz> <Bar> <Baz> `); }); it('should add newly mounted elements to the search results set if they match the current text', async () => { const Foo = () => null; const Bar = () => null; const Baz = () => null; const container = document.createElement('div'); utils.act(() => legacyRender( <React.Fragment> <Foo /> <Bar /> </React.Fragment>, container, ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Bar> `); utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Bar> `); await utils.actAsync(() => legacyRender( <React.Fragment> <Foo /> <Bar /> <Baz /> </React.Fragment>, container, ), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Bar> <Baz> `); utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Bar> → <Baz> `); }); it('should remove unmounted elements from the search results set', async () => { const Foo = () => null; const Bar = () => null; const Baz = () => null; const container = document.createElement('div'); utils.act(() => legacyRender( <React.Fragment> <Foo /> <Bar /> <Baz /> </React.Fragment>, container, ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Bar> <Baz> `); utils.act(() => dispatch({type: 'SET_SEARCH_TEXT', payload: 'ba'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Bar> <Baz> `); utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Bar> → <Baz> `); await utils.actAsync(() => legacyRender( <React.Fragment> <Foo /> <Bar /> </React.Fragment>, container, ), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> <Bar> `); utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Bar> `); // Noop since the list is now one item long utils.act(() => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Foo> → <Bar> `); }); }); describe('owners state', () => { it('should support entering and existing the owners tree view', () => { const Grandparent = () => <Parent />; const Parent = () => ( <React.Fragment> <Child /> <Child /> </React.Fragment> ); const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child> <Child> `); const parentID = ((store.getElementIDAtIndex(1): any): number); utils.act(() => dispatch({type: 'SELECT_OWNER', payload: parentID})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [owners] → ▾ <Parent> <Child> <Child> `); utils.act(() => dispatch({type: 'RESET_OWNER_STACK'})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> → ▾ <Parent> <Child> <Child> `); }); it('should remove an element from the owners list if it is unmounted', async () => { const Grandparent = ({count}) => <Parent count={count} />; const Parent = ({count}) => new Array(count).fill(true).map((_, index) => <Child key={index} />); const Child = () => null; const container = document.createElement('div'); utils.act(() => legacyRender(<Grandparent count={2} />, container)); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Grandparent> ▾ <Parent> <Child key="0"> <Child key="1"> `); const parentID = ((store.getElementIDAtIndex(1): any): number); utils.act(() => dispatch({type: 'SELECT_OWNER', payload: parentID})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [owners] → ▾ <Parent> <Child key="0"> <Child key="1"> `); await utils.actAsync(() => legacyRender(<Grandparent count={1} />, container), ); expect(state).toMatchInlineSnapshot(` [owners] → ▾ <Parent> <Child key="0"> `); await utils.actAsync(() => legacyRender(<Grandparent count={0} />, container), ); expect(state).toMatchInlineSnapshot(` [owners] → <Parent> `); }); it('should exit the owners list if the current owner is unmounted', async () => { const Parent = props => props.children || null; const Child = () => null; const container = document.createElement('div'); utils.act(() => legacyRender( <Parent> <Child /> </Parent>, container, ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Parent> <Child> `); const childID = ((store.getElementIDAtIndex(1): any): number); utils.act(() => dispatch({type: 'SELECT_OWNER', payload: childID})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [owners] → <Child> `); await utils.actAsync(() => legacyRender(<Parent />, container)); expect(state).toMatchInlineSnapshot(` [root] → <Parent> `); const parentID = ((store.getElementIDAtIndex(0): any): number); utils.act(() => dispatch({type: 'SELECT_OWNER', payload: parentID})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [owners] → <Parent> `); await utils.actAsync(() => ReactDOM.unmountComponentAtNode(container)); expect(state).toMatchInlineSnapshot(``); }); // This tests ensures support for toggling Suspense boundaries outside of the active owners list. it('should exit the owners list if an element outside the list is selected', () => { const Grandchild = () => null; const Child = () => ( <React.Suspense fallback="Loading"> <Grandchild /> </React.Suspense> ); const Parent = () => ( <React.Suspense fallback="Loading"> <Child /> </React.Suspense> ); const container = document.createElement('div'); utils.act(() => legacyRender(<Parent />, container)); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` [root] ▾ <Parent> ▾ <Suspense> ▾ <Child> ▾ <Suspense> <Grandchild> `); const outerSuspenseID = ((store.getElementIDAtIndex(1): any): number); const childID = ((store.getElementIDAtIndex(2): any): number); const innerSuspenseID = ((store.getElementIDAtIndex(3): any): number); utils.act(() => dispatch({type: 'SELECT_OWNER', payload: childID})); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [owners] → ▾ <Child> ▾ <Suspense> <Grandchild> `); // Toggling a Suspense boundary inside of the flat list should update selected index utils.act(() => dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: innerSuspenseID}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [owners] ▾ <Child> → ▾ <Suspense> <Grandchild> `); // Toggling a Suspense boundary outside of the flat list should exit owners list and update index utils.act(() => dispatch({type: 'SELECT_ELEMENT_BY_ID', payload: outerSuspenseID}), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] ▾ <Parent> → ▾ <Suspense> ▾ <Child> ▾ <Suspense> <Grandchild> `); }); }); describe('inline errors/warnings state', () => { const { clearErrorsAndWarnings: clearErrorsAndWarningsAPI, clearErrorsForElement: clearErrorsForElementAPI, clearWarningsForElement: clearWarningsForElementAPI, } = require('react-devtools-shared/src/backendAPI'); function clearAllErrors() { utils.act(() => clearErrorsAndWarningsAPI({bridge, store})); // flush events to the renderer jest.runAllTimers(); } function clearErrorsForElement(id) { const rendererID = store.getRendererIDForElement(id); utils.act(() => clearErrorsForElementAPI({bridge, id, rendererID})); // flush events to the renderer jest.runAllTimers(); } function clearWarningsForElement(id) { const rendererID = store.getRendererIDForElement(id); utils.act(() => clearWarningsForElementAPI({bridge, id, rendererID})); // flush events to the renderer jest.runAllTimers(); } function selectNextErrorOrWarning() { utils.act(() => dispatch({type: 'SELECT_NEXT_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE'}), ); } function selectPreviousErrorOrWarning() { utils.act(() => dispatch({ type: 'SELECT_PREVIOUS_ELEMENT_WITH_ERROR_OR_WARNING_IN_TREE', }), ); } function Child({logError = false, logWarning = false}) { if (logError === true) { console.error('test-only: error'); } if (logWarning === true) { console.warn('test-only: warning'); } return null; } it('should handle when there are no errors/warnings', () => { utils.act(() => legacyRender( <React.Fragment> <Child /> <Child /> <Child /> </React.Fragment>, document.createElement('div'), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Child> <Child> <Child> `); // Next/previous errors should be a no-op selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` [root] <Child> <Child> <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` [root] <Child> <Child> <Child> `); utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 0})); expect(state).toMatchInlineSnapshot(` [root] → <Child> <Child> <Child> `); // Next/previous errors should still be a no-op selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` [root] → <Child> <Child> <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` [root] → <Child> <Child> <Child> `); }); it('should cycle through the next errors/warnings and wrap around', () => { withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child /> <Child logWarning={true} /> <Child /> <Child logError={true} /> <Child /> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ <Child> <Child> ✕ <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> → <Child> ⚠ <Child> <Child> ✕ <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ <Child> → <Child> ✕ <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> → <Child> ⚠ <Child> <Child> ✕ <Child> `); }); it('should cycle through the previous errors/warnings and wrap around', () => { withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child /> <Child logWarning={true} /> <Child /> <Child logError={true} /> <Child /> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ <Child> <Child> ✕ <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ <Child> → <Child> ✕ <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> → <Child> ⚠ <Child> <Child> ✕ <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ <Child> → <Child> ✕ <Child> `); }); it('should cycle through the next errors/warnings and wrap around with multiple roots', () => { withErrorsOrWarningsIgnored(['test-only:'], () => { utils.act(() => { legacyRender( <React.Fragment> <Child /> <Child logWarning={true} />, </React.Fragment>, document.createElement('div'), ); legacyRender( <React.Fragment> <Child /> <Child logError={true} /> <Child /> </React.Fragment>, document.createElement('div'), ); }); }); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ [root] <Child> <Child> ✕ <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> → <Child> ⚠ [root] <Child> <Child> ✕ <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ [root] <Child> → <Child> ✕ <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> → <Child> ⚠ [root] <Child> <Child> ✕ <Child> `); }); it('should cycle through the previous errors/warnings and wrap around with multiple roots', () => { withErrorsOrWarningsIgnored(['test-only:'], () => { utils.act(() => { legacyRender( <React.Fragment> <Child /> <Child logWarning={true} />, </React.Fragment>, document.createElement('div'), ); legacyRender( <React.Fragment> <Child /> <Child logError={true} /> <Child /> </React.Fragment>, document.createElement('div'), ); }); }); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ [root] <Child> <Child> ✕ <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ [root] <Child> → <Child> ✕ <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> → <Child> ⚠ [root] <Child> <Child> ✕ <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ [root] <Child> → <Child> ✕ <Child> `); }); it('should select the next or previous element relative to the current selection', () => { withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child /> <Child logWarning={true} /> <Child /> <Child logError={true} /> <Child /> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 2})); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ → <Child> <Child> ✕ <Child> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ <Child> → <Child> ✕ <Child> `); utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 2})); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> <Child> ⚠ → <Child> <Child> ✕ <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> → <Child> ⚠ <Child> <Child> ✕ <Child> `); }); it('should update correctly when errors/warnings are cleared for a fiber in the list', () => { withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child logWarning={true} /> <Child logError={true} /> <Child logError={true} /> <Child logWarning={true} /> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Child> ⚠ <Child> ✕ <Child> ✕ <Child> ⚠ `); // Select the first item in the list selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] → <Child> ⚠ <Child> ✕ <Child> ✕ <Child> ⚠ `); // Clear warnings (but the next Fiber has only errors) clearWarningsForElement(store.getElementIDAtIndex(1)); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 2 [root] <Child> ⚠ → <Child> ✕ <Child> ✕ <Child> ⚠ `); clearErrorsForElement(store.getElementIDAtIndex(2)); // Should step to the (now) next one in the list. selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <Child> ⚠ <Child> ✕ <Child> → <Child> ⚠ `); // Should skip over the (now) cleared Fiber selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <Child> ⚠ → <Child> ✕ <Child> <Child> ⚠ `); }); it('should update correctly when errors/warnings are cleared for the currently selected fiber', () => { withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child logWarning={true} /> <Child logError={true} /> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> ⚠ <Child> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] → <Child> ⚠ <Child> ✕ `); clearWarningsForElement(store.getElementIDAtIndex(0)); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] <Child> → <Child> ✕ `); }); it('should update correctly when new errors/warnings are added', () => { const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child logWarning={true} /> <Child /> <Child /> <Child logError={true} /> </React.Fragment>, container, ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> ⚠ <Child> <Child> <Child> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] → <Child> ⚠ <Child> <Child> <Child> ✕ `); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child /> <Child logWarning={true} /> <Child /> <Child /> </React.Fragment>, container, ), ), ); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <Child> ⚠ → <Child> ⚠ <Child> <Child> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] <Child> ⚠ <Child> ⚠ <Child> → <Child> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 2 [root] → <Child> ⚠ <Child> ⚠ <Child> <Child> ✕ `); }); it('should update correctly when all errors/warnings are cleared', () => { withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child logWarning={true} /> <Child logError={true} /> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] <Child> ⚠ <Child> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 1 [root] → <Child> ⚠ <Child> ✕ `); clearAllErrors(); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` [root] → <Child> <Child> `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` [root] → <Child> <Child> `); }); it('should update correctly when elements are added/removed', () => { const container = document.createElement('div'); let errored = false; function ErrorOnce() { if (!errored) { errored = true; console.error('test-only:one-time-error'); } return null; } withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <ErrorOnce key="error" /> </React.Fragment>, container, ), ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] <ErrorOnce key="error"> ✕ `); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child /> <ErrorOnce key="error" /> </React.Fragment>, container, ), ), ); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] <Child> <ErrorOnce key="error"> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] <Child> → <ErrorOnce key="error"> ✕ `); }); it('should update correctly when elements are re-ordered', () => { const container = document.createElement('div'); function ErrorOnce() { const didErrorRef = React.useRef(false); if (!didErrorRef.current) { didErrorRef.current = true; console.error('test-only:one-time-error'); } return null; } withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Child key="A" /> <ErrorOnce key="B" /> <Child key="C" /> <ErrorOnce key="D" /> </React.Fragment>, container, ), ), ); let renderer; utils.act(() => (renderer = TestRenderer.create(<Contexts />))); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 0 [root] <Child key="A"> <ErrorOnce key="B"> ✕ <Child key="C"> <ErrorOnce key="D"> ✕ `); // Select a child selectNextErrorOrWarning(); utils.act(() => renderer.update(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 0 [root] <Child key="A"> → <ErrorOnce key="B"> ✕ <Child key="C"> <ErrorOnce key="D"> ✕ `); // Re-order the tree and ensure indices are updated. withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <ErrorOnce key="B" /> <Child key="A" /> <ErrorOnce key="D" /> <Child key="C" /> </React.Fragment>, container, ), ), ); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 0 [root] → <ErrorOnce key="B"> ✕ <Child key="A"> <ErrorOnce key="D"> ✕ <Child key="C"> `); // Select the next child and ensure the index doesn't break. selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 0 [root] <ErrorOnce key="B"> ✕ <Child key="A"> → <ErrorOnce key="D"> ✕ <Child key="C"> `); // Re-order the tree and ensure indices are updated. withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <ErrorOnce key="D" /> <ErrorOnce key="B" /> <Child key="A" /> <Child key="C" /> </React.Fragment>, container, ), ), ); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 0 [root] → <ErrorOnce key="D"> ✕ <ErrorOnce key="B"> ✕ <Child key="A"> <Child key="C"> `); }); it('should update select and auto-expand parts components within hidden parts of the tree', () => { const Wrapper = ({children}) => children; store.collapseNodesByDefault = true; withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Wrapper> <Child logWarning={true} /> </Wrapper> <Wrapper> <Wrapper> <Child logWarning={true} /> </Wrapper> </Wrapper> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▸ <Wrapper> ▸ <Wrapper> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> → <Child> ⚠ ▸ <Wrapper> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> <Child> ⚠ ▾ <Wrapper> ▾ <Wrapper> → <Child> ⚠ `); }); it('should properly handle when components filters are updated', () => { const Wrapper = ({children}) => children; withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Wrapper> <Child logWarning={true} /> </Wrapper> <Wrapper> <Wrapper> <Child logWarning={true} /> </Wrapper> </Wrapper> </React.Fragment>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> <Child> ⚠ ▾ <Wrapper> ▾ <Wrapper> <Child> ⚠ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> → <Child> ⚠ ▾ <Wrapper> ▾ <Wrapper> <Child> ⚠ `); utils.act(() => { store.componentFilters = [utils.createDisplayNameFilter('Wrapper')]; }); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] → <Child> ⚠ <Child> ⚠ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] <Child> ⚠ → <Child> ⚠ `); utils.act(() => { store.componentFilters = []; }); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> <Child> ⚠ ▾ <Wrapper> ▾ <Wrapper> → <Child> ⚠ `); selectPreviousErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> → <Child> ⚠ ▾ <Wrapper> ▾ <Wrapper> <Child> ⚠ `); }); it('should preserve errors for fibers even if they are filtered out of the tree initially', () => { const Wrapper = ({children}) => children; withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Fragment> <Wrapper> <Child logWarning={true} /> </Wrapper> <Wrapper> <Wrapper> <Child logWarning={true} /> </Wrapper> </Wrapper> </React.Fragment>, document.createElement('div'), ), ), ); store.componentFilters = [utils.createDisplayNameFilter('Child')]; utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Wrapper> ▾ <Wrapper> <Wrapper> `); utils.act(() => { store.componentFilters = []; }); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> <Child> ⚠ ▾ <Wrapper> ▾ <Wrapper> <Child> ⚠ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 2 [root] ▾ <Wrapper> → <Child> ⚠ ▾ <Wrapper> ▾ <Wrapper> <Child> ⚠ `); }); describe('suspense', () => { // This verifies that we don't flush before the tree has been committed. it('should properly handle errors/warnings from components inside of delayed Suspense', async () => { const NeverResolves = React.lazy(() => new Promise(() => {})); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Suspense fallback={null}> <Child logWarning={true} /> <NeverResolves /> </React.Suspense>, document.createElement('div'), ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); jest.runAllTimers(); expect(state).toMatchInlineSnapshot(` [root] <Suspense> `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` [root] <Suspense> `); }); it('should properly handle errors/warnings from components that dont mount because of Suspense', async () => { async function fakeImport(result) { return {default: result}; } const LazyComponent = React.lazy(() => fakeImport(Child)); const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Suspense fallback={null}> <Child logWarning={true} /> <LazyComponent /> </React.Suspense>, container, ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` [root] <Suspense> `); await Promise.resolve(); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Suspense fallback={null}> <Child logWarning={true} /> <LazyComponent /> </React.Suspense>, container, ), ), ); expect(state).toMatchInlineSnapshot(` ✕ 0, ⚠ 1 [root] ▾ <Suspense> <Child> ⚠ <Child> `); }); it('should properly show errors/warnings from components in the Suspense fallback tree', async () => { async function fakeImport(result) { return {default: result}; } const LazyComponent = React.lazy(() => fakeImport(Child)); const Fallback = () => <Child logError={true} />; const container = document.createElement('div'); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Suspense fallback={<Fallback />}> <LazyComponent /> </React.Suspense>, container, ), ), ); utils.act(() => TestRenderer.create(<Contexts />)); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] ▾ <Suspense> ▾ <Fallback> <Child> ✕ `); await Promise.resolve(); withErrorsOrWarningsIgnored(['test-only:'], () => utils.act(() => legacyRender( <React.Suspense fallback={<Fallback />}> <LazyComponent /> </React.Suspense>, container, ), ), ); expect(state).toMatchInlineSnapshot(` [root] ▾ <Suspense> <Child> `); }); }); describe('error boundaries', () => { it('should properly handle errors/warnings from components that dont mount because of an error', () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return null; } return this.props.children; } } class BadRender extends React.Component { render() { console.error('test-only: I am about to throw!'); throw new Error('test-only: Oops!'); } } const container = document.createElement('div'); withErrorsOrWarningsIgnored( ['test-only:', 'React will try to recreate this component tree'], () => { utils.act(() => legacyRender( <ErrorBoundary> <BadRender /> </ErrorBoundary>, container, ), ); }, ); utils.act(() => TestRenderer.create(<Contexts />)); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] <ErrorBoundary> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] → <ErrorBoundary> ✕ `); utils.act(() => ReactDOM.unmountComponentAtNode(container)); expect(state).toMatchInlineSnapshot(``); // Should be a noop selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(``); }); it('should properly handle errors/warnings from components that dont mount because of an error', () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return null; } return this.props.children; } } class LogsWarning extends React.Component { render() { console.warn('test-only: I am about to throw!'); return <ThrowsError />; } } class ThrowsError extends React.Component { render() { throw new Error('test-only: Oops!'); } } const container = document.createElement('div'); withErrorsOrWarningsIgnored( ['test-only:', 'React will try to recreate this component tree'], () => { utils.act(() => legacyRender( <ErrorBoundary> <LogsWarning /> </ErrorBoundary>, container, ), ); }, ); utils.act(() => TestRenderer.create(<Contexts />)); expect(store).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] <ErrorBoundary> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 1, ⚠ 0 [root] → <ErrorBoundary> ✕ `); utils.act(() => ReactDOM.unmountComponentAtNode(container)); expect(state).toMatchInlineSnapshot(``); // Should be a noop selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(``); }); it('should properly handle errors/warnings from inside of an error boundary', () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <Child logError={true} />; } return this.props.children; } } class BadRender extends React.Component { render() { console.error('test-only: I am about to throw!'); throw new Error('test-only: Oops!'); } } const container = document.createElement('div'); withErrorsOrWarningsIgnored( ['test-only:', 'React will try to recreate this component tree'], () => { utils.act(() => legacyRender( <ErrorBoundary> <BadRender /> </ErrorBoundary>, container, ), ); }, ); utils.act(() => TestRenderer.create(<Contexts />)); expect(store).toMatchInlineSnapshot(` ✕ 2, ⚠ 0 [root] ▾ <ErrorBoundary> ✕ <Child> ✕ `); selectNextErrorOrWarning(); expect(state).toMatchInlineSnapshot(` ✕ 2, ⚠ 0 [root] → ▾ <ErrorBoundary> ✕ <Child> ✕ `); }); }); }); });
26.394624
116
0.454206
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } // ?sourceMappingURL=([^\s'"]+)/gm function Component() { const [count, setCount] = (0, _react.useState)(0); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 18, columnNumber: 5 } }, /*#__PURE__*/_react.default.createElement("p", { __source: { fileName: _jsxFileName, lineNumber: 19, columnNumber: 7 } }, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", { onClick: () => setCount(count + 1), __source: { fileName: _jsxFileName, lineNumber: 20, columnNumber: 7 } }, "Click me")); } //# sourceMappingURL=ContainingStringSourceMappingURL.js.map?foo=bar&param=some_value
45.975
743
0.651225
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-client/src/ReactFlightClientConfigNode'; export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigBundlerNode'; export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigTargetTurbopackServer'; export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export const usedWithSSR = true;
35.666667
92
0.779599
cybersecurity-penetration-testing
/** * 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 { PostponedState, ErrorInfo, PostponeInfo, } from 'react-server/src/ReactFizzServer'; import type {ReactNodeList, ReactFormState} from 'shared/ReactTypes'; import type { BootstrapScriptDescriptor, HeadersDescriptor, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; import type {ImportMap} from '../shared/ReactDOMTypes'; import ReactVersion from 'shared/ReactVersion'; import { createRequest, resumeRequest, startWork, startFlowing, stopFlowing, abort, } from 'react-server/src/ReactFizzServer'; import { createResumableState, createRenderState, resumeRenderState, createRootFormatContext, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; type Options = { identifierPrefix?: string, namespaceURI?: string, nonce?: string, bootstrapScriptContent?: string, bootstrapScripts?: Array<string | BootstrapScriptDescriptor>, bootstrapModules?: Array<string | BootstrapScriptDescriptor>, progressiveChunkSize?: number, signal?: AbortSignal, onError?: (error: mixed, errorInfo: ErrorInfo) => ?string, onPostpone?: (reason: string, postponeInfo: PostponeInfo) => void, unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor, importMap?: ImportMap, formState?: ReactFormState<any, any> | null, onHeaders?: (headers: Headers) => void, maxHeadersLength?: number, }; type ResumeOptions = { nonce?: string, signal?: AbortSignal, onError?: (error: mixed) => ?string, onPostpone?: (reason: string) => void, unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor, }; // TODO: Move to sub-classing ReadableStream. type ReactDOMServerReadableStream = ReadableStream & { allReady: Promise<void>, }; function renderToReadableStream( children: ReactNodeList, options?: Options, ): Promise<ReactDOMServerReadableStream> { return new Promise((resolve, reject) => { let onFatalError; let onAllReady; const allReady = new Promise<void>((res, rej) => { onAllReady = res; onFatalError = rej; }); function onShellReady() { const stream: ReactDOMServerReadableStream = (new ReadableStream( { type: 'bytes', pull: (controller): ?Promise<void> => { startFlowing(request, controller); }, cancel: (reason): ?Promise<void> => { stopFlowing(request); abort(request, reason); }, }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. {highWaterMark: 0}, ): any); // TODO: Move to sub-classing ReadableStream. stream.allReady = allReady; resolve(stream); } function onShellError(error: mixed) { // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`. // However, `allReady` will be rejected by `onFatalError` as well. // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`. allReady.catch(() => {}); reject(error); } const onHeaders = options ? options.onHeaders : undefined; let onHeadersImpl; if (onHeaders) { onHeadersImpl = (headersDescriptor: HeadersDescriptor) => { onHeaders(new Headers(headersDescriptor)); }; } const resumableState = createResumableState( options ? options.identifierPrefix : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined, ); const request = createRequest( children, resumableState, createRenderState( resumableState, options ? options.nonce : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.importMap : undefined, onHeadersImpl, options ? options.maxHeadersLength : undefined, ), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError, options ? options.onPostpone : undefined, options ? options.formState : undefined, ); if (options && options.signal) { const signal = options.signal; if (signal.aborted) { abort(request, (signal: any).reason); } else { const listener = () => { abort(request, (signal: any).reason); signal.removeEventListener('abort', listener); }; signal.addEventListener('abort', listener); } } startWork(request); }); } function resume( children: ReactNodeList, postponedState: PostponedState, options?: ResumeOptions, ): Promise<ReactDOMServerReadableStream> { return new Promise((resolve, reject) => { let onFatalError; let onAllReady; const allReady = new Promise<void>((res, rej) => { onAllReady = res; onFatalError = rej; }); function onShellReady() { const stream: ReactDOMServerReadableStream = (new ReadableStream( { type: 'bytes', pull: (controller): ?Promise<void> => { startFlowing(request, controller); }, cancel: (reason): ?Promise<void> => { stopFlowing(request); abort(request, reason); }, }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. {highWaterMark: 0}, ): any); // TODO: Move to sub-classing ReadableStream. stream.allReady = allReady; resolve(stream); } function onShellError(error: mixed) { // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`. // However, `allReady` will be rejected by `onFatalError` as well. // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`. allReady.catch(() => {}); reject(error); } const request = resumeRequest( children, postponedState, resumeRenderState( postponedState.resumableState, options ? options.nonce : undefined, ), options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError, options ? options.onPostpone : undefined, ); if (options && options.signal) { const signal = options.signal; if (signal.aborted) { abort(request, (signal: any).reason); } else { const listener = () => { abort(request, (signal: any).reason); signal.removeEventListener('abort', listener); }; signal.addEventListener('abort', listener); } } startWork(request); }); } export {renderToReadableStream, resume, ReactVersion as version};
30.099138
123
0.653313
cybersecurity-penetration-testing
/** * 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. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ /* eslint-disable no-func-assign */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; let useState; let useReducer; let useEffect; let useContext; let useCallback; let useMemo; let useRef; let useImperativeHandle; let useInsertionEffect; let useLayoutEffect; let useDebugValue; let forwardRef; let yieldedValues; let yieldValue; let clearLog; function initModules() { // Reset warning cache. jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); useState = React.useState; useReducer = React.useReducer; useEffect = React.useEffect; useContext = React.useContext; useCallback = React.useCallback; useMemo = React.useMemo; useRef = React.useRef; useDebugValue = React.useDebugValue; useImperativeHandle = React.useImperativeHandle; useInsertionEffect = React.useInsertionEffect; useLayoutEffect = React.useLayoutEffect; forwardRef = React.forwardRef; yieldedValues = []; yieldValue = value => { yieldedValues.push(value); }; clearLog = () => { const ret = yieldedValues; yieldedValues = []; return ret; }; // Make them available to the helpers. return { ReactDOM, ReactDOMServer, ReactTestUtils, }; } const {resetModules, itRenders, itThrowsWhenRendering, serverRender} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerHooks', () => { beforeEach(() => { resetModules(); }); function Text(props) { yieldValue(props.text); return <span>{props.text}</span>; } describe('useState', () => { itRenders('basic render', async render => { function Counter(props) { const [count] = useState(0); return <span>Count: {count}</span>; } const domNode = await render(<Counter />); expect(domNode.textContent).toEqual('Count: 0'); }); itRenders('lazy state initialization', async render => { function Counter(props) { const [count] = useState(() => { return 0; }); return <span>Count: {count}</span>; } const domNode = await render(<Counter />); expect(domNode.textContent).toEqual('Count: 0'); }); it('does not trigger a re-renders when updater is invoked outside current render function', async () => { function UpdateCount({setCount, count, children}) { if (count < 3) { setCount(c => c + 1); } return <span>{children}</span>; } function Counter() { const [count, setCount] = useState(0); return ( <div> <UpdateCount setCount={setCount} count={count}> Count: {count} </UpdateCount> </div> ); } const domNode = await serverRender(<Counter />); expect(domNode.textContent).toEqual('Count: 0'); }); itThrowsWhenRendering( 'if used inside a class component', async render => { class Counter extends React.Component { render() { const [count] = useState(0); return <Text text={count} />; } } return render(<Counter />); }, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.', ); itRenders('multiple times when an updater is called', async render => { function Counter() { const [count, setCount] = useState(0); if (count < 12) { setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); } return <Text text={'Count: ' + count} />; } const domNode = await render(<Counter />); expect(domNode.textContent).toEqual('Count: 12'); }); itRenders('until there are no more new updates', async render => { function Counter() { const [count, setCount] = useState(0); if (count < 3) { setCount(count + 1); } return <span>Count: {count}</span>; } const domNode = await render(<Counter />); expect(domNode.textContent).toEqual('Count: 3'); }); itThrowsWhenRendering( 'after too many iterations', async render => { function Counter() { const [count, setCount] = useState(0); setCount(count + 1); return <span>{count}</span>; } return render(<Counter />); }, 'Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.', ); }); describe('useReducer', () => { itRenders('with initial state', async render => { function reducer(state, action) { return action === 'increment' ? state + 1 : state; } function Counter() { const [count] = useReducer(reducer, 0); yieldValue('Render: ' + count); return <Text text={count} />; } const domNode = await render(<Counter />); expect(clearLog()).toEqual(['Render: 0', 0]); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('0'); }); itRenders('lazy initialization', async render => { function reducer(state, action) { return action === 'increment' ? state + 1 : state; } function Counter() { const [count] = useReducer(reducer, 0, c => c + 1); yieldValue('Render: ' + count); return <Text text={count} />; } const domNode = await render(<Counter />); expect(clearLog()).toEqual(['Render: 1', 1]); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('1'); }); itRenders( 'multiple times when updates happen during the render phase', async render => { function reducer(state, action) { return action === 'increment' ? state + 1 : state; } function Counter() { const [count, dispatch] = useReducer(reducer, 0); if (count < 3) { dispatch('increment'); } yieldValue('Render: ' + count); return <Text text={count} />; } const domNode = await render(<Counter />); expect(clearLog()).toEqual([ 'Render: 0', 'Render: 1', 'Render: 2', 'Render: 3', 3, ]); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('3'); }, ); itRenders( 'using reducer passed at time of render, not time of dispatch', async render => { // This test is a bit contrived but it demonstrates a subtle edge case. // Reducer A increments by 1. Reducer B increments by 10. function reducerA(state, action) { switch (action) { case 'increment': return state + 1; case 'reset': return 0; } } function reducerB(state, action) { switch (action) { case 'increment': return state + 10; case 'reset': return 0; } } function Counter() { const [reducer, setReducer] = useState(() => reducerA); const [count, dispatch] = useReducer(reducer, 0); if (count < 20) { dispatch('increment'); // Swap reducers each time we increment if (reducer === reducerA) { setReducer(() => reducerB); } else { setReducer(() => reducerA); } } yieldValue('Render: ' + count); return <Text text={count} />; } const domNode = await render(<Counter />); expect(clearLog()).toEqual([ // The count should increase by alternating amounts of 10 and 1 // until we reach 21. 'Render: 0', 'Render: 10', 'Render: 11', 'Render: 21', 21, ]); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('21'); }, ); }); describe('useMemo', () => { itRenders('basic render', async render => { function CapitalizedText(props) { const text = props.text; const capitalizedText = useMemo(() => { yieldValue(`Capitalize '${text}'`); return text.toUpperCase(); }, [text]); return <Text text={capitalizedText} />; } const domNode = await render(<CapitalizedText text="hello" />); expect(clearLog()).toEqual(["Capitalize 'hello'", 'HELLO']); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('HELLO'); }); itRenders('if no inputs are provided', async render => { function LazyCompute(props) { const computed = useMemo(props.compute); return <Text text={computed} />; } function computeA() { yieldValue('compute A'); return 'A'; } const domNode = await render(<LazyCompute compute={computeA} />); expect(clearLog()).toEqual(['compute A', 'A']); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('A'); }); itRenders( 'multiple times when updates happen during the render phase', async render => { function CapitalizedText(props) { const [text, setText] = useState(props.text); const capitalizedText = useMemo(() => { yieldValue(`Capitalize '${text}'`); return text.toUpperCase(); }, [text]); if (text === 'hello') { setText('hello, world.'); } return <Text text={capitalizedText} />; } const domNode = await render(<CapitalizedText text="hello" />); expect(clearLog()).toEqual([ "Capitalize 'hello'", "Capitalize 'hello, world.'", 'HELLO, WORLD.', ]); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('HELLO, WORLD.'); }, ); itRenders( 'should only invoke the memoized function when the inputs change', async render => { function CapitalizedText(props) { const [text, setText] = useState(props.text); const [count, setCount] = useState(0); const capitalizedText = useMemo(() => { yieldValue(`Capitalize '${text}'`); return text.toUpperCase(); }, [text]); yieldValue(count); if (count < 3) { setCount(count + 1); } if (text === 'hello' && count === 2) { setText('hello, world.'); } return <Text text={capitalizedText} />; } const domNode = await render(<CapitalizedText text="hello" />); expect(clearLog()).toEqual([ "Capitalize 'hello'", 0, 1, 2, // `capitalizedText` only recomputes when the text has changed "Capitalize 'hello, world.'", 3, 'HELLO, WORLD.', ]); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('HELLO, WORLD.'); }, ); itRenders('with a warning for useState inside useMemo', async render => { function App() { useMemo(() => { useState(); return 0; }); return 'hi'; } const domNode = await render(<App />, 1); expect(domNode.textContent).toEqual('hi'); }); itRenders('with a warning for useRef inside useState', async render => { function App() { const [value] = useState(() => { useRef(0); return 0; }); return value; } const domNode = await render(<App />, 1); expect(domNode.textContent).toEqual('0'); }); }); describe('useRef', () => { itRenders('basic render', async render => { function Counter(props) { const ref = useRef(); return <span ref={ref}>Hi</span>; } const domNode = await render(<Counter />); expect(domNode.textContent).toEqual('Hi'); }); itRenders( 'multiple times when updates happen during the render phase', async render => { function Counter(props) { const [count, setCount] = useState(0); const ref = useRef(); if (count < 3) { const newCount = count + 1; setCount(newCount); } yieldValue(count); return <span ref={ref}>Count: {count}</span>; } const domNode = await render(<Counter />); expect(clearLog()).toEqual([0, 1, 2, 3]); expect(domNode.textContent).toEqual('Count: 3'); }, ); itRenders( 'always return the same reference through multiple renders', async render => { let firstRef = null; function Counter(props) { const [count, setCount] = useState(0); const ref = useRef(); if (firstRef === null) { firstRef = ref; } else if (firstRef !== ref) { throw new Error('should never change'); } if (count < 3) { setCount(count + 1); } else { firstRef = null; } yieldValue(count); return <span ref={ref}>Count: {count}</span>; } const domNode = await render(<Counter />); expect(clearLog()).toEqual([0, 1, 2, 3]); expect(domNode.textContent).toEqual('Count: 3'); }, ); }); describe('useEffect', () => { const yields = []; itRenders('should ignore effects on the server', async render => { function Counter(props) { useEffect(() => { yieldValue('invoked on client'); }); return <Text text={'Count: ' + props.count} />; } const domNode = await render(<Counter count={0} />); yields.push(clearLog()); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('Count: 0'); }); it('verifies yields in order', () => { expect(yields).toEqual([ ['Count: 0'], // server render ['Count: 0'], // server stream ['Count: 0', 'invoked on client'], // clean render ['Count: 0', 'invoked on client'], // hydrated render // nothing yielded for bad markup ]); }); }); describe('useCallback', () => { itRenders('should not invoke the passed callbacks', async render => { function Counter(props) { useCallback(() => { yieldValue('should not be invoked'); }); return <Text text={'Count: ' + props.count} />; } const domNode = await render(<Counter count={0} />); expect(clearLog()).toEqual(['Count: 0']); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('Count: 0'); }); itRenders('should support render time callbacks', async render => { function Counter(props) { const renderCount = useCallback(increment => { return 'Count: ' + (props.count + increment); }); return <Text text={renderCount(3)} />; } const domNode = await render(<Counter count={2} />); expect(clearLog()).toEqual(['Count: 5']); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('Count: 5'); }); itRenders( 'should only change the returned reference when the inputs change', async render => { function CapitalizedText(props) { const [text, setText] = useState(props.text); const [count, setCount] = useState(0); const capitalizeText = useCallback(() => text.toUpperCase(), [text]); yieldValue(capitalizeText); if (count < 3) { setCount(count + 1); } if (text === 'hello' && count === 2) { setText('hello, world.'); } return <Text text={capitalizeText()} />; } const domNode = await render(<CapitalizedText text="hello" />); const [first, second, third, fourth, result] = clearLog(); expect(first).toBe(second); expect(second).toBe(third); expect(third).not.toBe(fourth); expect(result).toEqual('HELLO, WORLD.'); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('HELLO, WORLD.'); }, ); }); describe('useImperativeHandle', () => { it('should not be invoked on the server', async () => { function Counter(props, ref) { useImperativeHandle(ref, () => { throw new Error('should not be invoked'); }); return <Text text={props.label + ': ' + ref.current} />; } Counter = forwardRef(Counter); const counter = React.createRef(); counter.current = 0; const domNode = await serverRender( <Counter label="Count" ref={counter} />, ); expect(clearLog()).toEqual(['Count: 0']); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('Count: 0'); }); }); describe('useInsertionEffect', () => { it('should warn when invoked during render', async () => { function Counter() { useInsertionEffect(() => { throw new Error('should not be invoked'); }); return <Text text="Count: 0" />; } const domNode = await serverRender(<Counter />, 1); expect(clearLog()).toEqual(['Count: 0']); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('Count: 0'); }); }); describe('useLayoutEffect', () => { it('should warn when invoked during render', async () => { function Counter() { useLayoutEffect(() => { throw new Error('should not be invoked'); }); return <Text text="Count: 0" />; } const domNode = await serverRender(<Counter />, 1); expect(clearLog()).toEqual(['Count: 0']); expect(domNode.tagName).toEqual('SPAN'); expect(domNode.textContent).toEqual('Count: 0'); }); }); describe('useContext', () => { itThrowsWhenRendering( 'if used inside a class component', async render => { const Context = React.createContext({}, () => {}); class Counter extends React.Component { render() { const [count] = useContext(Context); return <Text text={count} />; } } return render(<Counter />); }, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.', ); }); describe('invalid hooks', () => { it('warns when calling useRef inside useReducer', async () => { function App() { const [value, dispatch] = useReducer((state, action) => { useRef(0); return state + 1; }, 0); if (value === 0) { dispatch(); } return value; } let error; try { await serverRender(<App />); } catch (x) { error = x; } expect(error).not.toBe(undefined); expect(error.message).toContain( 'Rendered more hooks than during the previous render', ); }); }); itRenders( 'can use the same context multiple times in the same function', async render => { const Context = React.createContext({foo: 0, bar: 0, baz: 0}); function Provider(props) { return ( <Context.Provider value={{foo: props.foo, bar: props.bar, baz: props.baz}}> {props.children} </Context.Provider> ); } function FooAndBar() { const {foo} = useContext(Context); const {bar} = useContext(Context); return <Text text={`Foo: ${foo}, Bar: ${bar}`} />; } function Baz() { const {baz} = useContext(Context); return <Text text={'Baz: ' + baz} />; } class Indirection extends React.Component { render() { return this.props.children; } } function App(props) { return ( <div> <Provider foo={props.foo} bar={props.bar} baz={props.baz}> <Indirection> <Indirection> <FooAndBar /> </Indirection> <Indirection> <Baz /> </Indirection> </Indirection> </Provider> </div> ); } const domNode = await render(<App foo={1} bar={3} baz={5} />); expect(clearLog()).toEqual(['Foo: 1, Bar: 3', 'Baz: 5']); expect(domNode.childNodes.length).toBe(2); expect(domNode.firstChild.tagName).toEqual('SPAN'); expect(domNode.firstChild.textContent).toEqual('Foo: 1, Bar: 3'); expect(domNode.lastChild.tagName).toEqual('SPAN'); expect(domNode.lastChild.textContent).toEqual('Baz: 5'); }, ); describe('useDebugValue', () => { itRenders('is a noop', async render => { function Counter(props) { const debugValue = useDebugValue(123); return <Text text={typeof debugValue} />; } const domNode = await render(<Counter />); expect(domNode.textContent).toEqual('undefined'); }); }); describe('readContext', () => { function readContext(Context) { const dispatcher = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .ReactCurrentDispatcher.current; return dispatcher.readContext(Context); } itRenders( 'can read the same context multiple times in the same function', async render => { const Context = React.createContext( {foo: 0, bar: 0, baz: 0}, (a, b) => { let result = 0; if (a.foo !== b.foo) { result |= 0b001; } if (a.bar !== b.bar) { result |= 0b010; } if (a.baz !== b.baz) { result |= 0b100; } return result; }, ); function Provider(props) { return ( <Context.Provider value={{foo: props.foo, bar: props.bar, baz: props.baz}}> {props.children} </Context.Provider> ); } function FooAndBar() { const {foo} = readContext(Context, 0b001); const {bar} = readContext(Context, 0b010); return <Text text={`Foo: ${foo}, Bar: ${bar}`} />; } function Baz() { const {baz} = readContext(Context, 0b100); return <Text text={'Baz: ' + baz} />; } class Indirection extends React.Component { shouldComponentUpdate() { return false; } render() { return this.props.children; } } function App(props) { return ( <div> <Provider foo={props.foo} bar={props.bar} baz={props.baz}> <Indirection> <Indirection> <FooAndBar /> </Indirection> <Indirection> <Baz /> </Indirection> </Indirection> </Provider> </div> ); } const domNode = await render(<App foo={1} bar={3} baz={5} />); expect(clearLog()).toEqual(['Foo: 1, Bar: 3', 'Baz: 5']); expect(domNode.childNodes.length).toBe(2); expect(domNode.firstChild.tagName).toEqual('SPAN'); expect(domNode.firstChild.textContent).toEqual('Foo: 1, Bar: 3'); expect(domNode.lastChild.tagName).toEqual('SPAN'); expect(domNode.lastChild.textContent).toEqual('Baz: 5'); }, ); itRenders('with a warning inside useMemo and useReducer', async render => { const Context = React.createContext(42); function ReadInMemo(props) { const count = React.useMemo(() => readContext(Context), []); return <Text text={count} />; } function ReadInReducer(props) { const [count, dispatch] = React.useReducer(() => readContext(Context)); if (count !== 42) { dispatch(); } return <Text text={count} />; } const domNode1 = await render(<ReadInMemo />, 1); expect(domNode1.textContent).toEqual('42'); const domNode2 = await render(<ReadInReducer />, 1); expect(domNode2.textContent).toEqual('42'); }); }); it('renders successfully after a component using hooks throws an error', () => { function ThrowingComponent() { const [value, dispatch] = useReducer((state, action) => { return state + 1; }, 0); // throw an error if the count gets too high during the re-render phase if (value >= 3) { throw new Error('Error from ThrowingComponent'); } else { // dispatch to trigger a re-render of the component dispatch(); } return <div>{value}</div>; } function NonThrowingComponent() { const [count] = useState(0); return <div>{count}</div>; } // First, render a component that will throw an error during a re-render triggered // by a dispatch call. expect(() => ReactDOMServer.renderToString(<ThrowingComponent />)).toThrow( 'Error from ThrowingComponent', ); // Next, assert that we can render a function component using hooks immediately // after an error occurred, which indictates the internal hooks state has been // reset. const container = document.createElement('div'); container.innerHTML = ReactDOMServer.renderToString( <NonThrowingComponent />, ); expect(container.children[0].textContent).toEqual('0'); }); });
28.920705
119
0.54765
Penetration-Testing-Study-Notes
/** * 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. */ 'use strict'; import RulesOfHooks from './RulesOfHooks'; import ExhaustiveDeps from './ExhaustiveDeps'; export const configs = { recommended: { plugins: ['react-hooks'], rules: { 'react-hooks/rules-of-hooks': 'error', 'react-hooks/exhaustive-deps': 'warn', }, }, }; export const rules = { 'rules-of-hooks': RulesOfHooks, 'exhaustive-deps': ExhaustiveDeps, };
20.740741
66
0.667235
cybersecurity-penetration-testing
/** * 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 {ReactContext, RefObject} from 'shared/ReactTypes'; import * as React from 'react'; import { createContext, useContext, useMemo, useRef, useState, useSyncExternalStore, } from 'react'; import {StoreContext} from 'react-devtools-shared/src/devtools/views/context'; import type { HorizontalScrollStateChangeCallback, TimelineData, SearchRegExpStateChangeCallback, ViewState, ReactEventInfo, } from './types'; export type Context = { file: File | null, inMemoryTimelineData: Array<TimelineData> | null, isTimelineSupported: boolean, searchInputContainerRef: RefObject, setFile: (file: File | null) => void, viewState: ViewState, selectEvent: ReactEventInfo => void, selectedEvent: ReactEventInfo, }; const TimelineContext: ReactContext<Context> = createContext<Context>( ((null: any): Context), ); TimelineContext.displayName = 'TimelineContext'; type Props = { children: React$Node, }; function TimelineContextController({children}: Props): React.Node { const searchInputContainerRef = useRef(null); const [file, setFile] = useState<string | null>(null); const store = useContext(StoreContext); const isTimelineSupported = useSyncExternalStore<boolean>( function subscribe(callback) { store.addListener('rootSupportsTimelineProfiling', callback); return function unsubscribe() { store.removeListener('rootSupportsTimelineProfiling', callback); }; }, function getState() { return store.rootSupportsTimelineProfiling; }, ); const inMemoryTimelineData = useSyncExternalStore<Array<TimelineData> | null>( function subscribe(callback) { store.profilerStore.addListener('isProcessingData', callback); store.profilerStore.addListener('profilingData', callback); return function unsubscribe() { store.profilerStore.removeListener('isProcessingData', callback); store.profilerStore.removeListener('profilingData', callback); }; }, function getState() { return store.profilerStore.profilingData?.timelineData || null; }, ); // Recreate view state any time new profiling data is imported. const viewState = useMemo<ViewState>(() => { const horizontalScrollStateChangeCallbacks: Set<HorizontalScrollStateChangeCallback> = new Set(); const searchRegExpStateChangeCallbacks: Set<SearchRegExpStateChangeCallback> = new Set(); const horizontalScrollState = { offset: 0, length: 0, }; const state: ViewState = { horizontalScrollState, onHorizontalScrollStateChange: callback => { horizontalScrollStateChangeCallbacks.add(callback); }, onSearchRegExpStateChange: callback => { searchRegExpStateChangeCallbacks.add(callback); }, searchRegExp: null, updateHorizontalScrollState: scrollState => { if ( horizontalScrollState.offset === scrollState.offset && horizontalScrollState.length === scrollState.length ) { return; } horizontalScrollState.offset = scrollState.offset; horizontalScrollState.length = scrollState.length; horizontalScrollStateChangeCallbacks.forEach(callback => { callback(scrollState); }); }, updateSearchRegExpState: (searchRegExp: RegExp | null) => { state.searchRegExp = searchRegExp; searchRegExpStateChangeCallbacks.forEach(callback => { callback(searchRegExp); }); }, viewToMutableViewStateMap: new Map(), }; return state; }, [file]); const [selectedEvent, selectEvent] = useState<ReactEventInfo | null>(null); const value = useMemo( () => ({ file, inMemoryTimelineData, isTimelineSupported, searchInputContainerRef, setFile, viewState, selectEvent, selectedEvent, }), [ file, inMemoryTimelineData, isTimelineSupported, setFile, viewState, selectEvent, selectedEvent, ], ); return ( <TimelineContext.Provider value={value}> {children} </TimelineContext.Provider> ); } export {TimelineContext, TimelineContextController};
26
90
0.683307
null
/** * 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 {Fiber, FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import type { PublicInstance, Instance, TextInstance, } from './ReactFiberConfigTestHost'; import * as React from 'react'; import * as Scheduler from 'scheduler/unstable_mock'; import { getPublicRootInstance, createContainer, updateContainer, flushSync, injectIntoDevTools, batchedUpdates, } from 'react-reconciler/src/ReactFiberReconciler'; import {findCurrentFiberUsingSlowPath} from 'react-reconciler/src/ReactFiberTreeReflection'; import { Fragment, FunctionComponent, ClassComponent, HostComponent, HostHoistable, HostSingleton, HostPortal, HostText, HostRoot, ContextConsumer, ContextProvider, Mode, ForwardRef, Profiler, MemoComponent, SimpleMemoComponent, IncompleteClassComponent, ScopeComponent, } from 'react-reconciler/src/ReactWorkTags'; import isArray from 'shared/isArray'; import getComponentNameFromType from 'shared/getComponentNameFromType'; import ReactVersion from 'shared/ReactVersion'; import {checkPropStringCoercion} from 'shared/CheckStringCoercion'; import {getPublicInstance} from './ReactFiberConfigTestHost'; import {ConcurrentRoot, LegacyRoot} from 'react-reconciler/src/ReactRootTags'; import {allowConcurrentByDefault} from 'shared/ReactFeatureFlags'; const act = React.unstable_act; // TODO: Remove from public bundle type TestRendererOptions = { createNodeMock: (element: React$Element<any>) => any, isConcurrent: boolean, unstable_isConcurrent: boolean, unstable_strictMode: boolean, unstable_concurrentUpdatesByDefault: boolean, ... }; type ReactTestRendererJSON = { type: string, props: {[propName: string]: any, ...}, children: null | Array<ReactTestRendererNode>, $$typeof?: symbol, // Optional because we add it with defineProperty(). }; type ReactTestRendererNode = ReactTestRendererJSON | string; type FindOptions = { // performs a "greedy" search: if a matching node is found, will continue // to search within the matching node's children. (default: true) deep?: boolean, }; export type Predicate = (node: ReactTestInstance) => ?boolean; const defaultTestOptions = { createNodeMock: function () { return null; }, }; function toJSON(inst: Instance | TextInstance): ReactTestRendererNode | null { if (inst.isHidden) { // Omit timed out children from output entirely. This seems like the least // surprising behavior. We could perhaps add a separate API that includes // them, if it turns out people need it. return null; } switch (inst.tag) { case 'TEXT': return inst.text; case 'INSTANCE': { /* eslint-disable no-unused-vars */ // We don't include the `children` prop in JSON. // Instead, we will include the actual rendered children. const {children, ...props} = inst.props; /* eslint-enable */ let renderedChildren = null; if (inst.children && inst.children.length) { for (let i = 0; i < inst.children.length; i++) { const renderedChild = toJSON(inst.children[i]); if (renderedChild !== null) { if (renderedChildren === null) { renderedChildren = [renderedChild]; } else { renderedChildren.push(renderedChild); } } } } const json: ReactTestRendererJSON = { type: inst.type, props: props, children: renderedChildren, }; Object.defineProperty(json, '$$typeof', { value: Symbol.for('react.test.json'), }); return json; } default: throw new Error(`Unexpected node type in toJSON: ${inst.tag}`); } } function childrenToTree(node: null | Fiber) { if (!node) { return null; } const children = nodeAndSiblingsArray(node); if (children.length === 0) { return null; } else if (children.length === 1) { return toTree(children[0]); } return flatten(children.map(toTree)); } // $FlowFixMe[missing-local-annot] function nodeAndSiblingsArray(nodeWithSibling) { const array = []; let node = nodeWithSibling; while (node != null) { array.push(node); node = node.sibling; } return array; } // $FlowFixMe[missing-local-annot] function flatten(arr) { const result = []; const stack = [{i: 0, array: arr}]; while (stack.length) { const n = stack.pop(); while (n.i < n.array.length) { const el = n.array[n.i]; n.i += 1; if (isArray(el)) { stack.push(n); stack.push({i: 0, array: el}); break; } result.push(el); } } return result; } function toTree(node: null | Fiber): $FlowFixMe { if (node == null) { return null; } switch (node.tag) { case HostRoot: return childrenToTree(node.child); case HostPortal: return childrenToTree(node.child); case ClassComponent: return { nodeType: 'component', type: node.type, props: {...node.memoizedProps}, instance: node.stateNode, rendered: childrenToTree(node.child), }; case FunctionComponent: case SimpleMemoComponent: return { nodeType: 'component', type: node.type, props: {...node.memoizedProps}, instance: null, rendered: childrenToTree(node.child), }; case HostHoistable: case HostSingleton: case HostComponent: { return { nodeType: 'host', type: node.type, props: {...node.memoizedProps}, instance: null, // TODO: use createNodeMock here somehow? rendered: flatten(nodeAndSiblingsArray(node.child).map(toTree)), }; } case HostText: return node.stateNode.text; case Fragment: case ContextProvider: case ContextConsumer: case Mode: case Profiler: case ForwardRef: case MemoComponent: case IncompleteClassComponent: case ScopeComponent: return childrenToTree(node.child); default: throw new Error( `toTree() does not yet know how to handle nodes with tag=${node.tag}`, ); } } const validWrapperTypes = new Set([ FunctionComponent, ClassComponent, HostComponent, ForwardRef, MemoComponent, SimpleMemoComponent, // Normally skipped, but used when there's more than one root child. HostRoot, ]); function getChildren(parent: Fiber) { const children = []; const startingNode = parent; let node: Fiber = startingNode; if (node.child === null) { return children; } node.child.return = node; node = node.child; outer: while (true) { let descend = false; if (validWrapperTypes.has(node.tag)) { children.push(wrapFiber(node)); } else if (node.tag === HostText) { if (__DEV__) { checkPropStringCoercion(node.memoizedProps, 'memoizedProps'); } children.push('' + node.memoizedProps); } else { descend = true; } if (descend && node.child !== null) { node.child.return = node; node = node.child; continue; } while (node.sibling === null) { if (node.return === startingNode) { break outer; } node = (node.return: any); } (node.sibling: any).return = node.return; node = (node.sibling: any); } return children; } class ReactTestInstance { _fiber: Fiber; _currentFiber(): Fiber { // Throws if this component has been unmounted. const fiber = findCurrentFiberUsingSlowPath(this._fiber); if (fiber === null) { throw new Error( "Can't read from currently-mounting component. This error is likely " + 'caused by a bug in React. Please file an issue.', ); } return fiber; } constructor(fiber: Fiber) { if (!validWrapperTypes.has(fiber.tag)) { throw new Error( `Unexpected object passed to ReactTestInstance constructor (tag: ${fiber.tag}). ` + 'This is probably a bug in React.', ); } this._fiber = fiber; } get instance(): $FlowFixMe { const tag = this._fiber.tag; if ( tag === HostComponent || tag === HostHoistable || tag === HostSingleton ) { return getPublicInstance(this._fiber.stateNode); } else { return this._fiber.stateNode; } } get type(): any { return this._fiber.type; } get props(): Object { return this._currentFiber().memoizedProps; } get parent(): ?ReactTestInstance { let parent = this._fiber.return; while (parent !== null) { if (validWrapperTypes.has(parent.tag)) { if (parent.tag === HostRoot) { // Special case: we only "materialize" instances for roots // if they have more than a single child. So we'll check that now. if (getChildren(parent).length < 2) { return null; } } return wrapFiber(parent); } parent = parent.return; } return null; } get children(): Array<ReactTestInstance | string> { return getChildren(this._currentFiber()); } // Custom search functions find(predicate: Predicate): ReactTestInstance { return expectOne( this.findAll(predicate, {deep: false}), `matching custom predicate: ${predicate.toString()}`, ); } findByType(type: any): ReactTestInstance { return expectOne( this.findAllByType(type, {deep: false}), `with node type: "${getComponentNameFromType(type) || 'Unknown'}"`, ); } findByProps(props: Object): ReactTestInstance { return expectOne( this.findAllByProps(props, {deep: false}), `with props: ${JSON.stringify(props)}`, ); } findAll( predicate: Predicate, options: ?FindOptions = null, ): Array<ReactTestInstance> { return findAll(this, predicate, options); } findAllByType( type: any, options: ?FindOptions = null, ): Array<ReactTestInstance> { return findAll(this, node => node.type === type, options); } findAllByProps( props: Object, options: ?FindOptions = null, ): Array<ReactTestInstance> { return findAll( this, node => node.props && propsMatch(node.props, props), options, ); } } function findAll( root: ReactTestInstance, predicate: Predicate, options: ?FindOptions, ): Array<ReactTestInstance> { const deep = options ? options.deep : true; const results = []; if (predicate(root)) { results.push(root); if (!deep) { return results; } } root.children.forEach(child => { if (typeof child === 'string') { return; } results.push(...findAll(child, predicate, options)); }); return results; } function expectOne( all: Array<ReactTestInstance>, message: string, ): ReactTestInstance { if (all.length === 1) { return all[0]; } const prefix = all.length === 0 ? 'No instances found ' : `Expected 1 but found ${all.length} instances `; throw new Error(prefix + message); } function propsMatch(props: Object, filter: Object): boolean { for (const key in filter) { if (props[key] !== filter[key]) { return false; } } return true; } // $FlowFixMe[missing-local-annot] function onRecoverableError(error) { // TODO: Expose onRecoverableError option to userspace // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args console.error(error); } function create( element: React$Element<any>, options: TestRendererOptions, ): { _Scheduler: typeof Scheduler, root: void, toJSON(): Array<ReactTestRendererNode> | ReactTestRendererNode | null, toTree(): mixed, update(newElement: React$Element<any>): any, unmount(): void, getInstance(): React$Component<any, any> | PublicInstance | null, unstable_flushSync: typeof flushSync, } { let createNodeMock = defaultTestOptions.createNodeMock; let isConcurrent = false; let isStrictMode = false; let concurrentUpdatesByDefault = null; if (typeof options === 'object' && options !== null) { if (typeof options.createNodeMock === 'function') { // $FlowFixMe[incompatible-type] found when upgrading Flow createNodeMock = options.createNodeMock; } if ( options.unstable_isConcurrent === true || options.isConcurrent === true ) { isConcurrent = true; } if (options.unstable_strictMode === true) { isStrictMode = true; } if (allowConcurrentByDefault) { if (options.unstable_concurrentUpdatesByDefault !== undefined) { concurrentUpdatesByDefault = options.unstable_concurrentUpdatesByDefault; } } } let container = { children: ([]: Array<Instance | TextInstance>), createNodeMock, tag: 'CONTAINER', }; let root: FiberRoot | null = createContainer( container, isConcurrent ? ConcurrentRoot : LegacyRoot, null, isStrictMode, concurrentUpdatesByDefault, '', onRecoverableError, null, ); if (root == null) { throw new Error('something went wrong'); } updateContainer(element, root, null, null); const entry = { _Scheduler: Scheduler, root: undefined, // makes flow happy // we define a 'getter' for 'root' below using 'Object.defineProperty' toJSON(): Array<ReactTestRendererNode> | ReactTestRendererNode | null { if (root == null || root.current == null || container == null) { return null; } if (container.children.length === 0) { return null; } if (container.children.length === 1) { return toJSON(container.children[0]); } if ( container.children.length === 2 && container.children[0].isHidden === true && container.children[1].isHidden === false ) { // Omit timed out children from output entirely, including the fact that we // temporarily wrap fallback and timed out children in an array. return toJSON(container.children[1]); } let renderedChildren = null; if (container.children && container.children.length) { for (let i = 0; i < container.children.length; i++) { const renderedChild = toJSON(container.children[i]); if (renderedChild !== null) { if (renderedChildren === null) { renderedChildren = [renderedChild]; } else { renderedChildren.push(renderedChild); } } } } return renderedChildren; }, toTree() { if (root == null || root.current == null) { return null; } return toTree(root.current); }, update(newElement: React$Element<any>): number | void { if (root == null || root.current == null) { return; } updateContainer(newElement, root, null, null); }, unmount() { if (root == null || root.current == null) { return; } updateContainer(null, root, null, null); // $FlowFixMe[incompatible-type] found when upgrading Flow container = null; root = null; }, getInstance() { if (root == null || root.current == null) { return null; } return getPublicRootInstance(root); }, unstable_flushSync: flushSync, }; Object.defineProperty( entry, 'root', ({ configurable: true, enumerable: true, get: function () { if (root === null) { throw new Error("Can't access .root on unmounted test renderer"); } const children = getChildren(root.current); if (children.length === 0) { throw new Error("Can't access .root on unmounted test renderer"); } else if (children.length === 1) { // Normally, we skip the root and just give you the child. return children[0]; } else { // However, we give you the root if there's more than one root child. // We could make this the behavior for all cases but it would be a breaking change. // $FlowFixMe[incompatible-use] found when upgrading Flow return wrapFiber(root.current); } }, }: Object), ); return entry; } const fiberToWrapper = new WeakMap<Fiber, ReactTestInstance>(); function wrapFiber(fiber: Fiber): ReactTestInstance { let wrapper = fiberToWrapper.get(fiber); if (wrapper === undefined && fiber.alternate !== null) { wrapper = fiberToWrapper.get(fiber.alternate); } if (wrapper === undefined) { wrapper = new ReactTestInstance(fiber); fiberToWrapper.set(fiber, wrapper); } return wrapper; } // Enable ReactTestRenderer to be used to test DevTools integration. injectIntoDevTools({ findFiberByHostInstance: (() => { throw new Error('TestRenderer does not support findFiberByHostInstance()'); }: any), bundleType: __DEV__ ? 1 : 0, version: ReactVersion, rendererPackageName: 'react-test-renderer', }); export { Scheduler as _Scheduler, create, /* eslint-disable-next-line camelcase */ batchedUpdates as unstable_batchedUpdates, act, };
25.530769
95
0.630944
PenetrationTestingScripts
/* global chrome */ function injectBackendManager(tabId) { chrome.runtime.sendMessage({ source: 'devtools-page', payload: { type: 'inject-backend-manager', tabId, }, }); } export default injectBackendManager;
16.142857
38
0.65272
null
/** * 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'; export * from '../ReactFlightServerConfigBundlerCustom'; export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM'; export const supportsRequestStorage = false; export const requestStorage: AsyncLocalStorage<Request> = (null: any); export * from '../ReactFlightServerConfigDebugNoop';
29.157895
73
0.76049
null
(function () { 'use strict'; var ReactImage0 = function (x) { if (x === 0) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (x === 15) { return React.createElement('i', { className: '_3ut_ img sp_i534r85sjIn sx_e8ac93', src: null, alt: '', }); } if (x === 22) { return React.createElement('i', { alt: '', className: '_3-8_ img sp_i534r85sjIn sx_7b15bc', src: null, }); } if (x === 29) { return React.createElement('i', { className: '_1m1s _4540 _p img sp_i534r85sjIn sx_f40b1c', src: null, alt: '', }); } if (x === 42) { return React.createElement( 'i', { alt: 'Warning', className: '_585p img sp_i534r85sjIn sx_20273d', src: null, }, React.createElement('u', null, 'Warning') ); } if (x === 67) { return React.createElement('i', { alt: '', className: '_3-8_ img sp_i534r85sjIn sx_b5d079', src: null, }); } if (x === 70) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_29f8c9', }); } if (x === 76) { return React.createElement('i', { alt: '', className: '_3-8_ img sp_i534r85sjIn sx_ef6a9c', src: null, }); } if (x === 79) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_6f8c43', }); } if (x === 88) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_e94a2d', }); } if (x === 91) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_7ed7d4', }); } if (x === 94) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_930440', }); } if (x === 98) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_750c83', }); } if (x === 108) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_73c1bb', }); } if (x === 111) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_29f28d', }); } if (x === 126) { return React.createElement('i', { src: null, alt: '', className: '_3-8_ img sp_i534r85sjIn sx_91c59e', }); } if (x === 127) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (x === 134) { return React.createElement('i', { src: null, alt: '', className: '_3-8_ img sp_i534r85sjIn sx_c8eb75', }); } if (x === 135) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (x === 148) { return React.createElement('i', { className: '_3yz6 _5whs img sp_i534r85sjIn sx_896996', src: null, alt: '', }); } if (x === 152) { return React.createElement('i', { className: '_5b5p _4gem img sp_i534r85sjIn sx_896996', src: null, alt: '', }); } if (x === 153) { return React.createElement('i', { className: '_541d img sp_i534r85sjIn sx_2f396a', src: null, alt: '', }); } if (x === 160) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_31d9b0', }); } if (x === 177) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_2c18b7', src: null, }); } if (x === 186) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_0a681f', }); } if (x === 195) { return React.createElement('i', { className: '_1-lx img sp_OkER5ktbEyg sx_b369b4', src: null, alt: '', }); } if (x === 198) { return React.createElement('i', { className: '_1-lx img sp_i534r85sjIn sx_96948e', src: null, alt: '', }); } if (x === 237) { return React.createElement('i', { className: '_541d img sp_i534r85sjIn sx_2f396a', src: null, alt: '', }); } if (x === 266) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (x === 314) { return React.createElement('i', { className: '_1cie _1cif img sp_i534r85sjIn sx_6e6820', src: null, alt: '', }); } if (x === 345) { return React.createElement('i', { className: '_1cie img sp_i534r85sjIn sx_e896cf', src: null, alt: '', }); } if (x === 351) { return React.createElement('i', { className: '_1cie img sp_i534r85sjIn sx_38fed8', src: null, alt: '', }); } }; var AbstractLink1 = function (x) { if (x === 1) { return React.createElement( 'a', { className: '_387r _55pi _2agf _4jy0 _4jy4 _517h _51sy _42ft', style: {width: 250, maxWidth: '250px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '236px'}}, null, React.createElement( 'span', null, React.createElement('span', {className: '_48u-'}, 'Account:'), ' ', 'Dick Madanson (10149999073643408)' ) ), ReactImage0(0) ); } if (x === 43) { return React.createElement( 'a', { className: '_585q _50zy _50-0 _50z- _5upp _42ft', size: 'medium', type: null, title: 'Remove', 'data-hover': undefined, 'data-tooltip-alignh': undefined, 'data-tooltip-content': undefined, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, undefined, 'Remove', undefined ); } if (x === 49) { return React.createElement( 'a', { target: '_blank', href: '/ads/manage/billing.php?act=10149999073643408', rel: undefined, onClick: function () {}, }, XUIText29(48) ); } if (x === 128) { return React.createElement( 'a', { className: ' _5bbf _55pi _2agf _4jy0 _4jy4 _517h _51sy _42ft', style: {maxWidth: '200px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '186px'}}, ReactImage0(126), 'Search' ), ReactImage0(127) ); } if (x === 136) { return React.createElement( 'a', { className: ' _5bbf _55pi _2agf _4jy0 _4jy4 _517h _51sy _42ft', style: {maxWidth: '200px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '186px'}}, ReactImage0(134), 'Filters' ), ReactImage0(135) ); } if (x === 178) { return React.createElement( 'a', { className: '_1_-t _1_-v _42ft', disabled: null, height: 'medium', role: 'button', label: null, href: '#', rel: undefined, onClick: function () {}, }, undefined, 'Lifetime', ReactImage0(177) ); } if (x === 207) { return React.createElement( 'a', {href: '#', rel: undefined, onClick: function () {}}, 'Create Ad Set' ); } if (x === 209) { return React.createElement( 'a', {href: '#', rel: undefined, onClick: function () {}}, 'View Ad Set' ); } if (x === 241) { return React.createElement( 'a', {href: '#', rel: undefined, onClick: function () {}}, 'Set a Limit' ); } if (x === 267) { return React.createElement( 'a', { className: '_p _55pi _2agf _4jy0 _4jy3 _517h _51sy _42ft', style: {maxWidth: '200px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '186px'}}, null, 'Links' ), ReactImage0(266) ); } }; var Link2 = function (x) { if (x === 2) { return AbstractLink1(1); } if (x === 44) { return AbstractLink1(43); } if (x === 50) { return AbstractLink1(49); } if (x === 129) { return AbstractLink1(128); } if (x === 137) { return AbstractLink1(136); } if (x === 179) { return AbstractLink1(178); } if (x === 208) { return AbstractLink1(107); } if (x === 210) { return AbstractLink1(209); } if (x === 242) { return AbstractLink1(241); } if (x === 268) { return AbstractLink1(267); } }; var AbstractButton3 = function (x) { if (x === 3) { return Link2(2); } if (x === 20) { return React.createElement( 'button', { className: '_5n7z _4jy0 _4jy4 _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, 'Discard Changes', undefined ); } if (x === 23) { return React.createElement( 'button', { className: '_5n7z _2yak _4lj- _4jy0 _4jy4 _517h _51sy _42ft _42fr', disabled: true, onClick: function () {}, 'data-tooltip-content': 'You have no changes to publish', 'data-hover': 'tooltip', label: null, type: 'submit', value: '1', }, ReactImage0(22), 'Review Changes', undefined ); } if (x === 45) { return Link2(44); } if (x === 68) { return React.createElement( 'button', { className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(67), 'Create Campaign', undefined ); } if (x === 71) { return React.createElement( 'button', { className: '_u_k _3qx6 _p _4jy0 _4jy4 _517h _51sy _42ft', label: null, type: 'submit', value: '1', }, ReactImage0(70), undefined, undefined ); } if (x === 77) { return React.createElement( 'button', { 'aria-label': 'Edit', 'data-tooltip-content': 'Edit Campaigns (Ctrl+U)', 'data-hover': 'tooltip', className: '_d2_ _u_k noMargin _4jy0 _4jy4 _517h _51sy _42ft', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(76), 'Edit', undefined ); } if (x === 80) { return React.createElement( 'button', { className: '_u_k _3qx6 _p _4jy0 _4jy4 _517h _51sy _42ft', disabled: false, label: null, type: 'submit', value: '1', }, ReactImage0(79), undefined, undefined ); } if (x === 89) { return React.createElement( 'button', { 'aria-label': 'Revert', className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft _42fr', 'data-hover': 'tooltip', 'data-tooltip-content': 'Revert', disabled: true, onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(88), undefined, undefined ); } if (x === 92) { return React.createElement( 'button', { 'aria-label': 'Delete', className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Delete', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(91), undefined, undefined ); } if (x === 95) { return React.createElement( 'button', { 'aria-label': 'Duplicate', className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Duplicate', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(94), undefined, undefined ); } if (x === 99) { return React.createElement( 'button', { 'aria-label': 'Export & Import', className: '_u_k noMargin _p _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Export & Import', onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(98), undefined, undefined ); } if (x === 109) { return React.createElement( 'button', { 'aria-label': 'Create Report', className: '_u_k _5n7z _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Create Report', disabled: false, style: {boxSizing: 'border-box', height: '28px', width: '48px'}, onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(108), undefined, undefined ); } if (x === 112) { return React.createElement( 'button', { 'aria-label': 'Campaign Tags', className: ' _5uy7 _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Campaign Tags', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(111), undefined, undefined ); } if (x === 130) { return Link2(129); } if (x === 138) { return Link2(137); } if (x === 149) { return React.createElement( 'button', { className: '_3yz9 _1t-2 _50z- _50zy _50zz _50z- _5upp _42ft', size: 'small', onClick: function () {}, type: 'button', title: 'Remove', 'data-hover': undefined, 'data-tooltip-alignh': undefined, 'data-tooltip-content': undefined, label: null, }, undefined, 'Remove', undefined ); } if (x === 156) { return React.createElement( 'button', { className: '_5b5u _5b5v _4jy0 _4jy3 _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, 'Apply', undefined ); } if (x === 161) { return React.createElement( 'button', { className: '_1wdf _4jy0 _517i _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(160), undefined, undefined ); } if (x === 180) { return Link2(179); } if (x === 187) { return React.createElement( 'button', { 'aria-label': 'List Settings', className: '_u_k _3c5o _1-r0 _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'List Settings', onClick: function () {}, label: null, type: 'submit', value: '1', }, ReactImage0(186), undefined, undefined ); } if (x === 269) { return Link2(268); } if (x === 303) { return React.createElement( 'button', { className: '_tm3 _tm6 _tm7 _4jy0 _4jy6 _517h _51sy _42ft', 'data-tooltip-position': 'right', 'data-tooltip-content': 'Campaigns', 'data-hover': 'tooltip', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, React.createElement( 'div', null, React.createElement('div', {className: '_tma'}), React.createElement('div', {className: '_tm8'}), React.createElement('div', {className: '_tm9'}, 1) ), undefined ); } if (x === 305) { return React.createElement( 'button', { className: '_tm4 _tm6 _4jy0 _4jy6 _517h _51sy _42ft', 'data-tooltip-position': 'right', 'data-tooltip-content': 'Ad Sets', 'data-hover': 'tooltip', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, React.createElement( 'div', null, React.createElement('div', {className: '_tma'}), React.createElement('div', {className: '_tm8'}), React.createElement('div', {className: '_tm9'}, 1) ), undefined ); } if (x === 307) { return React.createElement( 'button', { className: '_tm5 _tm6 _4jy0 _4jy6 _517h _51sy _42ft', 'data-tooltip-position': 'right', 'data-tooltip-content': 'Ads', 'data-hover': 'tooltip', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, React.createElement( 'div', null, React.createElement('div', {className: '_tma'}), React.createElement('div', {className: '_tm8'}), React.createElement('div', {className: '_tm9'}, 1) ), undefined ); } }; var XUIButton4 = function (x) { if (x === 4) { return AbstractButton3(3); } if (x === 21) { return AbstractButton3(20); } if (x === 24) { return AbstractButton3(23); } if (x === 69) { return AbstractButton3(68); } if (x === 72) { return AbstractButton3(71); } if (x === 78) { return AbstractButton3(77); } if (x === 81) { return AbstractButton3(80); } if (x === 90) { return AbstractButton3(89); } if (x === 93) { return AbstractButton3(92); } if (x === 96) { return AbstractButton3(95); } if (x === 100) { return AbstractButton3(99); } if (x === 110) { return AbstractButton3(109); } if (x === 113) { return AbstractButton3(112); } if (x === 131) { return AbstractButton3(130); } if (x === 139) { return AbstractButton3(138); } if (x === 157) { return AbstractButton3(156); } if (x === 162) { return AbstractButton3(161); } if (x === 188) { return AbstractButton3(187); } if (x === 270) { return AbstractButton3(269); } if (x === 304) { return AbstractButton3(303); } if (x === 306) { return AbstractButton3(305); } if (x === 308) { return AbstractButton3(307); } }; var AbstractPopoverButton5 = function (x) { if (x === 5) { return XUIButton4(4); } if (x === 132) { return XUIButton4(131); } if (x === 140) { return XUIButton4(139); } if (x === 271) { return XUIButton4(270); } }; var ReactXUIPopoverButton6 = function (x) { if (x === 6) { return AbstractPopoverButton5(5); } if (x === 133) { return AbstractPopoverButton5(132); } if (x === 141) { return AbstractPopoverButton5(140); } if (x === 272) { return AbstractPopoverButton5(271); } }; var BIGAdAccountSelector7 = function (x) { if (x === 7) { return React.createElement('div', null, ReactXUIPopoverButton6(6), null); } }; var FluxContainer_AdsPEBIGAdAccountSelectorContainer_8 = function (x) { if (x === 8) { return BIGAdAccountSelector7(7); } }; var ErrorBoundary9 = function (x) { if (x === 9) { return FluxContainer_AdsPEBIGAdAccountSelectorContainer_8(8); } if (x === 13) { return FluxContainer_AdsPENavigationBarContainer_12(12); } if (x === 27) { return FluxContainer_AdsPEPublishButtonContainer_18(26); } if (x === 32) { return ReactPopoverMenu20(31); } if (x === 38) { return AdsPEResetDialog24(37); } if (x === 57) { return FluxContainer_AdsPETopErrorContainer_35(56); } if (x === 60) { return FluxContainer_AdsGuidanceChannel_36(59); } if (x === 64) { return FluxContainer_AdsBulkEditDialogContainer_38(63); } if (x === 124) { return AdsPECampaignGroupToolbarContainer57(123); } if (x === 170) { return AdsPEFilterContainer72(169); } if (x === 175) { return AdsPETablePagerContainer75(174); } if (x === 193) { return AdsPEStatRangeContainer81(192); } if (x === 301) { return FluxContainer_AdsPEMultiTabDrawerContainer_137(300); } if (x === 311) { return AdsPEOrganizerContainer139(310); } if (x === 471) { return AdsPECampaignGroupTableContainer159(470); } if (x === 475) { return AdsPEContentContainer161(474); } }; var AdsErrorBoundary10 = function (x) { if (x === 10) { return ErrorBoundary9(9); } if (x === 14) { return ErrorBoundary9(13); } if (x === 28) { return ErrorBoundary9(27); } if (x === 33) { return ErrorBoundary9(32); } if (x === 39) { return ErrorBoundary9(38); } if (x === 58) { return ErrorBoundary9(57); } if (x === 61) { return ErrorBoundary9(60); } if (x === 65) { return ErrorBoundary9(64); } if (x === 125) { return ErrorBoundary9(124); } if (x === 171) { return ErrorBoundary9(170); } if (x === 176) { return ErrorBoundary9(175); } if (x === 194) { return ErrorBoundary9(193); } if (x === 302) { return ErrorBoundary9(301); } if (x === 312) { return ErrorBoundary9(311); } if (x === 472) { return ErrorBoundary9(471); } if (x === 476) { return ErrorBoundary9(475); } }; var AdsPENavigationBar11 = function (x) { if (x === 11) { return React.createElement('div', {className: '_4t_9'}); } }; var FluxContainer_AdsPENavigationBarContainer_12 = function (x) { if (x === 12) { return AdsPENavigationBar11(11); } }; var AdsPEDraftSyncStatus13 = function (x) { if (x === 16) { return React.createElement( 'div', {className: '_3ut-', onClick: function () {}}, React.createElement('span', {className: '_3uu0'}, ReactImage0(15)) ); } }; var FluxContainer_AdsPEDraftSyncStatusContainer_14 = function (x) { if (x === 17) { return AdsPEDraftSyncStatus13(16); } }; var AdsPEDraftErrorsStatus15 = function (x) { if (x === 18) { return null; } }; var FluxContainer_viewFn_16 = function (x) { if (x === 19) { return AdsPEDraftErrorsStatus15(18); } }; var AdsPEPublishButton17 = function (x) { if (x === 25) { return React.createElement( 'div', {className: '_5533'}, FluxContainer_AdsPEDraftSyncStatusContainer_14(17), FluxContainer_viewFn_16(19), null, XUIButton4(21, 'discard'), XUIButton4(24) ); } }; var FluxContainer_AdsPEPublishButtonContainer_18 = function (x) { if (x === 26) { return AdsPEPublishButton17(25); } }; var InlineBlock19 = function (x) { if (x === 30) { return React.createElement( 'div', {className: 'uiPopover _6a _6b', disabled: null}, ReactImage0(29) ); } if (x === 73) { return React.createElement( 'div', {className: 'uiPopover _6a _6b', disabled: null}, XUIButton4(72) ); } if (x === 82) { return React.createElement( 'div', {className: '_1nwm uiPopover _6a _6b', disabled: null}, XUIButton4(81) ); } if (x === 101) { return React.createElement( 'div', {size: 'large', className: 'uiPopover _6a _6b', disabled: null}, XUIButton4(100) ); } if (x === 273) { return React.createElement( 'div', { className: '_3-90 uiPopover _6a _6b', style: {marginTop: 2}, disabled: null, }, ReactXUIPopoverButton6(272) ); } }; var ReactPopoverMenu20 = function (x) { if (x === 31) { return InlineBlock19(30); } if (x === 74) { return InlineBlock19(73); } if (x === 83) { return InlineBlock19(82); } if (x === 102) { return InlineBlock19(101); } if (x === 274) { return InlineBlock19(273); } }; var LeftRight21 = function (x) { if (x === 34) { return React.createElement( 'div', {className: 'clearfix'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, React.createElement( 'div', {className: '_34_j'}, React.createElement( 'div', {className: '_34_k'}, AdsErrorBoundary10(10) ), React.createElement( 'div', {className: '_2u-6'}, AdsErrorBoundary10(14) ) ) ), React.createElement( 'div', {key: 'right', className: '_ohf rfloat'}, React.createElement( 'div', {className: '_34_m'}, React.createElement( 'div', {key: '0', className: '_5ju2'}, AdsErrorBoundary10(28) ), React.createElement( 'div', {key: '1', className: '_5ju2'}, AdsErrorBoundary10(33) ) ) ) ); } if (x === 232) { return React.createElement( 'div', {direction: 'left', className: 'clearfix'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, AdsLabeledField104(231) ), React.createElement( 'div', {key: 'right', className: ''}, React.createElement( 'div', {className: '_42ef'}, React.createElement( 'div', {className: '_2oc7'}, 'Clicks to Website' ) ) ) ); } if (x === 235) { return React.createElement( 'div', {className: '_3-8x clearfix', direction: 'left'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, AdsLabeledField104(234) ), React.createElement( 'div', {key: 'right', className: ''}, React.createElement( 'div', {className: '_42ef'}, React.createElement('div', {className: '_2oc7'}, 'Auction') ) ) ); } if (x === 245) { return React.createElement( 'div', {className: '_3-8y clearfix', direction: 'left'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, AdsLabeledField104(240) ), React.createElement( 'div', {key: 'right', className: ''}, React.createElement( 'div', {className: '_42ef'}, FluxContainer_AdsCampaignGroupSpendCapContainer_107(244) ) ) ); } if (x === 277) { return React.createElement( 'div', {className: '_5dw9 _5dwa clearfix'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, XUICardHeaderTitle100(265) ), React.createElement( 'div', {key: 'right', className: '_ohf rfloat'}, FluxContainer_AdsPluginizedLinksMenuContainer_121(276) ) ); } }; var AdsUnifiedNavigationLocalNav22 = function (x) { if (x === 35) { return React.createElement('div', {className: '_34_i'}, LeftRight21(34)); } }; var XUIDialog23 = function (x) { if (x === 36) { return null; } }; var AdsPEResetDialog24 = function (x) { if (x === 37) { return React.createElement('span', null, XUIDialog23(36)); } }; var AdsPETopNav25 = function (x) { if (x === 40) { return React.createElement( 'div', {style: {width: 1306}}, AdsUnifiedNavigationLocalNav22(35), AdsErrorBoundary10(39) ); } }; var FluxContainer_AdsPETopNavContainer_26 = function (x) { if (x === 41) { return AdsPETopNav25(40); } }; var XUIAbstractGlyphButton27 = function (x) { if (x === 46) { return AbstractButton3(45); } if (x === 150) { return AbstractButton3(149); } }; var XUICloseButton28 = function (x) { if (x === 47) { return XUIAbstractGlyphButton27(46); } if (x === 151) { return XUIAbstractGlyphButton27(150); } }; var XUIText29 = function (x) { if (x === 48) { return React.createElement( 'span', {display: 'inline', className: ' _50f7'}, 'Ads Manager' ); } if (x === 205) { return React.createElement( 'span', {className: '_2x9f _50f5 _50f7', display: 'inline'}, 'Editing Campaign' ); } if (x === 206) { return React.createElement( 'span', {display: 'inline', className: ' _50f5 _50f7'}, 'Test Campaign' ); } }; var XUINotice30 = function (x) { if (x === 51) { return React.createElement( 'div', {size: 'medium', className: '_585n _585o _2wdd'}, ReactImage0(42), XUICloseButton28(47), React.createElement( 'div', {className: '_585r _2i-a _50f4'}, 'Please go to ', Link2(50), ' to set up a payment method for this ad account.' ) ); } }; var ReactCSSTransitionGroupChild31 = function (x) { if (x === 52) { return XUINotice30(51); } }; var ReactTransitionGroup32 = function (x) { if (x === 53) { return React.createElement( 'span', null, ReactCSSTransitionGroupChild31(52) ); } }; var ReactCSSTransitionGroup33 = function (x) { if (x === 54) { return ReactTransitionGroup32(53); } }; var AdsPETopError34 = function (x) { if (x === 55) { return React.createElement( 'div', {className: '_2wdc'}, ReactCSSTransitionGroup33(54) ); } }; var FluxContainer_AdsPETopErrorContainer_35 = function (x) { if (x === 56) { return AdsPETopError34(55); } }; var FluxContainer_AdsGuidanceChannel_36 = function (x) { if (x === 59) { return null; } }; var ResponsiveBlock37 = function (x) { if (x === 62) { return React.createElement( 'div', {className: '_4u-c'}, [AdsErrorBoundary10(58), AdsErrorBoundary10(61)], React.createElement( 'div', {key: 'sensor', className: '_4u-f'}, React.createElement('iframe', { 'aria-hidden': 'true', className: '_1_xb', tabIndex: '-1', }) ) ); } if (x === 469) { return React.createElement( 'div', {className: '_4u-c'}, AdsPEDataTableContainer158(468), React.createElement( 'div', {key: 'sensor', className: '_4u-f'}, React.createElement('iframe', { 'aria-hidden': 'true', className: '_1_xb', tabIndex: '-1', }) ) ); } }; var FluxContainer_AdsBulkEditDialogContainer_38 = function (x) { if (x === 63) { return null; } }; var Column39 = function (x) { if (x === 66) { return React.createElement( 'div', {className: '_4bl8 _4bl7'}, React.createElement( 'div', {className: '_3c5f'}, null, null, React.createElement('div', {className: '_3c5i'}), null ) ); } }; var XUIButtonGroup40 = function (x) { if (x === 75) { return React.createElement( 'div', {className: '_5n7z _51xa'}, XUIButton4(69), ReactPopoverMenu20(74) ); } if (x === 84) { return React.createElement( 'div', {className: '_5n7z _51xa'}, XUIButton4(78), ReactPopoverMenu20(83) ); } if (x === 97) { return React.createElement( 'div', {className: '_5n7z _51xa'}, XUIButton4(90), XUIButton4(93), XUIButton4(96) ); } if (x === 117) { return React.createElement( 'div', {className: '_5n7z _51xa'}, AdsPEExportImportMenuContainer48(107), XUIButton4(110), AdsPECampaignGroupTagContainer51(116) ); } }; var AdsPEEditToolbarButton41 = function (x) { if (x === 85) { return XUIButtonGroup40(84); } }; var FluxContainer_AdsPEEditCampaignGroupToolbarButtonContainer_42 = function ( x ) { if (x === 86) { return AdsPEEditToolbarButton41(85); } }; var FluxContainer_AdsPEEditToolbarButtonContainer_43 = function (x) { if (x === 87) { return FluxContainer_AdsPEEditCampaignGroupToolbarButtonContainer_42(86); } }; var AdsPEExportImportMenu44 = function (x) { if (x === 103) { return ReactPopoverMenu20(102); } }; var FluxContainer_AdsPECustomizeExportContainer_45 = function (x) { if (x === 104) { return null; } }; var AdsPEExportAsTextDialog46 = function (x) { if (x === 105) { return null; } }; var FluxContainer_AdsPEExportAsTextDialogContainer_47 = function (x) { if (x === 106) { return AdsPEExportAsTextDialog46(105); } }; var AdsPEExportImportMenuContainer48 = function (x) { if (x === 107) { return React.createElement( 'span', null, AdsPEExportImportMenu44(103), FluxContainer_AdsPECustomizeExportContainer_45(104), FluxContainer_AdsPEExportAsTextDialogContainer_47(106), null, null ); } }; var Constructor49 = function (x) { if (x === 114) { return null; } if (x === 142) { return null; } if (x === 143) { return null; } if (x === 183) { return null; } }; var TagSelectorPopover50 = function (x) { if (x === 115) { return React.createElement( 'span', {className: ' _3d6e'}, XUIButton4(113), Constructor49(114) ); } }; var AdsPECampaignGroupTagContainer51 = function (x) { if (x === 116) { return TagSelectorPopover50(115); } }; var AdsRuleToolbarMenu52 = function (x) { if (x === 118) { return null; } }; var FluxContainer_AdsPERuleToolbarMenuContainer_53 = function (x) { if (x === 119) { return AdsRuleToolbarMenu52(118); } }; var FillColumn54 = function (x) { if (x === 120) { return React.createElement( 'div', {className: '_4bl9'}, React.createElement( 'span', {className: '_3c5e'}, React.createElement( 'span', null, XUIButtonGroup40(75), FluxContainer_AdsPEEditToolbarButtonContainer_43(87), null, XUIButtonGroup40(97) ), XUIButtonGroup40(117), FluxContainer_AdsPERuleToolbarMenuContainer_53(119) ) ); } }; var Layout55 = function (x) { if (x === 121) { return React.createElement( 'div', {className: 'clearfix'}, Column39(66), FillColumn54(120) ); } }; var AdsPEMainPaneToolbar56 = function (x) { if (x === 122) { return React.createElement( 'div', {className: '_3c5b clearfix'}, Layout55(121) ); } }; var AdsPECampaignGroupToolbarContainer57 = function (x) { if (x === 123) { return AdsPEMainPaneToolbar56(122); } }; var AdsPEFiltersPopover58 = function (x) { if (x === 144) { return React.createElement( 'span', {className: '_5b-l _5bbe'}, ReactXUIPopoverButton6(133), ReactXUIPopoverButton6(141), [Constructor49(142), Constructor49(143)] ); } }; var AbstractCheckboxInput59 = function (x) { if (x === 145) { return React.createElement( 'label', {className: 'uiInputLabelInput _55sg _kv1'}, React.createElement('input', { checked: true, disabled: true, name: 'filterUnpublished', value: 'on', onClick: function () {}, className: null, id: 'js_input_label_21', type: 'checkbox', }), React.createElement('span', { 'data-hover': null, 'data-tooltip-content': undefined, }) ); } if (x === 336) { return React.createElement( 'label', {className: '_4h2r _55sg _kv1'}, React.createElement('input', { checked: undefined, onChange: function () {}, className: null, type: 'checkbox', }), React.createElement('span', { 'data-hover': null, 'data-tooltip-content': undefined, }) ); } }; var XUICheckboxInput60 = function (x) { if (x === 146) { return AbstractCheckboxInput59(145); } if (x === 337) { return AbstractCheckboxInput59(336); } }; var InputLabel61 = function (x) { if (x === 147) { return React.createElement( 'div', {display: 'block', className: 'uiInputLabel clearfix'}, XUICheckboxInput60(146), React.createElement( 'label', {className: 'uiInputLabelLabel', htmlFor: 'js_input_label_21'}, 'Always show new items' ) ); } }; var AdsPopoverLink62 = function (x) { if (x === 154) { return React.createElement( 'span', null, React.createElement( 'span', { onMouseEnter: function () {}, onMouseLeave: function () {}, onMouseUp: undefined, }, React.createElement('span', {className: '_3o_j'}), ReactImage0(153) ), null ); } if (x === 238) { return React.createElement( 'span', null, React.createElement( 'span', { onMouseEnter: function () {}, onMouseLeave: function () {}, onMouseUp: undefined, }, React.createElement('span', {className: '_3o_j'}), ReactImage0(237) ), null ); } }; var AdsHelpLink63 = function (x) { if (x === 155) { return AdsPopoverLink62(154); } if (x === 239) { return AdsPopoverLink62(238); } }; var BUIFilterTokenInput64 = function (x) { if (x === 158) { return React.createElement( 'div', {className: '_5b5o _3yz3 _4cld'}, React.createElement( 'div', {className: '_5b5t _2d2k'}, ReactImage0(152), React.createElement( 'div', {className: '_5b5r'}, 'Campaigns: (1)', AdsHelpLink63(155) ) ), XUIButton4(157) ); } }; var BUIFilterToken65 = function (x) { if (x === 159) { return React.createElement( 'div', {className: '_3yz1 _3yz2 _3dad'}, React.createElement( 'div', {className: '_3yz4', 'aria-hidden': false}, React.createElement( 'div', {onClick: function () {}, className: '_3yz5'}, ReactImage0(148), React.createElement('div', {className: '_3yz7'}, 'Campaigns:'), React.createElement( 'div', { className: 'ellipsis _3yz8', 'data-hover': 'tooltip', 'data-tooltip-display': 'overflow', }, '(1)' ) ), null, XUICloseButton28(151) ), BUIFilterTokenInput64(158) ); } }; var BUIFilterTokenCreateButton66 = function (x) { if (x === 163) { return React.createElement('div', {className: '_1tc'}, XUIButton4(162)); } }; var BUIFilterTokenizer67 = function (x) { if (x === 164) { return React.createElement( 'div', {className: '_5b-m clearfix'}, undefined, [], BUIFilterToken65(159), BUIFilterTokenCreateButton66(163), null, React.createElement('div', {className: '_49u3'}) ); } }; var XUIAmbientNUX68 = function (x) { if (x === 165) { return null; } if (x === 189) { return null; } if (x === 200) { return null; } }; var XUIAmbientNUX69 = function (x) { if (x === 166) { return XUIAmbientNUX68(165); } if (x === 190) { return XUIAmbientNUX68(189); } if (x === 201) { return XUIAmbientNUX68(200); } }; var AdsPEAmbientNUXMegaphone70 = function (x) { if (x === 167) { return React.createElement( 'span', null, React.createElement('span', {}), XUIAmbientNUX69(166) ); } }; var AdsPEFilters71 = function (x) { if (x === 168) { return React.createElement( 'div', {className: '_4rw_'}, AdsPEFiltersPopover58(144), React.createElement('div', {className: '_1eo'}, InputLabel61(147)), BUIFilterTokenizer67(164), '', AdsPEAmbientNUXMegaphone70(167) ); } }; var AdsPEFilterContainer72 = function (x) { if (x === 169) { return AdsPEFilters71(168); } }; var AdsPETablePager73 = function (x) { if (x === 172) { return null; } }; var AdsPECampaignGroupTablePagerContainer74 = function (x) { if (x === 173) { return AdsPETablePager73(172); } }; var AdsPETablePagerContainer75 = function (x) { if (x === 174) { return AdsPECampaignGroupTablePagerContainer74(173); } }; var ReactXUIError76 = function (x) { if (x === 181) { return AbstractButton3(180); } if (x === 216) { return React.createElement( 'div', {className: '_40bf _2vl4 _1h18'}, null, null, React.createElement( 'div', {className: '_2vl9 _1h1f', style: {backgroundColor: '#fff'}}, React.createElement( 'div', {className: '_2vla _1h1g'}, React.createElement( 'div', null, null, React.createElement('textarea', { className: '_2vli _2vlj _1h26 _1h27', dir: 'auto', disabled: undefined, id: undefined, maxLength: null, value: 'Test Campaign', onBlur: function () {}, onChange: function () {}, onFocus: function () {}, onKeyDown: function () {}, }), null ), React.createElement('div', { 'aria-hidden': 'true', className: '_2vlk', }) ) ), null ); } if (x === 221) { return XUICard94(220); } if (x === 250) { return XUICard94(249); } if (x === 280) { return XUICard94(279); } }; var BUIPopoverButton77 = function (x) { if (x === 182) { return ReactXUIError76(181); } }; var BUIDateRangePicker78 = function (x) { if (x === 184) { return React.createElement('span', null, BUIPopoverButton77(182), [ Constructor49(183), ]); } }; var AdsPEStatsRangePicker79 = function (x) { if (x === 185) { return BUIDateRangePicker78(184); } }; var AdsPEStatRange80 = function (x) { if (x === 191) { return React.createElement( 'div', {className: '_3c5k'}, React.createElement('span', {className: '_3c5j'}, 'Stats:'), React.createElement( 'span', {className: '_3c5l'}, AdsPEStatsRangePicker79(185), XUIButton4(188) ), [XUIAmbientNUX69(190)] ); } }; var AdsPEStatRangeContainer81 = function (x) { if (x === 192) { return AdsPEStatRange80(191); } }; var AdsPESideTrayTabButton82 = function (x) { if (x === 196) { return React.createElement( 'div', {className: '_1-ly _59j9 _d9a', onClick: function () {}}, ReactImage0(195), React.createElement('div', {className: '_vf7'}), React.createElement('div', {className: '_vf8'}) ); } if (x === 199) { return React.createElement( 'div', {className: ' _1-lz _d9a', onClick: function () {}}, ReactImage0(198), React.createElement('div', {className: '_vf7'}), React.createElement('div', {className: '_vf8'}) ); } if (x === 203) { return null; } }; var AdsPEEditorTrayTabButton83 = function (x) { if (x === 197) { return AdsPESideTrayTabButton82(196); } }; var AdsPEInsightsTrayTabButton84 = function (x) { if (x === 202) { return React.createElement( 'span', null, AdsPESideTrayTabButton82(199), XUIAmbientNUX69(201) ); } }; var AdsPENekoDebuggerTrayTabButton85 = function (x) { if (x === 204) { return AdsPESideTrayTabButton82(203); } }; var AdsPEEditorChildLink86 = function (x) { if (x === 211) { return React.createElement( 'div', {className: '_3ywr'}, Link2(208), React.createElement('span', {className: '_3ywq'}, '|'), Link2(210) ); } }; var AdsPEEditorChildLinkContainer87 = function (x) { if (x === 212) { return AdsPEEditorChildLink86(211); } }; var AdsPEHeaderSection88 = function (x) { if (x === 213) { return React.createElement( 'div', {className: '_yke'}, React.createElement('div', {className: '_2x9d _pr-'}), XUIText29(205), React.createElement( 'div', {className: '_3a-a'}, React.createElement('div', {className: '_3a-b'}, XUIText29(206)) ), AdsPEEditorChildLinkContainer87(212) ); } }; var AdsPECampaignGroupHeaderSectionContainer89 = function (x) { if (x === 214) { return AdsPEHeaderSection88(213); } }; var AdsEditorLoadingErrors90 = function (x) { if (x === 215) { return null; } }; var AdsTextInput91 = function (x) { if (x === 217) { return ReactXUIError76(216); } }; var BUIFormElement92 = function (x) { if (x === 218) { return React.createElement( 'div', {className: '_5521 clearfix'}, React.createElement( 'div', {className: '_5522 _3w5q'}, React.createElement( 'label', { onClick: undefined, htmlFor: '1467872040612:1961945894', className: '_5523 _3w5r', }, 'Campaign Name', null ) ), React.createElement( 'div', {className: '_5527'}, React.createElement( 'div', {className: '_5528'}, React.createElement( 'span', {key: '.0', className: '_40bg', id: '1467872040612:1961945894'}, AdsTextInput91(217), null ) ), null ) ); } }; var BUIForm93 = function (x) { if (x === 219) { return React.createElement( 'div', {className: '_5ks1 _550r _550t _550y _3w5n'}, BUIFormElement92(218) ); } }; var XUICard94 = function (x) { if (x === 220) { return React.createElement( 'div', {className: '_40bc _12k2 _4-u2 _4-u8'}, BUIForm93(219) ); } if (x === 249) { return React.createElement( 'div', {className: '_12k2 _4-u2 _4-u8'}, AdsCardHeader103(230), AdsCardSection108(248) ); } if (x === 279) { return React.createElement( 'div', {className: '_12k2 _4-u2 _4-u8'}, AdsCardLeftRightHeader122(278) ); } }; var AdsCard95 = function (x) { if (x === 222) { return ReactXUIError76(221); } if (x === 251) { return ReactXUIError76(250); } if (x === 281) { return ReactXUIError76(280); } }; var AdsEditorNameSection96 = function (x) { if (x === 223) { return AdsCard95(222); } }; var AdsCampaignGroupNameSectionContainer97 = function (x) { if (x === 224) { return AdsEditorNameSection96(223); } }; var _render98 = function (x) { if (x === 225) { return AdsCampaignGroupNameSectionContainer97(224); } }; var AdsPluginWrapper99 = function (x) { if (x === 226) { return _render98(225); } if (x === 255) { return _render111(254); } if (x === 258) { return _render113(257); } if (x === 287) { return _render127(286); } if (x === 291) { return _render130(290); } }; var XUICardHeaderTitle100 = function (x) { if (x === 227) { return React.createElement( 'span', {className: '_38my'}, 'Campaign Details', null, React.createElement('span', {className: '_c1c'}) ); } if (x === 265) { return React.createElement( 'span', {className: '_38my'}, [ React.createElement( 'span', {key: 1}, 'Campaign ID', ': ', '98010048849317' ), React.createElement( 'div', {className: '_5lh9', key: 2}, FluxContainer_AdsCampaignGroupStatusSwitchContainer_119(264) ), ], null, React.createElement('span', {className: '_c1c'}) ); } }; var XUICardSection101 = function (x) { if (x === 228) { return React.createElement( 'div', {className: '_5dw9 _5dwa _4-u3'}, [XUICardHeaderTitle100(227)], undefined, undefined, React.createElement('div', {className: '_3s3-'}) ); } if (x === 247) { return React.createElement( 'div', {className: '_12jy _4-u3'}, React.createElement( 'div', {className: '_3-8j'}, FlexibleBlock105(233), FlexibleBlock105(236), FlexibleBlock105(246), null, null ) ); } }; var XUICardHeader102 = function (x) { if (x === 229) { return XUICardSection101(228); } }; var AdsCardHeader103 = function (x) { if (x === 230) { return XUICardHeader102(229); } }; var AdsLabeledField104 = function (x) { if (x === 231) { return React.createElement( 'div', {className: '_2oc6 _3bvz', label: 'Objective'}, React.createElement( 'label', {className: '_4el4 _3qwj _3hy-', htmlFor: undefined}, 'Objective ' ), null, React.createElement('div', {className: '_3bv-'}) ); } if (x === 234) { return React.createElement( 'div', {className: '_2oc6 _3bvz', label: 'Buying Type'}, React.createElement( 'label', {className: '_4el4 _3qwj _3hy-', htmlFor: undefined}, 'Buying Type ' ), null, React.createElement('div', {className: '_3bv-'}) ); } if (x === 240) { return React.createElement( 'div', {className: '_2oc6 _3bvz'}, React.createElement( 'label', {className: '_4el4 _3qwj _3hy-', htmlFor: undefined}, 'Campaign Spending Limit ' ), AdsHelpLink63(239), React.createElement('div', {className: '_3bv-'}) ); } }; var FlexibleBlock105 = function (x) { if (x === 233) { return LeftRight21(232); } if (x === 236) { return LeftRight21(235); } if (x === 246) { return LeftRight21(245); } }; var AdsBulkCampaignSpendCapField106 = function (x) { if (x === 243) { return React.createElement( 'div', {className: '_33dv'}, '', Link2(242), ' (optional)' ); } }; var FluxContainer_AdsCampaignGroupSpendCapContainer_107 = function (x) { if (x === 244) { return AdsBulkCampaignSpendCapField106(243); } }; var AdsCardSection108 = function (x) { if (x === 248) { return XUICardSection101(247); } }; var AdsEditorCampaignGroupDetailsSection109 = function (x) { if (x === 252) { return AdsCard95(251); } }; var AdsEditorCampaignGroupDetailsSectionContainer110 = function (x) { if (x === 253) { return AdsEditorCampaignGroupDetailsSection109(252); } }; var _render111 = function (x) { if (x === 254) { return AdsEditorCampaignGroupDetailsSectionContainer110(253); } }; var FluxContainer_AdsEditorToplineDetailsSectionContainer_112 = function (x) { if (x === 256) { return null; } }; var _render113 = function (x) { if (x === 257) { return FluxContainer_AdsEditorToplineDetailsSectionContainer_112(256); } }; var AdsStickyArea114 = function (x) { if (x === 259) { return React.createElement( 'div', {}, React.createElement('div', {onWheel: function () {}}) ); } if (x === 292) { return React.createElement( 'div', {}, React.createElement('div', {onWheel: function () {}}, [ React.createElement( 'div', {key: 'campaign_group_errors_section98010048849317'}, AdsPluginWrapper99(291) ), ]) ); } }; var FluxContainer_AdsEditorColumnContainer_115 = function (x) { if (x === 260) { return React.createElement( 'div', null, [ React.createElement( 'div', {key: 'campaign_group_name_section98010048849317'}, AdsPluginWrapper99(226) ), React.createElement( 'div', {key: 'campaign_group_basic_section98010048849317'}, AdsPluginWrapper99(255) ), React.createElement( 'div', {key: 'campaign_group_topline_section98010048849317'}, AdsPluginWrapper99(258) ), ], AdsStickyArea114(259) ); } if (x === 293) { return React.createElement( 'div', null, [ React.createElement( 'div', {key: 'campaign_group_navigation_section98010048849317'}, AdsPluginWrapper99(287) ), ], AdsStickyArea114(292) ); } }; var BUISwitch116 = function (x) { if (x === 261) { return React.createElement( 'div', { 'data-hover': 'tooltip', 'data-tooltip-content': 'Currently active. Click this switch to deactivate it.', 'data-tooltip-position': 'below', disabled: false, value: true, onToggle: function () {}, className: '_128j _128k _128n', role: 'checkbox', 'aria-checked': 'true', }, React.createElement( 'div', { className: '_128o', onClick: function () {}, onKeyDown: function () {}, onMouseDown: function () {}, tabIndex: '0', }, React.createElement('div', {className: '_128p'}) ), null ); } }; var AdsStatusSwitchInternal117 = function (x) { if (x === 262) { return BUISwitch116(261); } }; var AdsStatusSwitch118 = function (x) { if (x === 263) { return AdsStatusSwitchInternal117(262); } }; var FluxContainer_AdsCampaignGroupStatusSwitchContainer_119 = function (x) { if (x === 264) { return AdsStatusSwitch118(263); } }; var AdsLinksMenu120 = function (x) { if (x === 275) { return ReactPopoverMenu20(274); } }; var FluxContainer_AdsPluginizedLinksMenuContainer_121 = function (x) { if (x === 276) { return React.createElement('div', null, null, AdsLinksMenu120(275)); } }; var AdsCardLeftRightHeader122 = function (x) { if (x === 278) { return LeftRight21(277); } }; var AdsPEIDSection123 = function (x) { if (x === 282) { return AdsCard95(281); } }; var FluxContainer_AdsPECampaignGroupIDSectionContainer_124 = function (x) { if (x === 283) { return AdsPEIDSection123(282); } }; var DeferredComponent125 = function (x) { if (x === 284) { return FluxContainer_AdsPECampaignGroupIDSectionContainer_124(283); } }; var BootloadedComponent126 = function (x) { if (x === 285) { return DeferredComponent125(284); } }; var _render127 = function (x) { if (x === 286) { return BootloadedComponent126(285); } }; var AdsEditorErrorsCard128 = function (x) { if (x === 288) { return null; } }; var FluxContainer_FunctionalContainer_129 = function (x) { if (x === 289) { return AdsEditorErrorsCard128(288); } }; var _render130 = function (x) { if (x === 290) { return FluxContainer_FunctionalContainer_129(289); } }; var AdsEditorMultiColumnLayout131 = function (x) { if (x === 294) { return React.createElement( 'div', {className: '_psh'}, React.createElement( 'div', {className: '_3cc0'}, React.createElement( 'div', null, AdsEditorLoadingErrors90(215), React.createElement( 'div', {className: '_3ms3'}, React.createElement( 'div', {className: '_3ms4'}, FluxContainer_AdsEditorColumnContainer_115(260) ), React.createElement( 'div', {className: '_3pvg'}, FluxContainer_AdsEditorColumnContainer_115(293) ) ) ) ) ); } }; var AdsPECampaignGroupEditor132 = function (x) { if (x === 295) { return React.createElement( 'div', null, AdsPECampaignGroupHeaderSectionContainer89(214), AdsEditorMultiColumnLayout131(294) ); } }; var AdsPECampaignGroupEditorContainer133 = function (x) { if (x === 296) { return AdsPECampaignGroupEditor132(295); } }; var AdsPESideTrayTabContent134 = function (x) { if (x === 297) { return React.createElement( 'div', {className: '_1o_8 _44ra _5cyn'}, AdsPECampaignGroupEditorContainer133(296) ); } }; var AdsPEEditorTrayTabContentContainer135 = function (x) { if (x === 298) { return AdsPESideTrayTabContent134(297); } }; var AdsPEMultiTabDrawer136 = function (x) { if (x === 299) { return React.createElement( 'div', {className: '_2kev _2kex'}, React.createElement( 'div', {className: '_5yno'}, AdsPEEditorTrayTabButton83(197), AdsPEInsightsTrayTabButton84(202), AdsPENekoDebuggerTrayTabButton85(204) ), React.createElement( 'div', {className: '_5ynn'}, AdsPEEditorTrayTabContentContainer135(298), null ) ); } }; var FluxContainer_AdsPEMultiTabDrawerContainer_137 = function (x) { if (x === 300) { return AdsPEMultiTabDrawer136(299); } }; var AdsPESimpleOrganizer138 = function (x) { if (x === 309) { return React.createElement( 'div', {className: '_tm2'}, XUIButton4(304), XUIButton4(306), XUIButton4(308) ); } }; var AdsPEOrganizerContainer139 = function (x) { if (x === 310) { return React.createElement('div', null, AdsPESimpleOrganizer138(309)); } }; var FixedDataTableColumnResizeHandle140 = function (x) { if (x === 313) { return React.createElement( 'div', { className: '_3487 _3488 _3489', style: {width: 0, height: 25, left: 0}, }, React.createElement('div', {className: '_348a', style: {height: 25}}) ); } }; var AdsPETableHeader141 = function (x) { if (x === 315) { return React.createElement( 'div', {className: '_1cig _1ksv _1vd7 _4h2r', id: undefined}, ReactImage0(314), React.createElement('span', {className: '_1cid'}, 'Campaigns') ); } if (x === 320) { return React.createElement( 'div', {className: '_1cig _1vd7 _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Performance') ); } if (x === 323) { return React.createElement( 'div', {className: '_1cig _1vd7 _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Overview') ); } if (x === 326) { return React.createElement( 'div', {className: '_1cig _1vd7 _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Toplines') ); } if (x === 329) { return React.createElement('div', { className: '_1cig _1vd7 _4h2r', id: undefined, }); } if (x === 340) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Campaign Name') ); } if (x === 346) { return React.createElement( 'div', { className: '_1cig _25fg', id: undefined, 'data-tooltip-content': 'Changed', 'data-hover': 'tooltip', }, ReactImage0(345), null ); } if (x === 352) { return React.createElement( 'div', { className: '_1cig _25fg', id: 'ads_pe_table_error_header', 'data-tooltip-content': 'Errors', 'data-hover': 'tooltip', }, ReactImage0(351), null ); } if (x === 357) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Status') ); } if (x === 362) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Delivery') ); } if (x === 369) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Results') ); } if (x === 374) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Cost') ); } if (x === 379) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Reach') ); } if (x === 384) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Impressions') ); } if (x === 389) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Clicks') ); } if (x === 394) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Avg. CPM') ); } if (x === 399) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Avg. CPC') ); } if (x === 404) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'CTR %') ); } if (x === 409) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Spent') ); } if (x === 414) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Objective') ); } if (x === 419) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Buying Type') ); } if (x === 424) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Campaign ID') ); } if (x === 429) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Start') ); } if (x === 434) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'End') ); } if (x === 439) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Date created') ); } if (x === 444) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Date last edited') ); } if (x === 449) { return React.createElement( 'div', {className: '_1cig _25fg _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Tags') ); } if (x === 452) { return React.createElement('div', { className: '_1cig _25fg _4h2r', id: undefined, }); } }; var TransitionCell142 = function (x) { if (x === 316) { return React.createElement( 'div', { label: 'Campaigns', height: 40, width: 721, className: '_4lgc _4h2u', style: {height: 40, width: 721}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, AdsPETableHeader141(315) ) ) ); } if (x === 321) { return React.createElement( 'div', { label: 'Performance', height: 40, width: 798, className: '_4lgc _4h2u', style: {height: 40, width: 798}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, AdsPETableHeader141(320) ) ) ); } if (x === 324) { return React.createElement( 'div', { label: 'Overview', height: 40, width: 1022, className: '_4lgc _4h2u', style: {height: 40, width: 1022}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, AdsPETableHeader141(323) ) ) ); } if (x === 327) { return React.createElement( 'div', { label: 'Toplines', height: 40, width: 0, className: '_4lgc _4h2u', style: {height: 40, width: 0}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, AdsPETableHeader141(326) ) ) ); } if (x === 330) { return React.createElement( 'div', { label: '', height: 40, width: 25, className: '_4lgc _4h2u', style: {height: 40, width: 25}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, AdsPETableHeader141(329) ) ) ); } if (x === 338) { return React.createElement( 'div', { label: undefined, width: 42, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 42}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, XUICheckboxInput60(337) ) ) ); } if (x === 343) { return React.createElement( 'div', { label: 'Campaign Name', width: 400, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 400}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(342) ) ) ); } if (x === 349) { return React.createElement( 'div', { label: undefined, width: 33, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 33}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(348) ) ) ); } if (x === 355) { return React.createElement( 'div', { label: undefined, width: 36, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 36}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(354) ) ) ); } if (x === 360) { return React.createElement( 'div', { label: 'Status', width: 60, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 60}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(359) ) ) ); } if (x === 365) { return React.createElement( 'div', { label: 'Delivery', width: 150, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 150}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(364) ) ) ); } if (x === 372) { return React.createElement( 'div', { label: 'Results', width: 140, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 140}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(371) ) ) ); } if (x === 377) { return React.createElement( 'div', { label: 'Cost', width: 140, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 140}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(376) ) ) ); } if (x === 382) { return React.createElement( 'div', { label: 'Reach', width: 80, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 80}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(381) ) ) ); } if (x === 387) { return React.createElement( 'div', { label: 'Impressions', width: 80, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 80}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(386) ) ) ); } if (x === 392) { return React.createElement( 'div', { label: 'Clicks', width: 60, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 60}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(391) ) ) ); } if (x === 397) { return React.createElement( 'div', { label: 'Avg. CPM', width: 80, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 80}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(396) ) ) ); } if (x === 402) { return React.createElement( 'div', { label: 'Avg. CPC', width: 78, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 78}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(401) ) ) ); } if (x === 407) { return React.createElement( 'div', { label: 'CTR %', width: 70, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 70}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(406) ) ) ); } if (x === 412) { return React.createElement( 'div', { label: 'Spent', width: 70, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 70}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(411) ) ) ); } if (x === 417) { return React.createElement( 'div', { label: 'Objective', width: 200, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 200}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(416) ) ) ); } if (x === 422) { return React.createElement( 'div', { label: 'Buying Type', width: 100, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 100}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(421) ) ) ); } if (x === 427) { return React.createElement( 'div', { label: 'Campaign ID', width: 120, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 120}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(426) ) ) ); } if (x === 432) { return React.createElement( 'div', { label: 'Start', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(431) ) ) ); } if (x === 437) { return React.createElement( 'div', { label: 'End', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(436) ) ) ); } if (x === 442) { return React.createElement( 'div', { label: 'Date created', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(441) ) ) ); } if (x === 447) { return React.createElement( 'div', { label: 'Date last edited', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, FixedDataTableSortableHeader149(446) ) ) ); } if (x === 450) { return React.createElement( 'div', { label: 'Tags', width: 150, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 150}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, AdsPETableHeader141(449) ) ) ); } if (x === 453) { return React.createElement( 'div', { label: '', width: 25, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 25}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, AdsPETableHeader141(452) ) ) ); } }; var FixedDataTableCell143 = function (x) { if (x === 317) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 721, left: 0}}, undefined, TransitionCell142(316) ); } if (x === 322) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 798, left: 0}}, undefined, TransitionCell142(321) ); } if (x === 325) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 1022, left: 798}}, undefined, TransitionCell142(324) ); } if (x === 328) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 0, left: 1820}}, undefined, TransitionCell142(327) ); } if (x === 331) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 25, left: 1820}}, undefined, TransitionCell142(330) ); } if (x === 339) { return React.createElement( 'div', { className: '_4lg0 _4lg6 _4h2m', style: {height: 25, width: 42, left: 0}, }, undefined, TransitionCell142(338) ); } if (x === 344) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 400, left: 42}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(343) ); } if (x === 350) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 33, left: 442}}, undefined, TransitionCell142(349) ); } if (x === 356) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 36, left: 475}}, undefined, TransitionCell142(355) ); } if (x === 361) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 60, left: 511}}, undefined, TransitionCell142(360) ); } if (x === 366) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 150, left: 571}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(365) ); } if (x === 373) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 140, left: 0}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(372) ); } if (x === 378) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 140, left: 140}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(377) ); } if (x === 383) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 80, left: 280}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(382) ); } if (x === 388) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 80, left: 360}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(387) ); } if (x === 393) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 60, left: 440}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(392) ); } if (x === 398) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 80, left: 500}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(397) ); } if (x === 403) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 78, left: 580}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(402) ); } if (x === 408) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 70, left: 658}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(407) ); } if (x === 413) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 70, left: 728}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(412) ); } if (x === 418) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 200, left: 798}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(417) ); } if (x === 423) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 100, left: 998}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(422) ); } if (x === 428) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 120, left: 1098}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(427) ); } if (x === 433) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1218}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(432) ); } if (x === 438) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1331}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(437) ); } if (x === 443) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1444}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(442) ); } if (x === 448) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1557}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(447) ); } if (x === 451) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 150, left: 1670}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), TransitionCell142(450) ); } if (x === 454) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 25, left: 1820}}, undefined, TransitionCell142(453) ); } }; var FixedDataTableCellGroupImpl144 = function (x) { if (x === 318) { return React.createElement( 'div', { className: '_3pzj', style: { height: 40, position: 'absolute', width: 721, zIndex: 2, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, FixedDataTableCell143(317) ); } if (x === 332) { return React.createElement( 'div', { className: '_3pzj', style: { height: 40, position: 'absolute', width: 1845, zIndex: 0, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, FixedDataTableCell143(322), FixedDataTableCell143(325), FixedDataTableCell143(328), FixedDataTableCell143(331) ); } if (x === 367) { return React.createElement( 'div', { className: '_3pzj', style: { height: 25, position: 'absolute', width: 721, zIndex: 2, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, FixedDataTableCell143(339), FixedDataTableCell143(344), FixedDataTableCell143(350), FixedDataTableCell143(356), FixedDataTableCell143(361), FixedDataTableCell143(366) ); } if (x === 455) { return React.createElement( 'div', { className: '_3pzj', style: { height: 25, position: 'absolute', width: 1845, zIndex: 0, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, FixedDataTableCell143(373), FixedDataTableCell143(378), FixedDataTableCell143(383), FixedDataTableCell143(388), FixedDataTableCell143(393), FixedDataTableCell143(398), FixedDataTableCell143(403), FixedDataTableCell143(408), FixedDataTableCell143(413), FixedDataTableCell143(418), FixedDataTableCell143(423), FixedDataTableCell143(428), FixedDataTableCell143(433), FixedDataTableCell143(438), FixedDataTableCell143(443), FixedDataTableCell143(448), FixedDataTableCell143(451), FixedDataTableCell143(454) ); } }; var FixedDataTableCellGroup145 = function (x) { if (x === 319) { return React.createElement( 'div', {style: {height: 40, left: 0}, className: '_3pzk'}, FixedDataTableCellGroupImpl144(318) ); } if (x === 333) { return React.createElement( 'div', {style: {height: 40, left: 721}, className: '_3pzk'}, FixedDataTableCellGroupImpl144(332) ); } if (x === 368) { return React.createElement( 'div', {style: {height: 25, left: 0}, className: '_3pzk'}, FixedDataTableCellGroupImpl144(367) ); } if (x === 456) { return React.createElement( 'div', {style: {height: 25, left: 721}, className: '_3pzk'}, FixedDataTableCellGroupImpl144(455) ); } }; var FixedDataTableRowImpl146 = function (x) { if (x === 334) { return React.createElement( 'div', { className: '_1gd4 _4li _52no _3h1a _1mib', onClick: null, onDoubleClick: null, onMouseDown: null, onMouseEnter: null, onMouseLeave: null, style: {width: 1209, height: 40}, }, React.createElement( 'div', {className: '_1gd5'}, FixedDataTableCellGroup145(319), FixedDataTableCellGroup145(333), React.createElement('div', { className: '_1gd6 _1gd8', style: {left: 721, height: 40}, }) ) ); } if (x === 457) { return React.createElement( 'div', { className: '_1gd4 _4li _3h1a _1mib', onClick: null, onDoubleClick: null, onMouseDown: null, onMouseEnter: null, onMouseLeave: null, style: {width: 1209, height: 25}, }, React.createElement( 'div', {className: '_1gd5'}, FixedDataTableCellGroup145(368), FixedDataTableCellGroup145(456), React.createElement('div', { className: '_1gd6 _1gd8', style: {left: 721, height: 25}, }) ) ); } }; var FixedDataTableRow147 = function (x) { if (x === 335) { return React.createElement( 'div', { style: { width: 1209, height: 40, zIndex: 1, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, className: '_1gda', }, FixedDataTableRowImpl146(334) ); } if (x === 458) { return React.createElement( 'div', { style: { width: 1209, height: 25, zIndex: 1, transform: 'translate3d(0px,40px,0)', backfaceVisibility: 'hidden', }, className: '_1gda', }, FixedDataTableRowImpl146(457) ); } }; var FixedDataTableAbstractSortableHeader148 = function (x) { if (x === 341) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(340) ) ); } if (x === 347) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _1kst _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(346) ) ); } if (x === 353) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _1kst _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(352) ) ); } if (x === 358) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(357) ) ); } if (x === 363) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _54_9 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(362) ) ); } if (x === 370) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(369) ) ); } if (x === 375) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(374) ) ); } if (x === 380) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(379) ) ); } if (x === 385) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(384) ) ); } if (x === 390) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(389) ) ); } if (x === 395) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(394) ) ); } if (x === 400) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(399) ) ); } if (x === 405) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(404) ) ); } if (x === 410) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(409) ) ); } if (x === 415) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(414) ) ); } if (x === 420) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(419) ) ); } if (x === 425) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(424) ) ); } if (x === 430) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(429) ) ); } if (x === 435) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(434) ) ); } if (x === 440) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(439) ) ); } if (x === 445) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, AdsPETableHeader141(444) ) ); } }; var FixedDataTableSortableHeader149 = function (x) { if (x === 342) { return FixedDataTableAbstractSortableHeader148(341); } if (x === 348) { return FixedDataTableAbstractSortableHeader148(347); } if (x === 354) { return FixedDataTableAbstractSortableHeader148(353); } if (x === 359) { return FixedDataTableAbstractSortableHeader148(358); } if (x === 364) { return FixedDataTableAbstractSortableHeader148(363); } if (x === 371) { return FixedDataTableAbstractSortableHeader148(370); } if (x === 376) { return FixedDataTableAbstractSortableHeader148(375); } if (x === 381) { return FixedDataTableAbstractSortableHeader148(380); } if (x === 386) { return FixedDataTableAbstractSortableHeader148(385); } if (x === 391) { return FixedDataTableAbstractSortableHeader148(390); } if (x === 396) { return FixedDataTableAbstractSortableHeader148(395); } if (x === 401) { return FixedDataTableAbstractSortableHeader148(400); } if (x === 406) { return FixedDataTableAbstractSortableHeader148(405); } if (x === 411) { return FixedDataTableAbstractSortableHeader148(410); } if (x === 416) { return FixedDataTableAbstractSortableHeader148(415); } if (x === 421) { return FixedDataTableAbstractSortableHeader148(420); } if (x === 426) { return FixedDataTableAbstractSortableHeader148(425); } if (x === 431) { return FixedDataTableAbstractSortableHeader148(430); } if (x === 436) { return FixedDataTableAbstractSortableHeader148(435); } if (x === 441) { return FixedDataTableAbstractSortableHeader148(440); } if (x === 446) { return FixedDataTableAbstractSortableHeader148(445); } }; var FixedDataTableBufferedRows150 = function (x) { if (x === 459) { return React.createElement('div', { style: { position: 'absolute', pointerEvents: 'auto', transform: 'translate3d(0px,65px,0)', backfaceVisibility: 'hidden', }, }); } }; var Scrollbar151 = function (x) { if (x === 460) { return null; } if (x === 461) { return React.createElement( 'div', { onFocus: function () {}, onBlur: function () {}, onKeyDown: function () {}, onMouseDown: function () {}, onWheel: function () {}, className: '_1t0r _1t0t _4jdr _1t0u', style: {width: 1209, zIndex: 99}, tabIndex: 0, }, React.createElement('div', { className: '_1t0w _1t0y _1t0_', style: { width: 561.6340607950117, transform: 'translate3d(4px,0px,0)', backfaceVisibility: 'hidden', }, }) ); } }; var HorizontalScrollbar152 = function (x) { if (x === 462) { return React.createElement( 'div', {className: '_3h1k _3h1m', style: {height: 15, width: 1209}}, React.createElement( 'div', { style: { height: 15, position: 'absolute', overflow: 'hidden', width: 1209, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, Scrollbar151(461) ) ); } }; var FixedDataTable153 = function (x) { if (x === 463) { return React.createElement( 'div', { className: '_3h1i _1mie', onWheel: function () {}, style: {height: 25, width: 1209}, }, React.createElement( 'div', {className: '_3h1j', style: {height: 8, width: 1209}}, FixedDataTableColumnResizeHandle140(313), FixedDataTableRow147(335), FixedDataTableRow147(458), FixedDataTableBufferedRows150(459), null, undefined, React.createElement('div', { className: '_3h1e _3h1h', style: {top: 8}, }) ), Scrollbar151(460), HorizontalScrollbar152(462) ); } }; var TransitionTable154 = function (x) { if (x === 464) { return FixedDataTable153(463); } }; var AdsSelectableFixedDataTable155 = function (x) { if (x === 465) { return React.createElement( 'div', {className: '_5hht'}, TransitionTable154(464) ); } }; var AdsDataTableKeyboardSupportDecorator156 = function (x) { if (x === 466) { return React.createElement( 'div', {className: '_5d6f', tabIndex: '0', onKeyDown: function () {}}, AdsSelectableFixedDataTable155(465) ); } }; var AdsEditableDataTableDecorator157 = function (x) { if (x === 467) { return React.createElement( 'div', {onCopy: function () {}}, AdsDataTableKeyboardSupportDecorator156(466) ); } }; var AdsPEDataTableContainer158 = function (x) { if (x === 468) { return React.createElement( 'div', {className: '_35l_ _1hr clearfix'}, null, null, null, AdsEditableDataTableDecorator157(467) ); } }; var AdsPECampaignGroupTableContainer159 = function (x) { if (x === 470) { return ResponsiveBlock37(469); } }; var AdsPEManageAdsPaneContainer160 = function (x) { if (x === 473) { return React.createElement( 'div', null, AdsErrorBoundary10(65), React.createElement( 'div', {className: '_2uty'}, AdsErrorBoundary10(125) ), React.createElement( 'div', {className: '_2utx _21oc'}, AdsErrorBoundary10(171), React.createElement( 'div', {className: '_41tu'}, AdsErrorBoundary10(176), AdsErrorBoundary10(194) ) ), React.createElement( 'div', {className: '_2utz', style: {height: 25}}, AdsErrorBoundary10(302), React.createElement( 'div', {className: '_2ut-'}, AdsErrorBoundary10(312) ), React.createElement( 'div', {className: '_2ut_'}, AdsErrorBoundary10(472) ) ) ); } }; var AdsPEContentContainer161 = function (x) { if (x === 474) { return AdsPEManageAdsPaneContainer160(473); } }; var FluxContainer_AdsPEWorkspaceContainer_162 = function (x) { if (x === 477) { return React.createElement( 'div', {className: '_49wu', style: {height: 177, top: 43, width: 1306}}, ResponsiveBlock37(62, '0'), AdsErrorBoundary10(476, '1'), null ); } }; var FluxContainer_AdsSessionExpiredDialogContainer_163 = function (x) { if (x === 478) { return null; } }; var FluxContainer_AdsPEUploadDialogLazyContainer_164 = function (x) { if (x === 479) { return null; } }; var FluxContainer_DialogContainer_165 = function (x) { if (x === 480) { return null; } }; var AdsBugReportContainer166 = function (x) { if (x === 481) { return React.createElement('span', null); } }; var AdsPEAudienceSplittingDialog167 = function (x) { if (x === 482) { return null; } }; var AdsPEAudienceSplittingDialogContainer168 = function (x) { if (x === 483) { return React.createElement( 'div', null, AdsPEAudienceSplittingDialog167(482) ); } }; var FluxContainer_AdsRuleDialogBootloadContainer_169 = function (x) { if (x === 484) { return null; } }; var FluxContainer_AdsPECFTrayContainer_170 = function (x) { if (x === 485) { return null; } }; var FluxContainer_AdsPEDeleteDraftContainer_171 = function (x) { if (x === 486) { return null; } }; var FluxContainer_AdsPEInitialDraftPublishDialogContainer_172 = function (x) { if (x === 487) { return null; } }; var FluxContainer_AdsPEReachFrequencyStatusTransitionDialogBootloadContainer_173 = function (x) { if (x === 488) { return null; } }; var FluxContainer_AdsPEPurgeArchiveDialogContainer_174 = function (x) { if (x === 489) { return null; } }; var AdsPECreateDialogContainer175 = function (x) { if (x === 490) { return React.createElement('span', null); } }; var FluxContainer_AdsPEModalStatusContainer_176 = function (x) { if (x === 491) { return null; } }; var FluxContainer_AdsBrowserExtensionErrorDialogContainer_177 = function (x) { if (x === 492) { return null; } }; var FluxContainer_AdsPESortByErrorTipContainer_178 = function (x) { if (x === 493) { return null; } }; var LeadDownloadDialogSelector179 = function (x) { if (x === 494) { return null; } }; var FluxContainer_AdsPELeadDownloadDialogContainerClass_180 = function (x) { if (x === 495) { return LeadDownloadDialogSelector179(494); } }; var AdsPEContainer181 = function (x) { if (x === 496) { return React.createElement( 'div', {id: 'ads_pe_container'}, FluxContainer_AdsPETopNavContainer_26(41), null, FluxContainer_AdsPEWorkspaceContainer_162(477), FluxContainer_AdsSessionExpiredDialogContainer_163(478), FluxContainer_AdsPEUploadDialogLazyContainer_164(479), FluxContainer_DialogContainer_165(480), AdsBugReportContainer166(481), AdsPEAudienceSplittingDialogContainer168(483), FluxContainer_AdsRuleDialogBootloadContainer_169(484), FluxContainer_AdsPECFTrayContainer_170(485), React.createElement( 'span', null, FluxContainer_AdsPEDeleteDraftContainer_171(486), FluxContainer_AdsPEInitialDraftPublishDialogContainer_172(487), FluxContainer_AdsPEReachFrequencyStatusTransitionDialogBootloadContainer_173( 488 ) ), FluxContainer_AdsPEPurgeArchiveDialogContainer_174(489), AdsPECreateDialogContainer175(490), FluxContainer_AdsPEModalStatusContainer_176(491), FluxContainer_AdsBrowserExtensionErrorDialogContainer_177(492), FluxContainer_AdsPESortByErrorTipContainer_178(493), FluxContainer_AdsPELeadDownloadDialogContainerClass_180(495), React.createElement('div', {id: 'web_ads_guidance_tips'}) ); } }; var Benchmark = function (x) { if (x === undefined) { return AdsPEContainer181(496); } }; var app = document.getElementById('app'); window.render = function render() { ReactDOM.render(Benchmark(), app); }; })();
23.163633
87
0.47544
null
/** * 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. */ 'use strict'; const execFileSync = require('child_process').execFileSync; const exec = (command, args) => { console.log('> ' + [command].concat(args).join(' ')); const options = { cwd: process.cwd(), env: process.env, stdio: 'pipe', encoding: 'utf-8', }; return execFileSync(command, args, options); }; const execGitCmd = args => exec('git', args).trim().toString().split('\n'); const listChangedFiles = () => { const mergeBase = execGitCmd(['merge-base', 'HEAD', 'main']); return new Set([ ...execGitCmd(['diff', '--name-only', '--diff-filter=ACMRTUB', mergeBase]), ...execGitCmd(['ls-files', '--others', '--exclude-standard']), ]); }; module.exports = listChangedFiles;
26.484848
79
0.635762
cybersecurity-penetration-testing
/** * 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 strict */ import type {PublicInstance} from './ReactNativePrivateInterface'; import {getNodeFromInternalInstanceHandle} from '../../../../ReactNativePublicCompat'; export default function getNodeFromPublicInstance( publicInstance: PublicInstance, ) { return getNodeFromInternalInstanceHandle( publicInstance.__internalInstanceHandle, ); }
25.333333
86
0.753623
owtf
/** * 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. * * @emails react-core */ 'use strict'; /** * Touch events state machine. * * Keeps track of the active pointers and allows them to be reflected in touch events. */ const activeTouches = new Map(); export function addTouch(touch) { const identifier = touch.identifier; const target = touch.target; if (!activeTouches.has(target)) { activeTouches.set(target, new Map()); } if (activeTouches.get(target).get(identifier)) { // Do not allow existing touches to be overwritten console.error( 'Touch with identifier %s already exists. Did not record touch start.', identifier, ); } else { activeTouches.get(target).set(identifier, touch); } } export function updateTouch(touch) { const identifier = touch.identifier; const target = touch.target; if (activeTouches.get(target) != null) { activeTouches.get(target).set(identifier, touch); } else { console.error( 'Touch with identifier %s does not exist. Cannot record touch move without a touch start.', identifier, ); } } export function removeTouch(touch) { const identifier = touch.identifier; const target = touch.target; if (activeTouches.get(target) != null) { if (activeTouches.get(target).has(identifier)) { activeTouches.get(target).delete(identifier); } else { console.error( 'Touch with identifier %s does not exist. Cannot record touch end without a touch start.', identifier, ); } } } export function getTouches() { const touches = []; activeTouches.forEach((_, target) => { touches.push(...getTargetTouches(target)); }); return touches; } export function getTargetTouches(target) { if (activeTouches.get(target) != null) { return Array.from(activeTouches.get(target).values()); } return []; } export function clear() { activeTouches.clear(); }
23.855422
98
0.674103
Penetration-Testing-Study-Notes
/** * 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. * @typechecks * * Example usage: * <Circle * radius={10} * stroke="green" * strokeWidth={3} * fill="blue" * /> * */ 'use strict'; var assign = Object.assign; var PropTypes = require('prop-types'); var React = require('react'); var ReactART = require('react-art'); var createReactClass = require('create-react-class'); var Path = ReactART.Path; var Shape = ReactART.Shape; /** * Circle is a React component for drawing circles. Like other ReactART * components, it must be used in a <Surface>. */ var Circle = createReactClass({ displayName: 'Circle', propTypes: { radius: PropTypes.number.isRequired, }, render: function render() { var radius = this.props.radius; var path = Path() .moveTo(0, -radius) .arc(0, radius * 2, radius) .arc(0, radius * -2, radius) .close(); return React.createElement(Shape, assign({}, this.props, {d: path})); }, }); module.exports = Circle;
20.111111
73
0.645303
Broken-Droid-Factory
/** * 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. * * @emails react-core */ 'use strict'; import {insertNodesAndExecuteScripts} from 'react-dom/src/test-utils/FizzTestUtils'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; global.TextDecoder = require('util').TextDecoder; // Don't wait before processing work on the server. // TODO: we can replace this with FlightServer.act(). global.setTimeout = cb => cb(); let container; let serverExports; let turbopackServerMap; let React; let ReactDOMServer; let ReactServerDOMServer; let ReactServerDOMClient; describe('ReactFlightDOMForm', () => { beforeEach(() => { jest.resetModules(); // Simulate the condition resolution jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-server-dom-turbopack/server', () => require('react-server-dom-turbopack/server.edge'), ); ReactServerDOMServer = require('react-server-dom-turbopack/server.edge'); const TurbopackMock = require('./utils/TurbopackMock'); serverExports = TurbopackMock.serverExports; turbopackServerMap = TurbopackMock.turbopackServerMap; __unmockReact(); jest.resetModules(); React = require('react'); ReactServerDOMClient = require('react-server-dom-turbopack/client.edge'); ReactDOMServer = require('react-dom/server.edge'); container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); }); async function POST(formData) { const boundAction = await ReactServerDOMServer.decodeAction( formData, turbopackServerMap, ); return boundAction(); } function submit(submitter) { const form = submitter.form || submitter; if (!submitter.form) { submitter = undefined; } const submitEvent = new Event('submit', {bubbles: true, cancelable: true}); submitEvent.submitter = submitter; const returnValue = form.dispatchEvent(submitEvent); if (!returnValue) { return; } const action = (submitter && submitter.getAttribute('formaction')) || form.action; if (!/\s*javascript:/i.test(action)) { const method = (submitter && submitter.formMethod) || form.method; const encType = (submitter && submitter.formEnctype) || form.enctype; if (method === 'post' && encType === 'multipart/form-data') { let formData; if (submitter) { const temp = document.createElement('input'); temp.name = submitter.name; temp.value = submitter.value; submitter.parentNode.insertBefore(temp, submitter); formData = new FormData(form); temp.parentNode.removeChild(temp); } else { formData = new FormData(form); } return POST(formData); } throw new Error('Navigate to: ' + action); } } async function readIntoContainer(stream) { const reader = stream.getReader(); let result = ''; while (true) { const {done, value} = await reader.read(); if (done) { break; } result += Buffer.from(value).toString('utf8'); } const temp = document.createElement('div'); temp.innerHTML = result; insertNodesAndExecuteScripts(temp, container, null); } // @gate enableFormActions it('can submit a passed server action without hydrating it', async () => { let foo = null; const serverAction = serverExports(function action(formData) { foo = formData.get('foo'); return 'hello'; }); function App() { return ( <form action={serverAction}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const rscStream = ReactServerDOMServer.renderToReadableStream(<App />); const response = ReactServerDOMClient.createFromReadableStream(rscStream, { ssrManifest: { moduleMap: null, moduleLoading: null, }, }); const ssrStream = await ReactDOMServer.renderToReadableStream(response); await readIntoContainer(ssrStream); const form = container.firstChild; expect(foo).toBe(null); const result = await submit(form); expect(result).toBe('hello'); expect(foo).toBe('bar'); }); });
29.38255
84
0.656871
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "ComponentUsingHooksIndirectly", { enumerable: true, get: function () { return _ComponentUsingHooksIndirectly.Component; } }); Object.defineProperty(exports, "ComponentWithCustomHook", { enumerable: true, get: function () { return _ComponentWithCustomHook.Component; } }); Object.defineProperty(exports, "ComponentWithExternalCustomHooks", { enumerable: true, get: function () { return _ComponentWithExternalCustomHooks.Component; } }); Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", { enumerable: true, get: function () { return _ComponentWithMultipleHooksPerLine.Component; } }); Object.defineProperty(exports, "ComponentWithNestedHooks", { enumerable: true, get: function () { return _ComponentWithNestedHooks.Component; } }); Object.defineProperty(exports, "ContainingStringSourceMappingURL", { enumerable: true, get: function () { return _ContainingStringSourceMappingURL.Component; } }); Object.defineProperty(exports, "Example", { enumerable: true, get: function () { return _Example.Component; } }); Object.defineProperty(exports, "InlineRequire", { enumerable: true, get: function () { return _InlineRequire.Component; } }); Object.defineProperty(exports, "useTheme", { enumerable: true, get: function () { return _useTheme.default; } }); exports.ToDoList = void 0; var _ComponentUsingHooksIndirectly = require("./ComponentUsingHooksIndirectly"); var _ComponentWithCustomHook = require("./ComponentWithCustomHook"); var _ComponentWithExternalCustomHooks = require("./ComponentWithExternalCustomHooks"); var _ComponentWithMultipleHooksPerLine = require("./ComponentWithMultipleHooksPerLine"); var _ComponentWithNestedHooks = require("./ComponentWithNestedHooks"); var _ContainingStringSourceMappingURL = require("./ContainingStringSourceMappingURL"); var _Example = require("./Example"); var _InlineRequire = require("./InlineRequire"); var ToDoList = _interopRequireWildcard(require("./ToDoList")); exports.ToDoList = ToDoList; var _useTheme = _interopRequireDefault(require("./useTheme")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } //# sourceMappingURL=index.js.map?foo=bar&param=some_value
36.325843
743
0.727793
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } // ?sourceMappingURL=([^\s'"]+)/gm function Component() { const [count, setCount] = (0, _react.useState)(0); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 18, columnNumber: 5 } }, /*#__PURE__*/_react.default.createElement("p", { __source: { fileName: _jsxFileName, lineNumber: 19, columnNumber: 7 } }, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", { onClick: () => setCount(count + 1), __source: { fileName: _jsxFileName, lineNumber: 20, columnNumber: 7 } }, "Click me")); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbnRhaW5pbmdTdHJpbmdTb3VyY2VNYXBwaW5nVVJMLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFFQTtBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuLy8gP3NvdXJjZU1hcHBpbmdVUkw9KFteXFxzJ1wiXSspL2dtXG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IFtjb3VudCwgc2V0Q291bnRdID0gdXNlU3RhdGUoMCk7XG5cbiAgcmV0dXJuIChcbiAgICA8ZGl2PlxuICAgICAgPHA+WW91IGNsaWNrZWQge2NvdW50fSB0aW1lczwvcD5cbiAgICAgIDxidXR0b24gb25DbGljaz17KCkgPT4gc2V0Q291bnQoY291bnQgKyAxKX0+Q2xpY2sgbWU8L2J1dHRvbj5cbiAgICA8L2Rpdj5cbiAgKTtcbn1cbiJdLCJ4X2ZhY2Vib29rX3NvdXJjZXMiOltbbnVsbCxbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJjb3VudCJdLCJtYXBwaW5ncyI6IkNBQUQ7ZTRCQ0EsQVdEQSJ9XV1dfQ==
80.85
1,480
0.798656
cybersecurity-penetration-testing
/** * 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 {Lane, Lanes} from './ReactFiberLane'; import type {Wakeable} from 'shared/ReactTypes'; import {enableDebugTracing} from 'shared/ReactFeatureFlags'; const nativeConsole: Object = console; let nativeConsoleLog: null | Function = null; const pendingGroupArgs: Array<any> = []; let printedGroupIndex: number = -1; function formatLanes(laneOrLanes: Lane | Lanes): string { return '0b' + (laneOrLanes: any).toString(2).padStart(31, '0'); } function group(...groupArgs: Array<string>): void { pendingGroupArgs.push(groupArgs); if (nativeConsoleLog === null) { nativeConsoleLog = nativeConsole.log; nativeConsole.log = log; } } function groupEnd(): void { pendingGroupArgs.pop(); while (printedGroupIndex >= pendingGroupArgs.length) { nativeConsole.groupEnd(); printedGroupIndex--; } if (pendingGroupArgs.length === 0) { nativeConsole.log = nativeConsoleLog; nativeConsoleLog = null; } } function log(...logArgs: Array<mixed>): void { if (printedGroupIndex < pendingGroupArgs.length - 1) { for (let i = printedGroupIndex + 1; i < pendingGroupArgs.length; i++) { const groupArgs = pendingGroupArgs[i]; nativeConsole.group(...groupArgs); } printedGroupIndex = pendingGroupArgs.length - 1; } if (typeof nativeConsoleLog === 'function') { nativeConsoleLog(...logArgs); } else { nativeConsole.log(...logArgs); } } const REACT_LOGO_STYLE = 'background-color: #20232a; color: #61dafb; padding: 0 2px;'; export function logCommitStarted(lanes: Lanes): void { if (__DEV__) { if (enableDebugTracing) { group( `%c⚛️%c commit%c (${formatLanes(lanes)})`, REACT_LOGO_STYLE, '', 'font-weight: normal;', ); } } } export function logCommitStopped(): void { if (__DEV__) { if (enableDebugTracing) { groupEnd(); } } } const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // $FlowFixMe[incompatible-type]: Flow cannot handle polymorphic WeakMaps const wakeableIDs: WeakMap<Wakeable, number> = new PossiblyWeakMap(); let wakeableID: number = 0; function getWakeableID(wakeable: Wakeable): number { if (!wakeableIDs.has(wakeable)) { wakeableIDs.set(wakeable, wakeableID++); } return ((wakeableIDs.get(wakeable): any): number); } export function logComponentSuspended( componentName: string, wakeable: Wakeable, ): void { if (__DEV__) { if (enableDebugTracing) { const id = getWakeableID(wakeable); const display = (wakeable: any).displayName || wakeable; log( `%c⚛️%c ${componentName} suspended`, REACT_LOGO_STYLE, 'color: #80366d; font-weight: bold;', id, display, ); wakeable.then( () => { log( `%c⚛️%c ${componentName} resolved`, REACT_LOGO_STYLE, 'color: #80366d; font-weight: bold;', id, display, ); }, () => { log( `%c⚛️%c ${componentName} rejected`, REACT_LOGO_STYLE, 'color: #80366d; font-weight: bold;', id, display, ); }, ); } } } export function logLayoutEffectsStarted(lanes: Lanes): void { if (__DEV__) { if (enableDebugTracing) { group( `%c⚛️%c layout effects%c (${formatLanes(lanes)})`, REACT_LOGO_STYLE, '', 'font-weight: normal;', ); } } } export function logLayoutEffectsStopped(): void { if (__DEV__) { if (enableDebugTracing) { groupEnd(); } } } export function logPassiveEffectsStarted(lanes: Lanes): void { if (__DEV__) { if (enableDebugTracing) { group( `%c⚛️%c passive effects%c (${formatLanes(lanes)})`, REACT_LOGO_STYLE, '', 'font-weight: normal;', ); } } } export function logPassiveEffectsStopped(): void { if (__DEV__) { if (enableDebugTracing) { groupEnd(); } } } export function logRenderStarted(lanes: Lanes): void { if (__DEV__) { if (enableDebugTracing) { group( `%c⚛️%c render%c (${formatLanes(lanes)})`, REACT_LOGO_STYLE, '', 'font-weight: normal;', ); } } } export function logRenderStopped(): void { if (__DEV__) { if (enableDebugTracing) { groupEnd(); } } } export function logForceUpdateScheduled( componentName: string, lane: Lane, ): void { if (__DEV__) { if (enableDebugTracing) { log( `%c⚛️%c ${componentName} forced update %c(${formatLanes(lane)})`, REACT_LOGO_STYLE, 'color: #db2e1f; font-weight: bold;', '', ); } } } export function logStateUpdateScheduled( componentName: string, lane: Lane, payloadOrAction: any, ): void { if (__DEV__) { if (enableDebugTracing) { log( `%c⚛️%c ${componentName} updated state %c(${formatLanes(lane)})`, REACT_LOGO_STYLE, 'color: #01a252; font-weight: bold;', '', payloadOrAction, ); } } }
21.862069
75
0.588535
null
'use strict'; const { existsSync, readdirSync, unlinkSync, readFileSync, writeFileSync, } = require('fs'); const path = require('path'); const Bundles = require('./bundles'); const { asyncCopyTo, asyncExecuteCommand, asyncExtractTar, asyncRimRaf, } = require('./utils'); const {getSigningToken, signFile} = require('signedsource'); const { NODE_ES2015, ESM_DEV, ESM_PROD, UMD_DEV, UMD_PROD, UMD_PROFILING, NODE_DEV, NODE_PROD, NODE_PROFILING, BUN_DEV, BUN_PROD, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, BROWSER_SCRIPT, } = Bundles.bundleTypes; function getPackageName(name) { if (name.indexOf('/') !== -1) { return name.split('/')[0]; } return name; } function getBundleOutputPath(bundle, bundleType, filename, packageName) { switch (bundleType) { case NODE_ES2015: return `build/node_modules/${packageName}/cjs/${filename}`; case ESM_DEV: case ESM_PROD: return `build/node_modules/${packageName}/esm/${filename}`; case BUN_DEV: case BUN_PROD: return `build/node_modules/${packageName}/cjs/${filename}`; case NODE_DEV: case NODE_PROD: case NODE_PROFILING: return `build/node_modules/${packageName}/cjs/${filename}`; case UMD_DEV: case UMD_PROD: case UMD_PROFILING: return `build/node_modules/${packageName}/umd/${filename}`; case FB_WWW_DEV: case FB_WWW_PROD: case FB_WWW_PROFILING: return `build/facebook-www/${filename}`; case RN_OSS_DEV: case RN_OSS_PROD: case RN_OSS_PROFILING: switch (packageName) { case 'react-native-renderer': return `build/react-native/implementations/${filename}`; default: throw new Error('Unknown RN package.'); } case RN_FB_DEV: case RN_FB_PROD: case RN_FB_PROFILING: switch (packageName) { case 'scheduler': case 'react': case 'react-is': case 'react-test-renderer': return `build/facebook-react-native/${packageName}/cjs/${filename}`; case 'react-native-renderer': return `build/react-native/implementations/${filename.replace( /\.js$/, '.fb.js' )}`; default: throw new Error('Unknown RN package.'); } case BROWSER_SCRIPT: { // Bundles that are served as browser scripts need to be able to be sent // straight to the browser with any additional bundling. We shouldn't use // a module to re-export. Depending on how they are served, they also may // not go through package.json module resolution, so we shouldn't rely on // that either. We should consider the output path as part of the public // contract, and explicitly specify its location within the package's // directory structure. const outputPath = bundle.outputPath; if (!outputPath) { throw new Error( 'Bundles with type BROWSER_SCRIPT must specific an explicit ' + 'output path.' ); } return `build/node_modules/${packageName}/${outputPath}`; } default: throw new Error('Unknown bundle type.'); } } async function copyWWWShims() { await asyncCopyTo( `${__dirname}/shims/facebook-www`, 'build/facebook-www/shims' ); } async function copyRNShims() { await asyncCopyTo( `${__dirname}/shims/react-native`, 'build/react-native/shims' ); await asyncCopyTo( require.resolve('react-native-renderer/src/ReactNativeTypes.js'), 'build/react-native/shims/ReactNativeTypes.js' ); processGenerated('build/react-native/shims'); } function processGenerated(directory) { const files = readdirSync(directory) .filter(dir => dir.endsWith('.js')) .map(file => path.join(directory, file)); files.forEach(file => { const originalContents = readFileSync(file, 'utf8'); const contents = originalContents // Replace {@}format with {@}noformat .replace(/(\r?\n\s*\*\s*)@format\b.*(\n)/, '$1@noformat$2') // Add {@}nolint and {@}generated .replace(/(\r?\n\s*\*)\//, `$1 @nolint$1 ${getSigningToken()}$1/`); const signedContents = signFile(contents); writeFileSync(file, signedContents, 'utf8'); }); } async function copyAllShims() { await Promise.all([copyWWWShims(), copyRNShims()]); } function getTarOptions(tgzName, packageName) { // Files inside the `npm pack`ed archive start // with "package/" in their paths. We'll undo // this during extraction. const CONTENTS_FOLDER = 'package'; return { src: tgzName, dest: `build/node_modules/${packageName}`, tar: { entries: [CONTENTS_FOLDER], map(header) { if (header.name.indexOf(CONTENTS_FOLDER + '/') === 0) { header.name = header.name.slice(CONTENTS_FOLDER.length + 1); } }, }, }; } let entryPointsToHasBundle = new Map(); // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const bundle of Bundles.bundles) { let hasBundle = entryPointsToHasBundle.get(bundle.entry); if (!hasBundle) { const hasNonFBBundleTypes = bundle.bundleTypes.some( type => type !== FB_WWW_DEV && type !== FB_WWW_PROD && type !== FB_WWW_PROFILING ); entryPointsToHasBundle.set(bundle.entry, hasNonFBBundleTypes); } } function filterOutEntrypoints(name) { // Remove entry point files that are not built in this configuration. let jsonPath = `build/node_modules/${name}/package.json`; let packageJSON = JSON.parse(readFileSync(jsonPath)); let files = packageJSON.files; let exportsJSON = packageJSON.exports; let browserJSON = packageJSON.browser; if (!Array.isArray(files)) { throw new Error('expected all package.json files to contain a files field'); } let changed = false; for (let i = 0; i < files.length; i++) { let filename = files[i]; let entry = filename === 'index.js' ? name : name + '/' + filename.replace(/\.js$/, ''); let hasBundle = entryPointsToHasBundle.get(entry); if (hasBundle === undefined) { // This entry doesn't exist in the bundles. Check if something similar exists. hasBundle = entryPointsToHasBundle.get(entry + '.node') || entryPointsToHasBundle.get(entry + '.browser'); } if (hasBundle === undefined) { // This doesn't exist in the bundles. It's an extra file. } else if (hasBundle === true) { // This is built in this release channel. } else { // This doesn't have any bundleTypes in this release channel. // Let's remove it. files.splice(i, 1); i--; unlinkSync(`build/node_modules/${name}/${filename}`); changed = true; // Remove it from the exports field too if it exists. if (exportsJSON) { if (filename === 'index.js') { delete exportsJSON['.']; } else { delete exportsJSON['./' + filename.replace(/\.js$/, '')]; } } if (browserJSON) { delete browserJSON['./' + filename]; } } // We only export the source directory so Jest and Rollup can access them // during local development and at build time. The files don't exist in the // public builds, so we don't need the export entry, either. const sourceWildcardExport = './src/*'; if (exportsJSON && exportsJSON[sourceWildcardExport]) { delete exportsJSON[sourceWildcardExport]; changed = true; } } if (changed) { let newJSON = JSON.stringify(packageJSON, null, ' '); writeFileSync(jsonPath, newJSON); } } async function prepareNpmPackage(name) { await Promise.all([ asyncCopyTo('LICENSE', `build/node_modules/${name}/LICENSE`), asyncCopyTo( `packages/${name}/package.json`, `build/node_modules/${name}/package.json` ), asyncCopyTo( `packages/${name}/README.md`, `build/node_modules/${name}/README.md` ), asyncCopyTo(`packages/${name}/npm`, `build/node_modules/${name}`), ]); filterOutEntrypoints(name); const tgzName = ( await asyncExecuteCommand(`npm pack build/node_modules/${name}`) ).trim(); await asyncRimRaf(`build/node_modules/${name}`); await asyncExtractTar(getTarOptions(tgzName, name)); unlinkSync(tgzName); } async function prepareNpmPackages() { if (!existsSync('build/node_modules')) { // We didn't build any npm packages. return; } const builtPackageFolders = readdirSync('build/node_modules').filter( dir => dir.charAt(0) !== '.' ); await Promise.all(builtPackageFolders.map(prepareNpmPackage)); } module.exports = { copyAllShims, getPackageName, getBundleOutputPath, prepareNpmPackages, };
28.705085
84
0.635015
cybersecurity-penetration-testing
/** * 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 {Rect} from '../../view-base'; import {rectEqualToRect} from '../../view-base'; import {COLORS, FONT_SIZE, TEXT_PADDING} from '../constants'; const cachedTextWidths = new Map<string, number>(); export function getTextWidth( context: CanvasRenderingContext2D, text: string, ): number { let measuredWidth = cachedTextWidths.get(text); if (measuredWidth == null) { measuredWidth = context.measureText(text).width; cachedTextWidths.set(text, measuredWidth); } return ((measuredWidth: any): number); } export function trimText( context: CanvasRenderingContext2D, text: string, width: number, ): string | null { const maxIndex = text.length - 1; let startIndex = 0; let stopIndex = maxIndex; let longestValidIndex = 0; let longestValidText = null; // Trimming long text could be really slow if we decrease only 1 character at a time. // Trimming with more of a binary search approach is faster in the worst cases. while (startIndex <= stopIndex) { const currentIndex = Math.floor((startIndex + stopIndex) / 2); const trimmedText = currentIndex === maxIndex ? text : text.slice(0, currentIndex) + '…'; if (getTextWidth(context, trimmedText) <= width) { if (longestValidIndex < currentIndex) { longestValidIndex = currentIndex; longestValidText = trimmedText; } startIndex = currentIndex + 1; } else { stopIndex = currentIndex - 1; } } return longestValidText; } type TextConfig = { fillStyle?: string, fontSize?: number, textAlign?: 'left' | 'center', }; export function drawText( text: string, context: CanvasRenderingContext2D, fullRect: Rect, drawableRect: Rect, config?: TextConfig, ): void { const { fillStyle = COLORS.TEXT_COLOR, fontSize = FONT_SIZE, textAlign = 'left', } = config || {}; if (fullRect.size.width > TEXT_PADDING * 2) { context.textAlign = textAlign; context.textBaseline = 'middle'; context.font = `${fontSize}px sans-serif`; const {x, y} = fullRect.origin; const trimmedName = trimText( context, text, fullRect.size.width - TEXT_PADDING * 2 + (x < 0 ? x : 0), ); if (trimmedName !== null) { context.fillStyle = fillStyle; // Prevent text from visibly overflowing its container when clipped. const textOverflowsViewableArea = !rectEqualToRect( drawableRect, fullRect, ); if (textOverflowsViewableArea) { context.save(); context.beginPath(); context.rect( drawableRect.origin.x, drawableRect.origin.y, drawableRect.size.width, drawableRect.size.height, ); context.closePath(); context.clip(); } let textX; if (textAlign === 'center') { textX = x + fullRect.size.width / 2 + TEXT_PADDING - (x < 0 ? x : 0); } else { textX = x + TEXT_PADDING - (x < 0 ? x : 0); } const textY = y + fullRect.size.height / 2; context.fillText(trimmedName, textX, textY); if (textOverflowsViewableArea) { context.restore(); } } } }
23.992593
87
0.630596
null
/** * 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. * * @noflow */ import {REACT_MEMO_TYPE} from 'shared/ReactSymbols'; import isValidElementType from 'shared/isValidElementType'; export function memo<Props>( type: React$ElementType, compare?: (oldProps: Props, newProps: Props) => boolean, ) { if (__DEV__) { if (!isValidElementType(type)) { console.error( 'memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type, ); } } const elementType = { $$typeof: REACT_MEMO_TYPE, type, compare: compare === undefined ? null : compare, }; if (__DEV__) { let ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.memo((props) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!type.name && !type.displayName) { type.displayName = name; } }, }); } return elementType; }
27.931034
88
0.614788
owtf
/** * 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. * */ // Tweak these to play with different kinds of latency. // How long the data fetches on the server. exports.API_DELAY = 2000; // How long the server waits for data before giving up. exports.ABORT_DELAY = 10000; // How long serving the JS bundles is delayed. exports.JS_BUNDLE_DELAY = 4000;
24.736842
66
0.723361
cybersecurity-penetration-testing
/** * 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 {ReactContext} from 'shared/ReactTypes'; import * as React from 'react'; import {createContext, useMemo, useReducer} from 'react'; import type {ReactComponentMeasure, TimelineData, ViewState} from './types'; type State = { profilerData: TimelineData, searchIndex: number, searchRegExp: RegExp | null, searchResults: Array<ReactComponentMeasure>, searchText: string, }; type ACTION_GO_TO_NEXT_SEARCH_RESULT = { type: 'GO_TO_NEXT_SEARCH_RESULT', }; type ACTION_GO_TO_PREVIOUS_SEARCH_RESULT = { type: 'GO_TO_PREVIOUS_SEARCH_RESULT', }; type ACTION_SET_SEARCH_TEXT = { type: 'SET_SEARCH_TEXT', payload: string, }; type Action = | ACTION_GO_TO_NEXT_SEARCH_RESULT | ACTION_GO_TO_PREVIOUS_SEARCH_RESULT | ACTION_SET_SEARCH_TEXT; type Dispatch = (action: Action) => void; const EMPTY_ARRAY: Array<ReactComponentMeasure> = []; function reducer(state: State, action: Action): State { let {searchIndex, searchRegExp, searchResults, searchText} = state; switch (action.type) { case 'GO_TO_NEXT_SEARCH_RESULT': if (searchResults.length > 0) { if (searchIndex === -1 || searchIndex + 1 === searchResults.length) { searchIndex = 0; } else { searchIndex++; } } break; case 'GO_TO_PREVIOUS_SEARCH_RESULT': if (searchResults.length > 0) { if (searchIndex === -1 || searchIndex === 0) { searchIndex = searchResults.length - 1; } else { searchIndex--; } } break; case 'SET_SEARCH_TEXT': searchText = action.payload; searchRegExp = null; searchResults = []; if (searchText !== '') { const safeSearchText = searchText.replace( /[.*+?^${}()|[\]\\]/g, '\\$&', ); searchRegExp = new RegExp(`^${safeSearchText}`, 'i'); // If something is zoomed in on already, and the new search still contains it, // don't change the selection (even if overall search results set changes). let prevSelectedMeasure = null; if (searchIndex >= 0 && searchResults.length > searchIndex) { prevSelectedMeasure = searchResults[searchIndex]; } const componentMeasures = state.profilerData.componentMeasures; let prevSelectedMeasureIndex = -1; for (let i = 0; i < componentMeasures.length; i++) { const componentMeasure = componentMeasures[i]; if (componentMeasure.componentName.match(searchRegExp)) { searchResults.push(componentMeasure); if (componentMeasure === prevSelectedMeasure) { prevSelectedMeasureIndex = searchResults.length - 1; } } } searchIndex = prevSelectedMeasureIndex >= 0 ? prevSelectedMeasureIndex : 0; } break; } return { profilerData: state.profilerData, searchIndex, searchRegExp, searchResults, searchText, }; } export type Context = { profilerData: TimelineData, // Search state dispatch: Dispatch, searchIndex: number, searchRegExp: null, searchResults: Array<ReactComponentMeasure>, searchText: string, }; const TimelineSearchContext: ReactContext<Context> = createContext<Context>( ((null: any): Context), ); TimelineSearchContext.displayName = 'TimelineSearchContext'; type Props = { children: React$Node, profilerData: TimelineData, viewState: ViewState, }; function TimelineSearchContextController({ children, profilerData, viewState, }: Props): React.Node { const [state, dispatch] = useReducer<State, State, Action>(reducer, { profilerData, searchIndex: -1, searchRegExp: null, searchResults: EMPTY_ARRAY, searchText: '', }); const value = useMemo( () => ({ ...state, dispatch, }), [state], ); return ( <TimelineSearchContext.Provider value={value}> {children} </TimelineSearchContext.Provider> ); } export {TimelineSearchContext, TimelineSearchContextController};
24.371257
86
0.639518
cybersecurity-penetration-testing
'use strict'; var l, s; if (process.env.NODE_ENV === 'production') { l = require('./cjs/react-dom-server-legacy.browser.production.min.js'); s = require('./cjs/react-dom-server.browser.production.min.js'); } else { l = require('./cjs/react-dom-server-legacy.browser.development.js'); s = require('./cjs/react-dom-server.browser.development.js'); } exports.version = l.version; exports.renderToString = l.renderToString; exports.renderToStaticMarkup = l.renderToStaticMarkup; exports.renderToNodeStream = l.renderToNodeStream; exports.renderToStaticNodeStream = l.renderToStaticNodeStream; exports.renderToReadableStream = s.renderToReadableStream; if (s.resume) { exports.resume = s.resume; }
32.619048
73
0.751773
cybersecurity-penetration-testing
/** * 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 {ReactNodeList, ReactFormState} from 'shared/ReactTypes'; import type { BootstrapScriptDescriptor, HeadersDescriptor, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; import type {ImportMap} from '../shared/ReactDOMTypes'; import type {ErrorInfo, PostponeInfo} from 'react-server/src/ReactFizzServer'; import ReactVersion from 'shared/ReactVersion'; import { createRequest, startWork, startFlowing, stopFlowing, abort, } from 'react-server/src/ReactFizzServer'; import { createResumableState, createRenderState, createRootFormatContext, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; type Options = { identifierPrefix?: string, namespaceURI?: string, nonce?: string, bootstrapScriptContent?: string, bootstrapScripts?: Array<string | BootstrapScriptDescriptor>, bootstrapModules?: Array<string | BootstrapScriptDescriptor>, progressiveChunkSize?: number, signal?: AbortSignal, onError?: (error: mixed, errorInfo: ErrorInfo) => ?string, onPostpone?: (reason: string, postponeInfo: PostponeInfo) => void, unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor, importMap?: ImportMap, formState?: ReactFormState<any, any> | null, onHeaders?: (headers: Headers) => void, maxHeadersLength?: number, }; // TODO: Move to sub-classing ReadableStream. type ReactDOMServerReadableStream = ReadableStream & { allReady: Promise<void>, }; function renderToReadableStream( children: ReactNodeList, options?: Options, ): Promise<ReactDOMServerReadableStream> { return new Promise((resolve, reject) => { let onFatalError; let onAllReady; const allReady = new Promise<void>((res, rej) => { onAllReady = res; onFatalError = rej; }); function onShellReady() { const stream: ReactDOMServerReadableStream = (new ReadableStream( { type: 'direct', pull: (controller): ?Promise<void> => { // $FlowIgnore startFlowing(request, controller); }, cancel: (reason): ?Promise<void> => { stopFlowing(request); abort(request, reason); }, }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. {highWaterMark: 2048}, ): any); // TODO: Move to sub-classing ReadableStream. stream.allReady = allReady; resolve(stream); } function onShellError(error: mixed) { // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`. // However, `allReady` will be rejected by `onFatalError` as well. // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`. allReady.catch(() => {}); reject(error); } const onHeaders = options ? options.onHeaders : undefined; let onHeadersImpl; if (onHeaders) { onHeadersImpl = (headersDescriptor: HeadersDescriptor) => { onHeaders(new Headers(headersDescriptor)); }; } const resumableState = createResumableState( options ? options.identifierPrefix : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined, ); const request = createRequest( children, resumableState, createRenderState( resumableState, options ? options.nonce : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.importMap : undefined, onHeadersImpl, options ? options.maxHeadersLength : undefined, ), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError, options ? options.onPostpone : undefined, options ? options.formState : undefined, ); if (options && options.signal) { const signal = options.signal; if (signal.aborted) { abort(request, (signal: any).reason); } else { const listener = () => { abort(request, (signal: any).reason); signal.removeEventListener('abort', listener); }; signal.addEventListener('abort', listener); } } startWork(request); }); } function renderToNodeStream() { throw new Error( 'ReactDOMServer.renderToNodeStream(): The Node Stream API is not available ' + 'in Bun. Use ReactDOMServer.renderToReadableStream() instead.', ); } function renderToStaticNodeStream() { throw new Error( 'ReactDOMServer.renderToStaticNodeStream(): The Node Stream API is not available ' + 'in Bun. Use ReactDOMServer.renderToReadableStream() instead.', ); } export { renderToReadableStream, renderToNodeStream, renderToStaticNodeStream, ReactVersion as version, };
30.319527
123
0.677816
null
'use strict'; /* eslint-disable no-for-of-loops/no-for-of-loops */ const getComments = require('./getComments'); const GATE_VERSION_STR = '@reactVersion '; const REACT_VERSION_ENV = process.env.REACT_VERSION; function transform(babel) { const {types: t} = babel; // Runs tests conditionally based on the version of react (semver range) we are running // Input: // @reactVersion >= 17.0 // test('some test', () => {/*...*/}) // // Output: // @reactVersion >= 17.0 // _test_react_version('>= 17.0', 'some test', () => {/*...*/}); // // See info about semver ranges here: // https://www.npmjs.com/package/semver function buildGateVersionCondition(comments) { if (!comments) { return null; } const resultingCondition = comments.reduce( (accumulatedCondition, commentLine) => { const commentStr = commentLine.value.trim(); if (!commentStr.startsWith(GATE_VERSION_STR)) { return accumulatedCondition; } const condition = commentStr.slice(GATE_VERSION_STR.length); if (accumulatedCondition === null) { return condition; } return accumulatedCondition.concat(' ', condition); }, null ); if (resultingCondition === null) { return null; } return t.stringLiteral(resultingCondition); } return { name: 'transform-react-version-pragma', visitor: { ExpressionStatement(path) { const statement = path.node; const expression = statement.expression; if (expression.type === 'CallExpression') { const callee = expression.callee; switch (callee.type) { case 'Identifier': { if ( callee.name === 'test' || callee.name === 'it' || callee.name === 'fit' ) { const comments = getComments(path); const condition = buildGateVersionCondition(comments); if (condition !== null) { callee.name = callee.name === 'fit' ? '_test_react_version_focus' : '_test_react_version'; expression.arguments = [condition, ...expression.arguments]; } else if (REACT_VERSION_ENV) { callee.name = '_test_ignore_for_react_version'; } } break; } case 'MemberExpression': { if ( callee.object.type === 'Identifier' && (callee.object.name === 'test' || callee.object.name === 'it') && callee.property.type === 'Identifier' && callee.property.name === 'only' ) { const comments = getComments(path); const condition = buildGateVersionCondition(comments); if (condition !== null) { statement.expression = t.callExpression( t.identifier('_test_react_version_focus'), [condition, ...expression.arguments] ); } else if (REACT_VERSION_ENV) { statement.expression = t.callExpression( t.identifier('_test_ignore_for_react_version'), expression.arguments ); } } break; } } } return; }, }, }; } module.exports = transform;
29.724138
89
0.505754
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export default class TimeoutError extends Error { constructor(message: string) { super(message); // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace) { Error.captureStackTrace(this, TimeoutError); } this.name = 'TimeoutError'; } }
23.090909
89
0.693762
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export const canUseDOM: boolean = !!( typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' );
24.333333
66
0.683377
Penetration_Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type TypeOfMode = number; export const NoMode = /* */ 0b0000000; // TODO: Remove ConcurrentMode by reading from the root tag instead export const ConcurrentMode = /* */ 0b0000001; export const ProfileMode = /* */ 0b0000010; export const DebugTracingMode = /* */ 0b0000100; export const StrictLegacyMode = /* */ 0b0001000; export const StrictEffectsMode = /* */ 0b0010000; export const ConcurrentUpdatesByDefaultMode = /* */ 0b0100000; export const NoStrictPassiveEffectsMode = /* */ 0b1000000;
37.619048
67
0.637037
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { if (__DEV__) { const constructor = publicInstance.constructor; const componentName = (constructor && (constructor.displayName || constructor.name)) || 'ReactClass'; const warningKey = `${componentName}.${callerName}`; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } console.error( "Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName, ); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ const ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function ( publicInstance, completeState, callback, callerName, ) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function ( publicInstance, partialState, callback, callerName, ) { warnNoop(publicInstance, 'setState'); }, }; export default ReactNoopUpdateQueue;
32.711712
80
0.690992
Effective-Python-Penetration-Testing
/** * 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 {Element} from 'react-devtools-shared/src/frontend/types'; import * as React from 'react'; import Badge from './Badge'; import ForgetBadge from './ForgetBadge'; import styles from './InspectedElementBadges.css'; type Props = { element: Element, }; export default function InspectedElementBadges({element}: Props): React.Node { const {hocDisplayNames, compiledWithForget} = element; return ( <div className={styles.Root}> {compiledWithForget && <ForgetBadge indexable={false} />} {hocDisplayNames !== null && hocDisplayNames.map(hocDisplayName => ( <Badge key={hocDisplayName}>{hocDisplayName}</Badge> ))} </div> ); }
23.189189
78
0.681208
GWT-Penetration-Testing-Toolset
/** * 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 * as React from 'react'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import styles from './shared.css'; type Props = { callStack: string | null, children: React$Node, componentStack: string | null, dismissError: Function | null, errorMessage: string | null, }; export default function ErrorView({ callStack, children, componentStack, dismissError = null, errorMessage, }: Props): React.Node { return ( <div className={styles.ErrorBoundary}> {children} <div className={styles.ErrorInfo}> <div className={styles.HeaderRow}> <div className={styles.ErrorHeader}> Uncaught Error: {errorMessage || ''} </div> {dismissError !== null && ( <Button className={styles.CloseButton} onClick={dismissError}> Dismiss <ButtonIcon className={styles.CloseButtonIcon} type="close" /> </Button> )} </div> {!!callStack && ( <div className={styles.ErrorStack}> The error was thrown {callStack.trim()} </div> )} {!!componentStack && ( <div className={styles.ErrorStack}> The error occurred {componentStack.trim()} </div> )} </div> </div> ); }
24.898305
76
0.589391
null
/** * 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, ReactClientValue, } from 'react-server/src/ReactFlightServer'; import type {Destination} from 'react-server/src/ReactServerStreamConfigNode'; import type {ClientManifest} from './ReactFlightServerConfigWebpackBundler'; import type {ServerManifest} from 'react-client/src/ReactFlightClientConfig'; import type {Busboy} from 'busboy'; import type {Writable} from 'stream'; import type {ServerContextJSONValue, Thenable} from 'shared/ReactTypes'; import { createRequest, startWork, startFlowing, stopFlowing, abort, } from 'react-server/src/ReactFlightServer'; import { createResponse, reportGlobalError, close, resolveField, resolveFileInfo, resolveFileChunk, resolveFileComplete, getRoot, } from 'react-server/src/ReactFlightReplyServer'; import { decodeAction, decodeFormState, } from 'react-server/src/ReactFlightActionServer'; export { registerServerReference, registerClientReference, createClientModuleProxy, } from './ReactFlightWebpackReferences'; function createDrainHandler(destination: Destination, request: Request) { return () => startFlowing(request, destination); } function createCancelHandler(request: Request, reason: string) { return () => { stopFlowing(request); // eslint-disable-next-line react-internal/prod-error-codes abort(request, new Error(reason)); }; } type Options = { onError?: (error: mixed) => void, onPostpone?: (reason: string) => void, context?: Array<[string, ServerContextJSONValue]>, identifierPrefix?: string, }; type PipeableStream = { abort(reason: mixed): void, pipe<T: Writable>(destination: T): T, }; function renderToPipeableStream( model: ReactClientValue, webpackMap: ClientManifest, options?: Options, ): PipeableStream { const request = createRequest( model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined, ); let hasStartedFlowing = false; startWork(request); return { pipe<T: Writable>(destination: T): T { if (hasStartedFlowing) { throw new Error( 'React currently only supports piping to one writable stream.', ); } hasStartedFlowing = true; startFlowing(request, destination); destination.on('drain', createDrainHandler(destination, request)); destination.on( 'error', createCancelHandler( request, 'The destination stream errored while writing data.', ), ); destination.on( 'close', createCancelHandler(request, 'The destination stream closed early.'), ); return destination; }, abort(reason: mixed) { abort(request, reason); }, }; } function decodeReplyFromBusboy<T>( busboyStream: Busboy, webpackMap: ServerManifest, ): Thenable<T> { const response = createResponse(webpackMap, ''); let pendingFiles = 0; const queuedFields: Array<string> = []; busboyStream.on('field', (name, value) => { if (pendingFiles > 0) { // Because the 'end' event fires two microtasks after the next 'field' // we would resolve files and fields out of order. To handle this properly // we queue any fields we receive until the previous file is done. queuedFields.push(name, value); } else { resolveField(response, name, value); } }); busboyStream.on('file', (name, value, {filename, encoding, mimeType}) => { if (encoding.toLowerCase() === 'base64') { throw new Error( "React doesn't accept base64 encoded file uploads because we don't expect " + "form data passed from a browser to ever encode data that way. If that's " + 'the wrong assumption, we can easily fix it.', ); } pendingFiles++; const file = resolveFileInfo(response, name, filename, mimeType); value.on('data', chunk => { resolveFileChunk(response, file, chunk); }); value.on('end', () => { resolveFileComplete(response, name, file); pendingFiles--; if (pendingFiles === 0) { // Release any queued fields for (let i = 0; i < queuedFields.length; i += 2) { resolveField(response, queuedFields[i], queuedFields[i + 1]); } queuedFields.length = 0; } }); }); busboyStream.on('finish', () => { close(response); }); busboyStream.on('error', err => { reportGlobalError( response, // $FlowFixMe[incompatible-call] types Error and mixed are incompatible err, ); }); return getRoot(response); } function decodeReply<T>( body: string | FormData, webpackMap: ServerManifest, ): Thenable<T> { if (typeof body === 'string') { const form = new FormData(); form.append('0', body); body = form; } const response = createResponse(webpackMap, '', body); const root = getRoot<T>(response); close(response); return root; } export { renderToPipeableStream, decodeReplyFromBusboy, decodeReply, decodeAction, decodeFormState, };
26.22449
86
0.667479
PenetrationTestingScripts
import hasOwnProperty from 'shared/hasOwnProperty'; import isArray from 'shared/isArray'; function formatLanes(laneArray) { const lanes = laneArray.reduce((current, reduced) => current + reduced, 0); return '0b' + lanes.toString(2).padStart(31, '0'); } // test() is part of Jest's serializer API export function test(maybeTimelineData) { if ( maybeTimelineData != null && typeof maybeTimelineData === 'object' && hasOwnProperty.call(maybeTimelineData, 'lanes') && isArray(maybeTimelineData.lanes) ) { return true; } return false; } // print() is part of Jest's serializer API export function print(timelineData, serialize, indent) { return serialize({ ...timelineData, lanes: formatLanes(timelineData.lanes), }); }
24.466667
77
0.698558
null
/** * 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. * * @emails react-core * @jest-environment node */ /* eslint-disable no-for-of-loops/no-for-of-loops */ 'use strict'; let Scheduler; let runtime; let performance; let cancelCallback; let scheduleCallback; let ImmediatePriority; let NormalPriority; let UserBlockingPriority; let LowPriority; let IdlePriority; let shouldYield; // The Scheduler postTask implementation uses a new postTask browser API to // schedule work on the main thread. This test suite mocks all browser methods // used in our implementation. It assumes as little as possible about the order // and timing of events. describe('SchedulerPostTask', () => { beforeEach(() => { jest.resetModules(); jest.mock('scheduler', () => jest.requireActual('scheduler/unstable_post_task'), ); runtime = installMockBrowserRuntime(); performance = window.performance; Scheduler = require('scheduler'); cancelCallback = Scheduler.unstable_cancelCallback; scheduleCallback = Scheduler.unstable_scheduleCallback; ImmediatePriority = Scheduler.unstable_ImmediatePriority; UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; NormalPriority = Scheduler.unstable_NormalPriority; LowPriority = Scheduler.unstable_LowPriority; IdlePriority = Scheduler.unstable_IdlePriority; shouldYield = Scheduler.unstable_shouldYield; }); afterEach(() => { if (!runtime.isLogEmpty()) { throw Error('Test exited without clearing log.'); } }); function installMockBrowserRuntime() { let taskQueue = new Map(); let eventLog = []; // Mock window functions const window = {}; global.window = window; let idCounter = 0; let currentTime = 0; window.performance = { now() { return currentTime; }, }; // Note: setTimeout is used to report errors and nothing else. window.setTimeout = cb => { try { cb(); } catch (error) { runtime.log(`Error: ${error.message}`); } }; // Mock browser scheduler. const scheduler = {}; global.scheduler = scheduler; scheduler.postTask = function (callback, {signal}) { const {priority} = signal; const id = idCounter++; log( `Post Task ${id} [${priority === undefined ? '<default>' : priority}]`, ); const controller = signal._controller; return new Promise((resolve, reject) => { taskQueue.set(controller, {id, callback, resolve, reject}); }); }; scheduler.yield = function ({signal}) { const {priority} = signal; const id = idCounter++; log(`Yield ${id} [${priority === undefined ? '<default>' : priority}]`); const controller = signal._controller; let callback; return { then(cb) { callback = cb; return new Promise((resolve, reject) => { taskQueue.set(controller, {id, callback, resolve, reject}); }); }, }; }; global.TaskController = class TaskController { constructor({priority}) { this.signal = {_controller: this, priority}; } abort() { const task = taskQueue.get(this); if (task !== undefined) { taskQueue.delete(this); const reject = task.reject; reject(new Error('Aborted')); } } }; function ensureLogIsEmpty() { if (eventLog.length !== 0) { throw Error('Log is not empty. Call assertLog before continuing.'); } } function advanceTime(ms) { currentTime += ms; } function flushTasks() { ensureLogIsEmpty(); // If there's a continuation, it will call postTask again // which will set nextTask. That means we need to clear // nextTask before the invocation, otherwise we would // delete the continuation task. const prevTaskQueue = taskQueue; taskQueue = new Map(); for (const [, {id, callback, resolve}] of prevTaskQueue) { log(`Task ${id} Fired`); callback(false); resolve(); } } function log(val) { eventLog.push(val); } function isLogEmpty() { return eventLog.length === 0; } function assertLog(expected) { const actual = eventLog; eventLog = []; expect(actual).toEqual(expected); } return { advanceTime, flushTasks, log, isLogEmpty, assertLog, }; } it('task that finishes before deadline', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); }); runtime.assertLog(['Post Task 0 [user-visible]']); runtime.flushTasks(); runtime.assertLog(['Task 0 Fired', 'A']); }); it('task with continuation', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); while (!Scheduler.unstable_shouldYield()) { runtime.advanceTime(1); } runtime.log(`Yield at ${performance.now()}ms`); return () => { runtime.log('Continuation'); }; }); runtime.assertLog(['Post Task 0 [user-visible]']); runtime.flushTasks(); runtime.assertLog([ 'Task 0 Fired', 'A', 'Yield at 5ms', 'Yield 1 [user-visible]', ]); runtime.flushTasks(); runtime.assertLog(['Task 1 Fired', 'Continuation']); }); it('multiple tasks', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); }); scheduleCallback(NormalPriority, () => { runtime.log('B'); }); runtime.assertLog([ 'Post Task 0 [user-visible]', 'Post Task 1 [user-visible]', ]); runtime.flushTasks(); runtime.assertLog(['Task 0 Fired', 'A', 'Task 1 Fired', 'B']); }); it('cancels tasks', () => { const task = scheduleCallback(NormalPriority, () => { runtime.log('A'); }); runtime.assertLog(['Post Task 0 [user-visible]']); cancelCallback(task); runtime.flushTasks(); runtime.assertLog([]); }); it('an error in one task does not affect execution of other tasks', () => { scheduleCallback(NormalPriority, () => { throw Error('Oops!'); }); scheduleCallback(NormalPriority, () => { runtime.log('Yay'); }); runtime.assertLog([ 'Post Task 0 [user-visible]', 'Post Task 1 [user-visible]', ]); runtime.flushTasks(); runtime.assertLog(['Task 0 Fired', 'Error: Oops!', 'Task 1 Fired', 'Yay']); }); it('schedule new task after queue has emptied', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); }); runtime.assertLog(['Post Task 0 [user-visible]']); runtime.flushTasks(); runtime.assertLog(['Task 0 Fired', 'A']); scheduleCallback(NormalPriority, () => { runtime.log('B'); }); runtime.assertLog(['Post Task 1 [user-visible]']); runtime.flushTasks(); runtime.assertLog(['Task 1 Fired', 'B']); }); it('schedule new task after a cancellation', () => { const handle = scheduleCallback(NormalPriority, () => { runtime.log('A'); }); runtime.assertLog(['Post Task 0 [user-visible]']); cancelCallback(handle); runtime.flushTasks(); runtime.assertLog([]); scheduleCallback(NormalPriority, () => { runtime.log('B'); }); runtime.assertLog(['Post Task 1 [user-visible]']); runtime.flushTasks(); runtime.assertLog(['Task 1 Fired', 'B']); }); it('schedules tasks at different priorities', () => { scheduleCallback(ImmediatePriority, () => { runtime.log('A'); }); scheduleCallback(UserBlockingPriority, () => { runtime.log('B'); }); scheduleCallback(NormalPriority, () => { runtime.log('C'); }); scheduleCallback(LowPriority, () => { runtime.log('D'); }); scheduleCallback(IdlePriority, () => { runtime.log('E'); }); runtime.assertLog([ 'Post Task 0 [user-blocking]', 'Post Task 1 [user-blocking]', 'Post Task 2 [user-visible]', 'Post Task 3 [user-visible]', 'Post Task 4 [background]', ]); runtime.flushTasks(); runtime.assertLog([ 'Task 0 Fired', 'A', 'Task 1 Fired', 'B', 'Task 2 Fired', 'C', 'Task 3 Fired', 'D', 'Task 4 Fired', 'E', ]); }); it('yielding continues in a new task regardless of how much time is remaining', () => { scheduleCallback(NormalPriority, () => { runtime.log('Original Task'); runtime.log('shouldYield: ' + shouldYield()); runtime.log('Return a continuation'); return () => { runtime.log('Continuation Task'); }; }); runtime.assertLog(['Post Task 0 [user-visible]']); runtime.flushTasks(); runtime.assertLog([ 'Task 0 Fired', 'Original Task', // Immediately before returning a continuation, `shouldYield` returns // false, which means there must be time remaining in the frame. 'shouldYield: false', 'Return a continuation', // The continuation should be scheduled in a separate macrotask even // though there's time remaining. 'Yield 1 [user-visible]', ]); // No time has elapsed expect(performance.now()).toBe(0); runtime.flushTasks(); runtime.assertLog(['Task 1 Fired', 'Continuation Task']); }); describe('falls back to postTask for scheduling continuations when scheduler.yield is not available', () => { beforeEach(() => { delete global.scheduler.yield; }); it('task with continuation', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); while (!Scheduler.unstable_shouldYield()) { runtime.advanceTime(1); } runtime.log(`Yield at ${performance.now()}ms`); return () => { runtime.log('Continuation'); }; }); runtime.assertLog(['Post Task 0 [user-visible]']); runtime.flushTasks(); runtime.assertLog([ 'Task 0 Fired', 'A', 'Yield at 5ms', 'Post Task 1 [user-visible]', ]); runtime.flushTasks(); runtime.assertLog(['Task 1 Fired', 'Continuation']); }); it('yielding continues in a new task regardless of how much time is remaining', () => { scheduleCallback(NormalPriority, () => { runtime.log('Original Task'); runtime.log('shouldYield: ' + shouldYield()); runtime.log('Return a continuation'); return () => { runtime.log('Continuation Task'); }; }); runtime.assertLog(['Post Task 0 [user-visible]']); runtime.flushTasks(); runtime.assertLog([ 'Task 0 Fired', 'Original Task', // Immediately before returning a continuation, `shouldYield` returns // false, which means there must be time remaining in the frame. 'shouldYield: false', 'Return a continuation', // The continuation should be scheduled in a separate macrotask even // though there's time remaining. 'Post Task 1 [user-visible]', ]); // No time has elapsed expect(performance.now()).toBe(0); runtime.flushTasks(); runtime.assertLog(['Task 1 Fired', 'Continuation Task']); }); }); });
26.544578
111
0.588889
null
/** * 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 typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags'; import typeof * as ExportsType from './ReactFeatureFlags.www'; import typeof * as DynamicFeatureFlags from './ReactFeatureFlags.www-dynamic'; // Re-export dynamic flags from the www version. const dynamicFeatureFlags: DynamicFeatureFlags = require('ReactFeatureFlags'); export const { disableInputAttributeSyncing, disableIEWorkarounds, enableTrustedTypesIntegration, replayFailedUnitOfWorkWithInvokeGuardedCallback, enableLegacyFBSupport, enableDebugTracing, enableUseRefAccessWarning, enableLazyContextPropagation, enableUnifiedSyncLane, enableRetryLaneExpiration, enableTransitionTracing, enableCustomElementPropertySupport, enableDeferRootSchedulingToMicrotask, enableAsyncActions, alwaysThrottleRetries, enableDO_NOT_USE_disableStrictPassiveEffect, disableSchedulerTimeoutInWorkLoop, enableUseDeferredValueInitialArg, retryLaneExpirationMs, syncLaneExpirationMs, transitionLaneExpirationMs, } = dynamicFeatureFlags; // On WWW, __EXPERIMENTAL__ is used for a new modern build. // It's not used anywhere in production yet. export const debugRenderPhaseSideEffectsForStrictMode = __DEV__; export const enableProfilerTimer = __PROFILE__; export const enableProfilerCommitHooks = __PROFILE__; export const enableProfilerNestedUpdatePhase = __PROFILE__; export const enableProfilerNestedUpdateScheduledHook: boolean = __PROFILE__ && dynamicFeatureFlags.enableProfilerNestedUpdateScheduledHook; export const enableUpdaterTracking = __PROFILE__; export const createRootStrictEffectsByDefault = false; export const enableSuspenseAvoidThisFallback = true; export const enableSuspenseAvoidThisFallbackFizz = false; export const enableCPUSuspense = true; export const enableFloat = true; export const enableUseMemoCacheHook = true; export const enableUseEffectEventHook = true; export const enableClientRenderFallbackOnTextMismatch = false; export const enableFilterEmptyStringAttributesDOM = true; // Logs additional User Timing API marks for use with an experimental profiling tool. export const enableSchedulingProfiler: boolean = __PROFILE__ && dynamicFeatureFlags.enableSchedulingProfiler; // Note: we'll want to remove this when we to userland implementation. // For now, we'll turn it on for everyone because it's *already* on for everyone in practice. // At least this will let us stop shipping <Profiler> implementation to all users. export const enableSchedulerDebugging = true; export const disableLegacyContext = __EXPERIMENTAL__; export const enableGetInspectorDataForInstanceInProduction = false; export const enableCache = true; export const enableLegacyCache = true; export const enableCacheElement = true; export const enableFetchInstrumentation = false; export const enableFormActions = false; export const enableBinaryFlight = false; export const enableTaint = false; export const enablePostpone = false; export const disableJavaScriptURLs = true; // TODO: www currently relies on this feature. It's disabled in open source. // Need to remove it. export const disableCommentsAsDOMContainers = false; export const disableModulePatternComponents = true; export const enableCreateEventHandleAPI = true; export const enableScopeAPI = true; export const enableSuspenseCallback = true; export const enableLegacyHidden = true; export const enableComponentStackLocations = true; export const disableTextareaChildren = __EXPERIMENTAL__; export const allowConcurrentByDefault = true; export const consoleManagedByDevToolsDuringStrictMode = true; export const enableServerContext = false; export const useModernStrictMode = false; export const enableFizzExternalRuntime = true; export const forceConcurrentByDefaultForTesting = false; export const useMicrotasksForSchedulingInFabric = false; export const passChildrenWhenCloningPersistedNodes = false; export const enableAsyncDebugInfo = false; // Flow magic to verify the exports of this file match the original version. ((((null: any): ExportsType): FeatureFlagsType): ExportsType);
33.829268
93
0.814616