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
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 React = require('react'); let useContext; let ReactNoop; let Scheduler; let gen; let waitForAll; let waitFor; let waitForThrow; describe('ReactNewContext', () => { beforeEach(() => { jest.resetModules(); React = require('react'); useContext = React.useContext; ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); gen = require('random-seed'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForThrow = InternalTestUtils.waitForThrow; }); afterEach(() => { jest.restoreAllMocks(); }); function Text(props) { Scheduler.log(props.text); return <span prop={props.text} />; } function span(prop) { return {type: 'span', children: [], prop, hidden: false}; } function readContext(Context) { const dispatcher = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .ReactCurrentDispatcher.current; return dispatcher.readContext(Context); } // Note: This is based on a similar component we use in www. We can delete // once the extra div wrapper is no longer necessary. function LegacyHiddenDiv({children, mode}) { return ( <div hidden={mode === 'hidden'}> <React.unstable_LegacyHidden mode={mode === 'hidden' ? 'unstable-defer-without-hiding' : mode}> {children} </React.unstable_LegacyHidden> </div> ); } // We have several ways of reading from context. sharedContextTests runs // a suite of tests for a given context consumer implementation. sharedContextTests('Context.Consumer', Context => Context.Consumer); sharedContextTests( 'useContext inside function component', Context => function Consumer(props) { const contextValue = useContext(Context); const render = props.children; return render(contextValue); }, ); sharedContextTests('useContext inside forwardRef component', Context => React.forwardRef(function Consumer(props, ref) { const contextValue = useContext(Context); const render = props.children; return render(contextValue); }), ); sharedContextTests('useContext inside memoized function component', Context => React.memo(function Consumer(props) { const contextValue = useContext(Context); const render = props.children; return render(contextValue); }), ); sharedContextTests( 'readContext(Context) inside class component', Context => class Consumer extends React.Component { render() { const contextValue = readContext(Context); const render = this.props.children; return render(contextValue); } }, ); sharedContextTests( 'readContext(Context) inside pure class component', Context => class Consumer extends React.PureComponent { render() { const contextValue = readContext(Context); const render = this.props.children; return render(contextValue); } }, ); function sharedContextTests(label, getConsumer) { describe(`reading context with ${label}`, () => { it('simple mount and update', async () => { const Context = React.createContext(1); const Consumer = getConsumer(Context); const Indirection = React.Fragment; function App(props) { return ( <Context.Provider value={props.value}> <Indirection> <Indirection> <Consumer> {value => <span prop={'Result: ' + value} />} </Consumer> </Indirection> </Indirection> </Context.Provider> ); } ReactNoop.render(<App value={2} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 2" />); // Update ReactNoop.render(<App value={3} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 3" />); }); it('propagates through shouldComponentUpdate false', async () => { const Context = React.createContext(1); const ContextConsumer = getConsumer(Context); function Provider(props) { Scheduler.log('Provider'); return ( <Context.Provider value={props.value}> {props.children} </Context.Provider> ); } function Consumer(props) { Scheduler.log('Consumer'); return ( <ContextConsumer> {value => { Scheduler.log('Consumer render prop'); return <span prop={'Result: ' + value} />; }} </ContextConsumer> ); } class Indirection extends React.Component { shouldComponentUpdate() { return false; } render() { Scheduler.log('Indirection'); return this.props.children; } } function App(props) { Scheduler.log('App'); return ( <Provider value={props.value}> <Indirection> <Indirection> <Consumer /> </Indirection> </Indirection> </Provider> ); } ReactNoop.render(<App value={2} />); await waitForAll([ 'App', 'Provider', 'Indirection', 'Indirection', 'Consumer', 'Consumer render prop', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 2" />); // Update ReactNoop.render(<App value={3} />); await waitForAll(['App', 'Provider', 'Consumer render prop']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 3" />); }); it('consumers bail out if context value is the same', async () => { const Context = React.createContext(1); const ContextConsumer = getConsumer(Context); function Provider(props) { Scheduler.log('Provider'); return ( <Context.Provider value={props.value}> {props.children} </Context.Provider> ); } function Consumer(props) { Scheduler.log('Consumer'); return ( <ContextConsumer> {value => { Scheduler.log('Consumer render prop'); return <span prop={'Result: ' + value} />; }} </ContextConsumer> ); } class Indirection extends React.Component { shouldComponentUpdate() { return false; } render() { Scheduler.log('Indirection'); return this.props.children; } } function App(props) { Scheduler.log('App'); return ( <Provider value={props.value}> <Indirection> <Indirection> <Consumer /> </Indirection> </Indirection> </Provider> ); } ReactNoop.render(<App value={2} />); await waitForAll([ 'App', 'Provider', 'Indirection', 'Indirection', 'Consumer', 'Consumer render prop', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 2" />); // Update with the same context value ReactNoop.render(<App value={2} />); await waitForAll([ 'App', 'Provider', // Don't call render prop again ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 2" />); }); it('nested providers', async () => { const Context = React.createContext(1); const Consumer = getConsumer(Context); function Provider(props) { return ( <Consumer> {contextValue => ( // Multiply previous context value by 2, unless prop overrides <Context.Provider value={props.value || contextValue * 2}> {props.children} </Context.Provider> )} </Consumer> ); } class Indirection extends React.Component { shouldComponentUpdate() { return false; } render() { return this.props.children; } } function App(props) { return ( <Provider value={props.value}> <Indirection> <Provider> <Indirection> <Provider> <Indirection> <Consumer> {value => <span prop={'Result: ' + value} />} </Consumer> </Indirection> </Provider> </Indirection> </Provider> </Indirection> </Provider> ); } ReactNoop.render(<App value={2} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 8" />); // Update ReactNoop.render(<App value={3} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: 12" />); }); it('should provide the correct (default) values to consumers outside of a provider', async () => { const FooContext = React.createContext({value: 'foo-initial'}); const BarContext = React.createContext({value: 'bar-initial'}); const FooConsumer = getConsumer(FooContext); const BarConsumer = getConsumer(BarContext); const Verify = ({actual, expected}) => { expect(expected).toBe(actual); return null; }; ReactNoop.render( <> <BarContext.Provider value={{value: 'bar-updated'}}> <BarConsumer> {({value}) => <Verify actual={value} expected="bar-updated" />} </BarConsumer> <FooContext.Provider value={{value: 'foo-updated'}}> <FooConsumer> {({value}) => ( <Verify actual={value} expected="foo-updated" /> )} </FooConsumer> </FooContext.Provider> </BarContext.Provider> <FooConsumer> {({value}) => <Verify actual={value} expected="foo-initial" />} </FooConsumer> <BarConsumer> {({value}) => <Verify actual={value} expected="bar-initial" />} </BarConsumer> </>, ); await waitForAll([]); }); it('multiple consumers in different branches', async () => { const Context = React.createContext(1); const Consumer = getConsumer(Context); function Provider(props) { return ( <Context.Consumer> {contextValue => ( // Multiply previous context value by 2, unless prop overrides <Context.Provider value={props.value || contextValue * 2}> {props.children} </Context.Provider> )} </Context.Consumer> ); } class Indirection extends React.Component { shouldComponentUpdate() { return false; } render() { return this.props.children; } } function App(props) { return ( <Provider value={props.value}> <Indirection> <Indirection> <Provider> <Consumer> {value => <span prop={'Result: ' + value} />} </Consumer> </Provider> </Indirection> <Indirection> <Consumer> {value => <span prop={'Result: ' + value} />} </Consumer> </Indirection> </Indirection> </Provider> ); } ReactNoop.render(<App value={2} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Result: 4" /> <span prop="Result: 2" /> </>, ); // Update ReactNoop.render(<App value={3} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Result: 6" /> <span prop="Result: 3" /> </>, ); // Another update ReactNoop.render(<App value={4} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Result: 8" /> <span prop="Result: 4" /> </>, ); }); it('compares context values with Object.is semantics', async () => { const Context = React.createContext(1); const ContextConsumer = getConsumer(Context); function Provider(props) { Scheduler.log('Provider'); return ( <Context.Provider value={props.value}> {props.children} </Context.Provider> ); } function Consumer(props) { Scheduler.log('Consumer'); return ( <ContextConsumer> {value => { Scheduler.log('Consumer render prop'); return <span prop={'Result: ' + value} />; }} </ContextConsumer> ); } class Indirection extends React.Component { shouldComponentUpdate() { return false; } render() { Scheduler.log('Indirection'); return this.props.children; } } function App(props) { Scheduler.log('App'); return ( <Provider value={props.value}> <Indirection> <Indirection> <Consumer /> </Indirection> </Indirection> </Provider> ); } ReactNoop.render(<App value={NaN} />); await waitForAll([ 'App', 'Provider', 'Indirection', 'Indirection', 'Consumer', 'Consumer render prop', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: NaN" />); // Update ReactNoop.render(<App value={NaN} />); await waitForAll([ 'App', 'Provider', // Consumer should not re-render again // 'Consumer render prop', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Result: NaN" />); }); it('context unwinds when interrupted', async () => { const Context = React.createContext('Default'); const ContextConsumer = getConsumer(Context); function Consumer(props) { return ( <ContextConsumer> {value => <span prop={'Result: ' + value} />} </ContextConsumer> ); } function BadRender() { throw new Error('Bad render'); } class ErrorBoundary extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { if (this.state.error) { return null; } return this.props.children; } } function App(props) { return ( <> <Context.Provider value="Does not unwind"> <ErrorBoundary> <Context.Provider value="Unwinds after BadRender throws"> <BadRender /> </Context.Provider> </ErrorBoundary> <Consumer /> </Context.Provider> </> ); } ReactNoop.render(<App value="A" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( // The second provider should use the default value. <span prop="Result: Does not unwind" />, ); }); it("does not re-render if there's an update in a child", async () => { const Context = React.createContext(0); const Consumer = getConsumer(Context); let child; class Child extends React.Component { state = {step: 0}; render() { Scheduler.log('Child'); return ( <span prop={`Context: ${this.props.context}, Step: ${this.state.step}`} /> ); } } function App(props) { return ( <Context.Provider value={props.value}> <Consumer> {value => { Scheduler.log('Consumer render prop'); return <Child ref={inst => (child = inst)} context={value} />; }} </Consumer> </Context.Provider> ); } // Initial mount ReactNoop.render(<App value={1} />); await waitForAll(['Consumer render prop', 'Child']); expect(ReactNoop).toMatchRenderedOutput( <span prop="Context: 1, Step: 0" />, ); child.setState({step: 1}); await waitForAll(['Child']); expect(ReactNoop).toMatchRenderedOutput( <span prop="Context: 1, Step: 1" />, ); }); it('consumer bails out if value is unchanged and something above bailed out', async () => { const Context = React.createContext(0); const Consumer = getConsumer(Context); function renderChildValue(value) { Scheduler.log('Consumer'); return <span prop={value} />; } function ChildWithInlineRenderCallback() { Scheduler.log('ChildWithInlineRenderCallback'); // Note: we are intentionally passing an inline arrow. Don't refactor. return <Consumer>{value => renderChildValue(value)}</Consumer>; } function ChildWithCachedRenderCallback() { Scheduler.log('ChildWithCachedRenderCallback'); return <Consumer>{renderChildValue}</Consumer>; } class PureIndirection extends React.PureComponent { render() { Scheduler.log('PureIndirection'); return ( <> <ChildWithInlineRenderCallback /> <ChildWithCachedRenderCallback /> </> ); } } class App extends React.Component { render() { Scheduler.log('App'); return ( <Context.Provider value={this.props.value}> <PureIndirection /> </Context.Provider> ); } } // Initial mount ReactNoop.render(<App value={1} />); await waitForAll([ 'App', 'PureIndirection', 'ChildWithInlineRenderCallback', 'Consumer', 'ChildWithCachedRenderCallback', 'Consumer', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop={1} /> <span prop={1} /> </>, ); // Update (bailout) ReactNoop.render(<App value={1} />); await waitForAll(['App']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop={1} /> <span prop={1} /> </>, ); // Update (no bailout) ReactNoop.render(<App value={2} />); await waitForAll(['App', 'Consumer', 'Consumer']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop={2} /> <span prop={2} /> </>, ); }); // @gate www it("context consumer doesn't bail out inside hidden subtree", async () => { const Context = React.createContext('dark'); const Consumer = getConsumer(Context); function App({theme}) { return ( <Context.Provider value={theme}> <LegacyHiddenDiv mode="hidden"> <Consumer>{value => <Text text={value} />}</Consumer> </LegacyHiddenDiv> </Context.Provider> ); } ReactNoop.render(<App theme="dark" />); await waitForAll(['dark']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <span prop="dark" /> </div>, ); ReactNoop.render(<App theme="light" />); await waitForAll(['light']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <span prop="light" /> </div>, ); }); // This is a regression case for https://github.com/facebook/react/issues/12389. it('does not run into an infinite loop', async () => { const Context = React.createContext(null); const Consumer = getConsumer(Context); class App extends React.Component { renderItem(id) { return ( <span key={id}> <Consumer>{() => <span>inner</span>}</Consumer> <span>outer</span> </span> ); } renderList() { const list = [1, 2].map(id => this.renderItem(id)); if (this.props.reverse) { list.reverse(); } return list; } render() { return ( <Context.Provider value={{}}> {this.renderList()} </Context.Provider> ); } } ReactNoop.render(<App reverse={false} />); await waitForAll([]); ReactNoop.render(<App reverse={true} />); await waitForAll([]); ReactNoop.render(<App reverse={false} />); await waitForAll([]); }); // This is a regression case for https://github.com/facebook/react/issues/12686 it('does not skip some siblings', async () => { const Context = React.createContext(0); const ContextConsumer = getConsumer(Context); class App extends React.Component { state = { step: 0, }; render() { Scheduler.log('App'); return ( <Context.Provider value={this.state.step}> <StaticContent /> {this.state.step > 0 && <Indirection />} </Context.Provider> ); } } class StaticContent extends React.PureComponent { render() { return ( <> <> <span prop="static 1" /> <span prop="static 2" /> </> </> ); } } class Indirection extends React.PureComponent { render() { return ( <ContextConsumer> {value => { Scheduler.log('Consumer'); return <span prop={value} />; }} </ContextConsumer> ); } } // Initial mount let inst; ReactNoop.render(<App ref={ref => (inst = ref)} />); await waitForAll(['App']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="static 1" /> <span prop="static 2" /> </>, ); // Update the first time inst.setState({step: 1}); await waitForAll(['App', 'Consumer']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="static 1" /> <span prop="static 2" /> <span prop={1} /> </>, ); // Update the second time inst.setState({step: 2}); await waitForAll(['App', 'Consumer']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="static 1" /> <span prop="static 2" /> <span prop={2} /> </>, ); }); }); } describe('Context.Provider', () => { it('warns if no value prop provided', async () => { const Context = React.createContext(); ReactNoop.render( <Context.Provider anyPropNameOtherThanValue="value could be anything" />, ); await expect(async () => await waitForAll([])).toErrorDev( 'The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?', { withoutStack: true, }, ); }); it('warns if multiple renderers concurrently render the same context', async () => { spyOnDev(console, 'error').mockImplementation(() => {}); const Context = React.createContext(0); function Foo(props) { Scheduler.log('Foo'); return null; } function App(props) { return ( <Context.Provider value={props.value}> <Foo /> <Foo /> </Context.Provider> ); } React.startTransition(() => { ReactNoop.render(<App value={1} />); }); // Render past the Provider, but don't commit yet await waitFor(['Foo']); // Get a new copy of ReactNoop jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; // Render the provider again using a different renderer ReactNoop.render(<App value={1} />); await waitForAll(['Foo', 'Foo']); if (__DEV__) { expect(console.error.mock.calls[0][0]).toContain( 'Detected multiple renderers concurrently rendering the same ' + 'context provider. This is currently unsupported', ); } }); it('does not warn if multiple renderers use the same context sequentially', async () => { spyOnDev(console, 'error'); const Context = React.createContext(0); function Foo(props) { Scheduler.log('Foo'); return null; } function App(props) { return ( <Context.Provider value={props.value}> <Foo /> <Foo /> </Context.Provider> ); } React.startTransition(() => { ReactNoop.render(<App value={1} />); }); await waitForAll(['Foo', 'Foo']); // Get a new copy of ReactNoop jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; // Render the provider again using a different renderer ReactNoop.render(<App value={1} />); await waitForAll(['Foo', 'Foo']); if (__DEV__) { expect(console.error).not.toHaveBeenCalled(); } }); it('provider bails out if children and value are unchanged (like sCU)', async () => { const Context = React.createContext(0); function Child() { Scheduler.log('Child'); return <span prop="Child" />; } const children = <Child />; function App(props) { Scheduler.log('App'); return ( <Context.Provider value={props.value}>{children}</Context.Provider> ); } // Initial mount ReactNoop.render(<App value={1} />); await waitForAll(['App', 'Child']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Child" />); // Update ReactNoop.render(<App value={1} />); await waitForAll([ 'App', // Child does not re-render ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Child" />); }); // @gate !disableLegacyContext it('provider does not bail out if legacy context changed above', async () => { const Context = React.createContext(0); function Child() { Scheduler.log('Child'); return <span prop="Child" />; } const children = <Child />; class LegacyProvider extends React.Component { static childContextTypes = { legacyValue: () => {}, }; state = {legacyValue: 1}; getChildContext() { return {legacyValue: this.state.legacyValue}; } render() { Scheduler.log('LegacyProvider'); return this.props.children; } } class App extends React.Component { state = {value: 1}; render() { Scheduler.log('App'); return ( <Context.Provider value={this.state.value}> {this.props.children} </Context.Provider> ); } } const legacyProviderRef = React.createRef(); const appRef = React.createRef(); // Initial mount ReactNoop.render( <LegacyProvider ref={legacyProviderRef}> <App ref={appRef} value={1}> {children} </App> </LegacyProvider>, ); await waitForAll(['LegacyProvider', 'App', 'Child']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Child" />); // Update App with same value (should bail out) appRef.current.setState({value: 1}); await waitForAll(['App']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Child" />); // Update LegacyProvider (should not bail out) legacyProviderRef.current.setState({value: 1}); await waitForAll(['LegacyProvider', 'App', 'Child']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Child" />); // Update App with same value (should bail out) appRef.current.setState({value: 1}); await waitForAll(['App']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Child" />); }); }); describe('Context.Consumer', () => { it('warns if child is not a function', async () => { spyOnDev(console, 'error').mockImplementation(() => {}); const Context = React.createContext(0); ReactNoop.render(<Context.Consumer />); await waitForThrow('is not a function'); if (__DEV__) { expect(console.error.mock.calls[0][0]).toContain( 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function", ); } }); it('can read other contexts inside consumer render prop', async () => { const FooContext = React.createContext(0); const BarContext = React.createContext(0); function FooAndBar() { return ( <FooContext.Consumer> {foo => { const bar = readContext(BarContext); return <Text text={`Foo: ${foo}, Bar: ${bar}`} />; }} </FooContext.Consumer> ); } class Indirection extends React.Component { shouldComponentUpdate() { return false; } render() { return this.props.children; } } function App(props) { return ( <FooContext.Provider value={props.foo}> <BarContext.Provider value={props.bar}> <Indirection> <FooAndBar /> </Indirection> </BarContext.Provider> </FooContext.Provider> ); } ReactNoop.render(<App foo={1} bar={1} />); await waitForAll(['Foo: 1, Bar: 1']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Foo: 1, Bar: 1" />); // Update foo ReactNoop.render(<App foo={2} bar={1} />); await waitForAll(['Foo: 2, Bar: 1']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Foo: 2, Bar: 1" />); // Update bar ReactNoop.render(<App foo={2} bar={2} />); await waitForAll(['Foo: 2, Bar: 2']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Foo: 2, Bar: 2" />); }); // Context consumer bails out on propagating "deep" updates when `value` hasn't changed. // However, it doesn't bail out from rendering if the component above it re-rendered anyway. // If we bailed out on referential equality, it would be confusing that you // can call this.setState(), but an autobound render callback "blocked" the update. // https://github.com/facebook/react/pull/12470#issuecomment-376917711 it('consumer does not bail out if there were no bailouts above it', async () => { const Context = React.createContext(0); const Consumer = Context.Consumer; class App extends React.Component { state = { text: 'hello', }; renderConsumer = context => { Scheduler.log('App#renderConsumer'); return <span prop={this.state.text} />; }; render() { Scheduler.log('App'); return ( <Context.Provider value={this.props.value}> <Consumer>{this.renderConsumer}</Consumer> </Context.Provider> ); } } // Initial mount let inst; ReactNoop.render(<App value={1} ref={ref => (inst = ref)} />); await waitForAll(['App', 'App#renderConsumer']); expect(ReactNoop).toMatchRenderedOutput(<span prop="hello" />); // Update inst.setState({text: 'goodbye'}); await waitForAll(['App', 'App#renderConsumer']); expect(ReactNoop).toMatchRenderedOutput(<span prop="goodbye" />); }); }); describe('readContext', () => { // Unstable changedBits API was removed. Port this test to context selectors // once that exists. // @gate FIXME it('can read the same context multiple times in the same function', async () => { 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 ( <Provider foo={props.foo} bar={props.bar} baz={props.baz}> <Indirection> <Indirection> <FooAndBar /> </Indirection> <Indirection> <Baz /> </Indirection> </Indirection> </Provider> ); } ReactNoop.render(<App foo={1} bar={1} baz={1} />); await waitForAll(['Foo: 1, Bar: 1', 'Baz: 1']); expect(ReactNoop).toMatchRenderedOutput([ <span prop="Foo: 1, Bar: 1" />, <span prop="Baz: 1" />, ]); // Update only foo ReactNoop.render(<App foo={2} bar={1} baz={1} />); await waitForAll(['Foo: 2, Bar: 1']); expect(ReactNoop).toMatchRenderedOutput([ <span prop="Foo: 2, Bar: 1" />, <span prop="Baz: 1" />, ]); // Update only bar ReactNoop.render(<App foo={2} bar={2} baz={1} />); await waitForAll(['Foo: 2, Bar: 2']); expect(ReactNoop).toMatchRenderedOutput([ <span prop="Foo: 2, Bar: 2" />, <span prop="Baz: 1" />, ]); // Update only baz ReactNoop.render(<App foo={2} bar={2} baz={2} />); await waitForAll(['Baz: 2']); expect(ReactNoop).toMatchRenderedOutput([ <span prop="Foo: 2, Bar: 2" />, <span prop="Baz: 2" />, ]); }); // Context consumer bails out on propagating "deep" updates when `value` hasn't changed. // However, it doesn't bail out from rendering if the component above it re-rendered anyway. // If we bailed out on referential equality, it would be confusing that you // can call this.setState(), but an autobound render callback "blocked" the update. // https://github.com/facebook/react/pull/12470#issuecomment-376917711 it('does not bail out if there were no bailouts above it', async () => { const Context = React.createContext(0); class Consumer extends React.Component { render() { const contextValue = readContext(Context); return this.props.children(contextValue); } } class App extends React.Component { state = { text: 'hello', }; renderConsumer = context => { Scheduler.log('App#renderConsumer'); return <span prop={this.state.text} />; }; render() { Scheduler.log('App'); return ( <Context.Provider value={this.props.value}> <Consumer>{this.renderConsumer}</Consumer> </Context.Provider> ); } } // Initial mount let inst; ReactNoop.render(<App value={1} ref={ref => (inst = ref)} />); await waitForAll(['App', 'App#renderConsumer']); expect(ReactNoop).toMatchRenderedOutput(<span prop="hello" />); // Update inst.setState({text: 'goodbye'}); await waitForAll(['App', 'App#renderConsumer']); expect(ReactNoop).toMatchRenderedOutput(<span prop="goodbye" />); }); it('warns when reading context inside render phase class setState updater', async () => { const ThemeContext = React.createContext('light'); class Cls extends React.Component { state = {}; render() { this.setState(() => { readContext(ThemeContext); }); return null; } } ReactNoop.render(<Cls />); await expect(async () => await waitForAll([])).toErrorDev([ 'Context can only be read while React is rendering', 'Cannot update during an existing state transition', ]); }); }); describe('useContext', () => { it('throws when used in a class component', async () => { const Context = React.createContext(0); class Foo extends React.Component { render() { return useContext(Context); } } ReactNoop.render(<Foo />); await waitForThrow( '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.', ); }); it('warns when passed a consumer', async () => { const Context = React.createContext(0); function Foo() { return useContext(Context.Consumer); } ReactNoop.render(<Foo />); await expect(async () => await waitForAll([])).toErrorDev( 'Calling useContext(Context.Consumer) is not supported, may cause bugs, ' + 'and will be removed in a future major release. ' + 'Did you mean to call useContext(Context) instead?', ); }); it('warns when passed a provider', async () => { const Context = React.createContext(0); function Foo() { useContext(Context.Provider); return null; } ReactNoop.render(<Foo />); await expect(async () => await waitForAll([])).toErrorDev( 'Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?', ); }); // Context consumer bails out on propagating "deep" updates when `value` hasn't changed. // However, it doesn't bail out from rendering if the component above it re-rendered anyway. // If we bailed out on referential equality, it would be confusing that you // can call this.setState(), but an autobound render callback "blocked" the update. // https://github.com/facebook/react/pull/12470#issuecomment-376917711 it('does not bail out if there were no bailouts above it', async () => { const Context = React.createContext(0); function Consumer({children}) { const contextValue = useContext(Context); return children(contextValue); } class App extends React.Component { state = { text: 'hello', }; renderConsumer = context => { Scheduler.log('App#renderConsumer'); return <span prop={this.state.text} />; }; render() { Scheduler.log('App'); return ( <Context.Provider value={this.props.value}> <Consumer>{this.renderConsumer}</Consumer> </Context.Provider> ); } } // Initial mount let inst; ReactNoop.render(<App value={1} ref={ref => (inst = ref)} />); await waitForAll(['App', 'App#renderConsumer']); expect(ReactNoop).toMatchRenderedOutput(<span prop="hello" />); // Update inst.setState({text: 'goodbye'}); await waitForAll(['App', 'App#renderConsumer']); expect(ReactNoop).toMatchRenderedOutput(<span prop="goodbye" />); }); }); it('unwinds after errors in complete phase', async () => { const Context = React.createContext(0); // This is a regression test for stack misalignment // caused by unwinding the context from wrong point. ReactNoop.render( <errorInCompletePhase> <Context.Provider value={null} /> </errorInCompletePhase>, ); await waitForThrow('Error in host config.'); ReactNoop.render( <Context.Provider value={10}> <Context.Consumer>{value => <span prop={value} />}</Context.Consumer> </Context.Provider>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop={10} />); }); describe('fuzz test', () => { const contextKeys = ['A', 'B', 'C', 'D', 'E', 'F', 'G']; const FLUSH_ALL = 'FLUSH_ALL'; function flushAll() { return { type: FLUSH_ALL, toString() { return `flushAll()`; }, }; } const FLUSH = 'FLUSH'; function flush(unitsOfWork) { return { type: FLUSH, unitsOfWork, toString() { return `flush(${unitsOfWork})`; }, }; } const UPDATE = 'UPDATE'; function update(key, value) { return { type: UPDATE, key, value, toString() { return `update('${key}', ${value})`; }, }; } function randomInteger(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } function randomAction() { switch (randomInteger(0, 3)) { case 0: return flushAll(); case 1: return flush(randomInteger(0, 500)); case 2: const key = contextKeys[randomInteger(0, contextKeys.length)]; const value = randomInteger(1, 10); return update(key, value); default: throw new Error('Switch statement should be exhaustive'); } } function randomActions(n) { const actions = []; for (let i = 0; i < n; i++) { actions.push(randomAction()); } return actions; } function ContextSimulator(maxDepth) { const contexts = new Map( contextKeys.map(key => { const Context = React.createContext(0); Context.displayName = 'Context' + key; return [key, Context]; }), ); class ConsumerTree extends React.Component { shouldComponentUpdate() { return false; } render() { Scheduler.log(); if (this.props.depth >= this.props.maxDepth) { return null; } const consumers = [0, 1, 2].map(i => { const randomKey = contextKeys[ this.props.rand.intBetween(0, contextKeys.length - 1) ]; const Context = contexts.get(randomKey); return ( <Context.Consumer key={i}> {value => ( <> <span prop={`${randomKey}:${value}`} /> <ConsumerTree rand={this.props.rand} depth={this.props.depth + 1} maxDepth={this.props.maxDepth} /> </> )} </Context.Consumer> ); }); return consumers; } } function Root(props) { return contextKeys.reduceRight( (children, key) => { const Context = contexts.get(key); const value = props.values[key]; return ( <Context.Provider value={value}>{children}</Context.Provider> ); }, <ConsumerTree rand={props.rand} depth={0} maxDepth={props.maxDepth} />, ); } const initialValues = contextKeys.reduce( (result, key, i) => ({...result, [key]: i + 1}), {}, ); function assertConsistentTree(expectedValues = {}) { const jsx = ReactNoop.getChildrenAsJSX(); const children = jsx === null ? [] : jsx.props.children; children.forEach(child => { const text = child.props.prop; const key = text[0]; const value = parseInt(text[2], 10); const expectedValue = expectedValues[key]; if (expectedValue === undefined) { // If an expected value was not explicitly passed to this function, // use the first occurrence. expectedValues[key] = value; } else if (value !== expectedValue) { throw new Error( `Inconsistent value! Expected: ${key}:${expectedValue}. Actual: ${text}`, ); } }); } function simulate(seed, actions) { const rand = gen.create(seed); let finalExpectedValues = initialValues; function updateRoot() { ReactNoop.render( <Root maxDepth={maxDepth} rand={rand} values={finalExpectedValues} />, ); } updateRoot(); actions.forEach(action => { switch (action.type) { case FLUSH_ALL: Scheduler.unstable_flushAllWithoutAsserting(); break; case FLUSH: Scheduler.unstable_flushNumberOfYields(action.unitsOfWork); break; case UPDATE: finalExpectedValues = { ...finalExpectedValues, [action.key]: action.value, }; updateRoot(); break; default: throw new Error('Switch statement should be exhaustive'); } assertConsistentTree(); }); Scheduler.unstable_flushAllWithoutAsserting(); assertConsistentTree(finalExpectedValues); } return {simulate}; } it('hard-coded tests', () => { const {simulate} = ContextSimulator(5); simulate('randomSeed', [flush(3), update('A', 4)]); }); it('generated tests', () => { const {simulate} = ContextSimulator(5); const LIMIT = 100; for (let i = 0; i < LIMIT; i++) { const seed = Math.random().toString(36).slice(2, 7); const actions = randomActions(5); try { simulate(seed, actions); } catch (error) { console.error(` Context fuzz tester error! Copy and paste the following line into the test suite: simulate('${seed}', ${actions.join(', ')}); `); throw error; } } }); }); it('should warn with an error message when using context as a consumer in DEV', async () => { const BarContext = React.createContext({value: 'bar-initial'}); const BarConsumer = BarContext; function Component() { return ( <> <BarContext.Provider value={{value: 'bar-updated'}}> <BarConsumer> {({value}) => <div actual={value} expected="bar-updated" />} </BarConsumer> </BarContext.Provider> </> ); } await expect(async () => { ReactNoop.render(<Component />); await waitForAll([]); }).toErrorDev( 'Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?', ); }); // False positive regression test. it('should not warn when using Consumer from React < 16.6 with newer renderer', async () => { const BarContext = React.createContext({value: 'bar-initial'}); // React 16.5 and earlier didn't have a separate object. BarContext.Consumer = BarContext; function Component() { return ( <> <BarContext.Provider value={{value: 'bar-updated'}}> <BarContext.Consumer> {({value}) => <div actual={value} expected="bar-updated" />} </BarContext.Consumer> </BarContext.Provider> </> ); } ReactNoop.render(<Component />); await waitForAll([]); }); it('should warn with an error message when using nested context consumers in DEV', async () => { const BarContext = React.createContext({value: 'bar-initial'}); const BarConsumer = BarContext; function Component() { return ( <> <BarContext.Provider value={{value: 'bar-updated'}}> <BarConsumer.Consumer.Consumer> {({value}) => <div actual={value} expected="bar-updated" />} </BarConsumer.Consumer.Consumer> </BarContext.Provider> </> ); } await expect(async () => { ReactNoop.render(<Component />); await waitForAll([]); }).toErrorDev( 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?', ); }); it('should warn with an error message when using Context.Consumer.Provider DEV', async () => { const BarContext = React.createContext({value: 'bar-initial'}); function Component() { return ( <> <BarContext.Consumer.Provider value={{value: 'bar-updated'}}> <BarContext.Consumer> {({value}) => <div actual={value} expected="bar-updated" />} </BarContext.Consumer> </BarContext.Consumer.Provider> </> ); } await expect(async () => { ReactNoop.render(<Component />); await waitForAll([]); }).toErrorDev( 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?', ); }); });
29.114857
117
0.522827
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 {withErrorsOrWarningsIgnored} from 'react-devtools-shared/src/__tests__/utils'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type Store from 'react-devtools-shared/src/devtools/store'; describe('InspectedElement', () => { let React; let ReactDOM; let ReactDOMClient; let PropTypes; let TestRenderer: ReactTestRenderer; let bridge: FrontendBridge; let store: Store; let utils; let BridgeContext; let InspectedElementContext; let InspectedElementContextController; let SettingsContextController; let StoreContext; let TreeContextController; let TestUtilsAct; let TestRendererAct; let legacyRender; let testRendererInstance; let ErrorBoundary; let errorBoundaryInstance; global.IS_REACT_ACT_ENVIRONMENT = true; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); legacyRender = utils.legacyRender; bridge = global.bridge; store = global.store; store.collapseNodesByDefault = false; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); PropTypes = require('prop-types'); TestUtilsAct = require('internal-test-utils').act; TestRenderer = utils.requireTestRenderer(); TestRendererAct = require('internal-test-utils').act; BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext; InspectedElementContext = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext').InspectedElementContext; InspectedElementContextController = require('react-devtools-shared/src/devtools/views/Components/InspectedElementContext').InspectedElementContextController; SettingsContextController = require('react-devtools-shared/src/devtools/views/Settings/SettingsContext').SettingsContextController; StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext; TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController; // Used by inspectElementAtIndex() helper function utils.act(() => { testRendererInstance = TestRenderer.create(null, { isConcurrent: true, }); }); errorBoundaryInstance = null; ErrorBoundary = class extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { errorBoundaryInstance = this; if (this.state.error) { return null; } return this.props.children; } }; }); afterEach(() => { jest.restoreAllMocks(); }); const Contexts = ({ children, defaultSelectedElementID = null, defaultSelectedElementIndex = null, }) => ( <BridgeContext.Provider value={bridge}> <StoreContext.Provider value={store}> <SettingsContextController> <TreeContextController defaultSelectedElementID={defaultSelectedElementID} defaultSelectedElementIndex={defaultSelectedElementIndex}> <React.Suspense fallback="Loading..."> <InspectedElementContextController> {children} </InspectedElementContextController> </React.Suspense> </TreeContextController> </SettingsContextController> </StoreContext.Provider> </BridgeContext.Provider> ); function useInspectedElement() { const {inspectedElement} = React.useContext(InspectedElementContext); return inspectedElement; } function useInspectElementPath() { const {inspectPaths} = React.useContext(InspectedElementContext); return inspectPaths; } function noop() {} async function inspectElementAtIndex( index, useCustomHook = noop, shouldThrow = false, ) { let didFinish = false; let inspectedElement = null; function Suspender() { useCustomHook(); inspectedElement = useInspectedElement(); didFinish = true; return null; } const id = ((store.getElementIDAtIndex(index): any): number); await utils.actAsync(() => { testRendererInstance.update( <ErrorBoundary> <Contexts defaultSelectedElementID={id} defaultSelectedElementIndex={index}> <React.Suspense fallback={null}> <Suspender id={id} index={index} /> </React.Suspense> </Contexts> </ErrorBoundary>, ); }, false); if (!shouldThrow) { expect(didFinish).toBe(true); } return inspectedElement; } it('should inspect the currently selected element', async () => { const Example = () => { const [count] = React.useState(1); return count; }; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example a={1} b="abc" />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement).toMatchInlineSnapshot(` { "context": null, "events": undefined, "hooks": [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "Example", "lineNumber": "removed by Jest serializer", }, "id": 0, "isStateEditable": true, "name": "State", "subHooks": [], "value": 1, }, ], "id": 2, "owners": null, "props": { "a": 1, "b": "abc", }, "rootType": "render()", "state": null, } `); }); it('should have hasLegacyContext flag set to either "true" or "false" depending on which context API is used.', async () => { const contextData = { bool: true, }; // Legacy Context API. class LegacyContextProvider extends React.Component<any> { static childContextTypes = { bool: PropTypes.bool, }; getChildContext() { return contextData; } render() { return this.props.children; } } class LegacyContextConsumer extends React.Component<any> { static contextTypes = { bool: PropTypes.bool, }; render() { return null; } } // Modern Context API const BoolContext = React.createContext(contextData.bool); BoolContext.displayName = 'BoolContext'; class ModernContextType extends React.Component<any> { static contextType = BoolContext; render() { return null; } } const ModernContext = React.createContext(); ModernContext.displayName = 'ModernContext'; const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <React.Fragment> <LegacyContextProvider> <LegacyContextConsumer /> </LegacyContextProvider> <BoolContext.Consumer>{value => null}</BoolContext.Consumer> <ModernContextType /> <ModernContext.Provider value={contextData}> <ModernContext.Consumer>{value => null}</ModernContext.Consumer> </ModernContext.Provider> </React.Fragment>, container, ), ); const cases = [ { // <LegacyContextConsumer /> index: 1, shouldHaveLegacyContext: true, }, { // <BoolContext.Consumer> index: 2, shouldHaveLegacyContext: false, }, { // <ModernContextType /> index: 3, shouldHaveLegacyContext: false, }, { // <ModernContext.Consumer> index: 5, shouldHaveLegacyContext: false, }, ]; for (let i = 0; i < cases.length; i++) { const {index, shouldHaveLegacyContext} = cases[i]; // HACK: Recreate TestRenderer instance because we rely on default state values // from props like defaultSelectedElementID and it's easier to reset here than // to read the TreeDispatcherContext and update the selected ID that way. // We're testing the inspected values here, not the context wiring, so that's ok. utils.withErrorsOrWarningsIgnored( ['An update to %s inside a test was not wrapped in act'], () => { testRendererInstance = TestRenderer.create(null, { isConcurrent: true, }); }, ); const inspectedElement = await inspectElementAtIndex(index); expect(inspectedElement.context).not.toBe(null); expect(inspectedElement.hasLegacyContext).toBe(shouldHaveLegacyContext); } }); it('should poll for updates for the currently selected element', async () => { const Example = () => null; const container = document.createElement('div'); await utils.actAsync( () => legacyRender(<Example a={1} b="abc" />, container), false, ); let inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "a": 1, "b": "abc", } `); await utils.actAsync( () => legacyRender(<Example a={2} b="def" />, container), false, ); // TODO (cache) // This test only passes if both the check-for-updates poll AND the test renderer.update() call are included below. // It seems like either one of the two should be sufficient but: // 1. Running only check-for-updates schedules a transition that React never renders. // 2. Running only renderer.update() loads stale data (first props) // Wait for our check-for-updates poll to get the new data. jest.runOnlyPendingTimers(); await Promise.resolve(); inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "a": 2, "b": "def", } `); }); it('should not re-render a function with hooks if it did not update since it was last inspected', async () => { let targetRenderCount = 0; const Wrapper = ({children}) => children; const Target = React.memo(props => { targetRenderCount++; // Even though his hook isn't referenced, it's used to observe backend rendering. React.useState(0); return null; }); const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Wrapper> <Target a={1} b="abc" /> </Wrapper>, container, ), ); targetRenderCount = 0; let inspectedElement = await inspectElementAtIndex(1); expect(targetRenderCount).toBe(1); expect(inspectedElement.props).toMatchInlineSnapshot(` { "a": 1, "b": "abc", } `); const prevInspectedElement = inspectedElement; targetRenderCount = 0; inspectedElement = await inspectElementAtIndex(1); expect(targetRenderCount).toBe(0); expect(inspectedElement).toEqual(prevInspectedElement); targetRenderCount = 0; await utils.actAsync( () => legacyRender( <Wrapper> <Target a={2} b="def" /> </Wrapper>, container, ), false, ); // Target should have been rendered once (by ReactDOM) and once by DevTools for inspection. inspectedElement = await inspectElementAtIndex(1); expect(targetRenderCount).toBe(2); expect(inspectedElement.props).toMatchInlineSnapshot(` { "a": 2, "b": "def", } `); }); // See github.com/facebook/react/issues/22241#issuecomment-931299972 it('should properly recover from a cache miss on the frontend', async () => { let targetRenderCount = 0; const Wrapper = ({children}) => children; const Target = React.memo(props => { targetRenderCount++; // Even though his hook isn't referenced, it's used to observe backend rendering. React.useState(0); return null; }); const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Wrapper> <Target a={1} b="abc" /> </Wrapper>, container, ), ); targetRenderCount = 0; let inspectedElement = await inspectElementAtIndex(1); expect(targetRenderCount).toBe(1); expect(inspectedElement.props).toMatchInlineSnapshot(` { "a": 1, "b": "abc", } `); const prevInspectedElement = inspectedElement; // This test causes an intermediate error to be logged but we can ignore it. jest.spyOn(console, 'error').mockImplementation(() => {}); // Clear the frontend cache to simulate DevTools being closed and re-opened. // The backend still thinks the most recently-inspected element is still cached, // so the frontend needs to tell it to resend a full value. // We can verify this by asserting that the component is re-rendered again. utils.withErrorsOrWarningsIgnored( ['An update to %s inside a test was not wrapped in act'], () => { testRendererInstance = TestRenderer.create(null, { isConcurrent: true, }); }, ); const { clearCacheForTests, } = require('react-devtools-shared/src/inspectedElementMutableSource'); clearCacheForTests(); targetRenderCount = 0; inspectedElement = await inspectElementAtIndex(1); expect(targetRenderCount).toBe(1); expect(inspectedElement).toEqual(prevInspectedElement); }); it('should temporarily disable console logging when re-running a component to inspect its hooks', async () => { let targetRenderCount = 0; jest.spyOn(console, 'error').mockImplementation(() => {}); jest.spyOn(console, 'info').mockImplementation(() => {}); jest.spyOn(console, 'log').mockImplementation(() => {}); jest.spyOn(console, 'warn').mockImplementation(() => {}); const Target = React.memo(props => { targetRenderCount++; console.error('error'); console.info('info'); console.log('log'); console.warn('warn'); React.useState(0); return null; }); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await utils.actAsync(() => root.render(<Target a={1} b="abc" />)); expect(targetRenderCount).toBe(1); expect(console.error).toHaveBeenCalledTimes(1); expect(console.error).toHaveBeenCalledWith('error'); expect(console.info).toHaveBeenCalledTimes(1); expect(console.info).toHaveBeenCalledWith('info'); expect(console.log).toHaveBeenCalledTimes(1); expect(console.log).toHaveBeenCalledWith('log'); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledWith('warn'); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement).not.toBe(null); expect(targetRenderCount).toBe(2); expect(console.error).toHaveBeenCalledTimes(1); expect(console.info).toHaveBeenCalledTimes(1); expect(console.log).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledTimes(1); }); it('should support simple data types', async () => { const Example = () => null; const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Example boolean_false={false} boolean_true={true} infinity={Infinity} integer_zero={0} integer_one={1} float={1.23} string="abc" string_empty="" nan={NaN} value_null={null} value_undefined={undefined} />, container, ), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "boolean_false": false, "boolean_true": true, "float": 1.23, "infinity": Infinity, "integer_one": 1, "integer_zero": 0, "nan": NaN, "string": "abc", "string_empty": "", "value_null": null, "value_undefined": undefined, } `); }); it('should support complex data types', async () => { const Immutable = require('immutable'); const Example = () => null; const arrayOfArrays = [[['abc', 123, true], []]]; const div = document.createElement('div'); const exampleFunction = () => {}; const exampleDateISO = '2019-12-31T23:42:42.000Z'; const setShallow = new Set(['abc', 123]); const mapShallow = new Map([ ['name', 'Brian'], ['food', 'sushi'], ]); const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]); const mapOfMaps = new Map([ ['first', mapShallow], ['second', mapShallow], ]); const objectOfObjects = { inner: {string: 'abc', number: 123, boolean: true}, }; const objectWithSymbol = { [Symbol('name')]: 'hello', }; const typedArray = Int8Array.from([100, -100, 0]); const arrayBuffer = typedArray.buffer; const dataView = new DataView(arrayBuffer); const immutableMap = Immutable.fromJS({ a: [{hello: 'there'}, 'fixed', true], b: 123, c: { '1': 'xyz', xyz: 1, }, }); class Class { anonymousFunction = () => {}; } const instance = new Class(); const proxyInstance = new Proxy(() => {}, { get: function (_, name) { return function () { return null; }; }, }); const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Example anonymous_fn={instance.anonymousFunction} array_buffer={arrayBuffer} array_of_arrays={arrayOfArrays} // eslint-disable-next-line no-undef big_int={BigInt(123)} bound_fn={exampleFunction.bind(this)} data_view={dataView} date={new Date(exampleDateISO)} fn={exampleFunction} html_element={div} immutable={immutableMap} map={mapShallow} map_of_maps={mapOfMaps} object_of_objects={objectOfObjects} object_with_symbol={objectWithSymbol} proxy={proxyInstance} react_element={<span />} regexp={/abc/giu} set={setShallow} set_of_sets={setOfSets} symbol={Symbol('symbol')} typed_array={typedArray} />, container, ), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "anonymous_fn": Dehydrated { "preview_short": ƒ () {}, "preview_long": ƒ () {}, }, "array_buffer": Dehydrated { "preview_short": ArrayBuffer(3), "preview_long": ArrayBuffer(3), }, "array_of_arrays": [ Dehydrated { "preview_short": Array(2), "preview_long": [Array(3), Array(0)], }, ], "big_int": Dehydrated { "preview_short": 123n, "preview_long": 123n, }, "bound_fn": Dehydrated { "preview_short": ƒ bound exampleFunction() {}, "preview_long": ƒ bound exampleFunction() {}, }, "data_view": Dehydrated { "preview_short": DataView(3), "preview_long": DataView(3), }, "date": Dehydrated { "preview_short": Tue Dec 31 2019 23:42:42 GMT+0000 (Coordinated Universal Time), "preview_long": Tue Dec 31 2019 23:42:42 GMT+0000 (Coordinated Universal Time), }, "fn": Dehydrated { "preview_short": ƒ exampleFunction() {}, "preview_long": ƒ exampleFunction() {}, }, "html_element": Dehydrated { "preview_short": <div />, "preview_long": <div />, }, "immutable": { "0": Dehydrated { "preview_short": Array(2), "preview_long": ["a", List(3)], }, "1": Dehydrated { "preview_short": Array(2), "preview_long": ["b", 123], }, "2": Dehydrated { "preview_short": Array(2), "preview_long": ["c", Map(2)], }, }, "map": { "0": Dehydrated { "preview_short": Array(2), "preview_long": ["name", "Brian"], }, "1": Dehydrated { "preview_short": Array(2), "preview_long": ["food", "sushi"], }, }, "map_of_maps": { "0": Dehydrated { "preview_short": Array(2), "preview_long": ["first", Map(2)], }, "1": Dehydrated { "preview_short": Array(2), "preview_long": ["second", Map(2)], }, }, "object_of_objects": { "inner": Dehydrated { "preview_short": {…}, "preview_long": {boolean: true, number: 123, string: "abc"}, }, }, "object_with_symbol": { "Symbol(name)": "hello", }, "proxy": Dehydrated { "preview_short": ƒ () {}, "preview_long": ƒ () {}, }, "react_element": Dehydrated { "preview_short": <span />, "preview_long": <span />, }, "regexp": Dehydrated { "preview_short": /abc/giu, "preview_long": /abc/giu, }, "set": { "0": "abc", "1": 123, }, "set_of_sets": { "0": Dehydrated { "preview_short": Set(3), "preview_long": Set(3) {"a", "b", "c"}, }, "1": Dehydrated { "preview_short": Set(3), "preview_long": Set(3) {1, 2, 3}, }, }, "symbol": Dehydrated { "preview_short": Symbol(symbol), "preview_long": Symbol(symbol), }, "typed_array": { "0": 100, "1": -100, "2": 0, }, } `); }); it('should not consume iterables while inspecting', async () => { const Example = () => null; function* generator() { throw Error('Should not be consumed!'); } const container = document.createElement('div'); const iterable = generator(); await utils.actAsync(() => legacyRender(<Example prop={iterable} />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "prop": Dehydrated { "preview_short": Generator, "preview_long": Generator, }, } `); }); it('should support objects with no prototype', async () => { const Example = () => null; const object = Object.create(null); object.string = 'abc'; object.number = 123; object.boolean = true; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example object={object} />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "object": { "boolean": true, "number": 123, "string": "abc", }, } `); }); it('should support objects with overridden hasOwnProperty', async () => { const Example = () => null; const object = { name: 'blah', hasOwnProperty: true, }; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example object={object} />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "object": { "hasOwnProperty": true, "name": "blah", }, } `); }); it('should support custom objects with enumerable properties and getters', async () => { class CustomData { _number = 42; get number() { return this._number; } set number(value) { this._number = value; } } const descriptor = ((Object.getOwnPropertyDescriptor( CustomData.prototype, 'number', ): any): PropertyDescriptor<number>); descriptor.enumerable = true; Object.defineProperty(CustomData.prototype, 'number', descriptor); const Example = () => null; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example data={new CustomData()} />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "data": { "_number": 42, "number": 42, }, } `); }); it('should support objects with inherited keys', async () => { const Example = () => null; const base = Object.create(Object.prototype, { enumerableStringBase: { value: 1, writable: true, enumerable: true, configurable: true, }, [Symbol('enumerableSymbolBase')]: { value: 1, writable: true, enumerable: true, configurable: true, }, nonEnumerableStringBase: { value: 1, writable: true, enumerable: false, configurable: true, }, [Symbol('nonEnumerableSymbolBase')]: { value: 1, writable: true, enumerable: false, configurable: true, }, }); const object = Object.create(base, { enumerableString: { value: 2, writable: true, enumerable: true, configurable: true, }, nonEnumerableString: { value: 3, writable: true, enumerable: false, configurable: true, }, 123: { value: 3, writable: true, enumerable: true, configurable: true, }, [Symbol('nonEnumerableSymbol')]: { value: 2, writable: true, enumerable: false, configurable: true, }, [Symbol('enumerableSymbol')]: { value: 3, writable: true, enumerable: true, configurable: true, }, }); const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example object={object} />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "object": { "123": 3, "Symbol(enumerableSymbol)": 3, "Symbol(enumerableSymbolBase)": 1, "enumerableString": 2, "enumerableStringBase": 1, }, } `); }); it('should allow component prop value and value`s prototype has same name params.', async () => { const testData = Object.create( { a: undefined, b: Infinity, c: NaN, d: 'normal', }, { a: { value: undefined, writable: true, enumerable: true, configurable: true, }, b: { value: Infinity, writable: true, enumerable: true, configurable: true, }, c: { value: NaN, writable: true, enumerable: true, configurable: true, }, d: { value: 'normal', writable: true, enumerable: true, configurable: true, }, }, ); const Example = ({data}) => null; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example data={testData} />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "data": { "a": undefined, "b": Infinity, "c": NaN, "d": "normal", }, } `); }); it('should not dehydrate nested values until explicitly requested', async () => { const Example = () => { const [state] = React.useState({ foo: { bar: { baz: 'hi', }, }, }); return state.foo.bar.baz; }; const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Example nestedObject={{ a: { b: { c: [ { d: { e: {}, }, }, ], }, }, }} />, container, ), ); let inspectedElement = null; let inspectElementPath = null; // Render once to get a handle on inspectElementPath() inspectedElement = await inspectElementAtIndex(0, () => { inspectElementPath = useInspectElementPath(); }); async function loadPath(path) { await TestUtilsAct(async () => { await TestRendererAct(async () => { inspectElementPath(path); }); }); inspectedElement = await inspectElementAtIndex(0); } expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": Dehydrated { "preview_short": {…}, "preview_long": {b: {…}}, }, }, } `); await loadPath(['props', 'nestedObject', 'a']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "c": Dehydrated { "preview_short": Array(1), "preview_long": [{…}], }, }, }, }, } `); await loadPath(['props', 'nestedObject', 'a', 'b', 'c']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "c": [ { "d": Dehydrated { "preview_short": {…}, "preview_long": {e: {…}}, }, }, ], }, }, }, } `); await loadPath(['props', 'nestedObject', 'a', 'b', 'c', 0, 'd']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "c": [ { "d": { "e": {}, }, }, ], }, }, }, } `); await loadPath(['hooks', 0, 'value']); expect(inspectedElement.hooks).toMatchInlineSnapshot(` [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "Example", "lineNumber": "removed by Jest serializer", }, "id": 0, "isStateEditable": true, "name": "State", "subHooks": [], "value": { "foo": { "bar": Dehydrated { "preview_short": {…}, "preview_long": {baz: "hi"}, }, }, }, }, ] `); await loadPath(['hooks', 0, 'value', 'foo', 'bar']); expect(inspectedElement.hooks).toMatchInlineSnapshot(` [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "Example", "lineNumber": "removed by Jest serializer", }, "id": 0, "isStateEditable": true, "name": "State", "subHooks": [], "value": { "foo": { "bar": { "baz": "hi", }, }, }, }, ] `); }); it('should dehydrate complex nested values when requested', async () => { const Example = () => null; const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Example set_of_sets={new Set([new Set([1, 2, 3]), new Set(['a', 'b', 'c'])])} />, container, ), ); let inspectedElement = null; let inspectElementPath = null; // Render once to get a handle on inspectElementPath() inspectedElement = await inspectElementAtIndex(0, () => { inspectElementPath = useInspectElementPath(); }); async function loadPath(path) { await TestUtilsAct(async () => { await TestRendererAct(async () => { inspectElementPath(path); }); }); inspectedElement = await inspectElementAtIndex(0); } expect(inspectedElement.props).toMatchInlineSnapshot(` { "set_of_sets": { "0": Dehydrated { "preview_short": Set(3), "preview_long": Set(3) {1, 2, 3}, }, "1": Dehydrated { "preview_short": Set(3), "preview_long": Set(3) {"a", "b", "c"}, }, }, } `); await loadPath(['props', 'set_of_sets', 0]); expect(inspectedElement.props).toMatchInlineSnapshot(` { "set_of_sets": { "0": { "0": 1, "1": 2, "2": 3, }, "1": Dehydrated { "preview_short": Set(3), "preview_long": Set(3) {"a", "b", "c"}, }, }, } `); }); it('should include updates for nested values that were previously hydrated', async () => { const Example = () => null; const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Example nestedObject={{ a: { value: 1, b: { value: 1, }, }, c: { value: 1, d: { value: 1, e: { value: 1, }, }, }, }} />, container, ), ); let inspectedElement = null; let inspectElementPath = null; // Render once to get a handle on inspectElementPath() inspectedElement = await inspectElementAtIndex(0, () => { inspectElementPath = useInspectElementPath(); }); async function loadPath(path) { await TestUtilsAct(async () => { await TestRendererAct(async () => { inspectElementPath(path); }); }); inspectedElement = await inspectElementAtIndex(0); } expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": Dehydrated { "preview_short": {…}, "preview_long": {b: {…}, value: 1}, }, "c": Dehydrated { "preview_short": {…}, "preview_long": {d: {…}, value: 1}, }, }, } `); await loadPath(['props', 'nestedObject', 'a']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "value": 1, }, "value": 1, }, "c": Dehydrated { "preview_short": {…}, "preview_long": {d: {…}, value: 1}, }, }, } `); await loadPath(['props', 'nestedObject', 'c']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "value": 1, }, "value": 1, }, "c": { "d": { "e": Dehydrated { "preview_short": {…}, "preview_long": {value: 1}, }, "value": 1, }, "value": 1, }, }, } `); await TestRendererAct(async () => { await TestUtilsAct(async () => { legacyRender( <Example nestedObject={{ a: { value: 2, b: { value: 2, }, }, c: { value: 2, d: { value: 2, e: { value: 2, }, }, }, }} />, container, ); }); }); // Wait for pending poll-for-update and then update inspected element data. jest.runOnlyPendingTimers(); await Promise.resolve(); inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "value": 2, }, "value": 2, }, "c": { "d": { "e": Dehydrated { "preview_short": {…}, "preview_long": {value: 2}, }, "value": 2, }, "value": 2, }, }, } `); }); it('should return a full update if a path is inspected for an object that has other pending changes', async () => { const Example = () => null; const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Example nestedObject={{ a: { value: 1, b: { value: 1, }, }, c: { value: 1, d: { value: 1, e: { value: 1, }, }, }, }} />, container, ), ); let inspectedElement = null; let inspectElementPath = null; // Render once to get a handle on inspectElementPath() inspectedElement = await inspectElementAtIndex(0, () => { inspectElementPath = useInspectElementPath(); }); async function loadPath(path) { await TestUtilsAct(async () => { await TestRendererAct(() => { inspectElementPath(path); }); }); inspectedElement = await inspectElementAtIndex(0); } expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": Dehydrated { "preview_short": {…}, "preview_long": {b: {…}, value: 1}, }, "c": Dehydrated { "preview_short": {…}, "preview_long": {d: {…}, value: 1}, }, }, } `); await loadPath(['props', 'nestedObject', 'a']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "value": 1, }, "value": 1, }, "c": Dehydrated { "preview_short": {…}, "preview_long": {d: {…}, value: 1}, }, }, } `); await TestRendererAct(async () => { await TestUtilsAct(async () => { legacyRender( <Example nestedObject={{ a: { value: 2, b: { value: 2, }, }, c: { value: 2, d: { value: 2, e: { value: 2, }, }, }, }} />, container, ); }); }); await loadPath(['props', 'nestedObject', 'c']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "value": 2, }, "value": 2, }, "c": { "d": { "e": Dehydrated { "preview_short": {…}, "preview_long": {value: 2}, }, "value": 2, }, "value": 2, }, }, } `); }); it('should not tear if hydration is requested after an update', async () => { const Example = () => null; const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <Example nestedObject={{ value: 1, a: { value: 1, b: { value: 1, }, }, }} />, container, ), ); let inspectedElement = null; let inspectElementPath = null; // Render once to get a handle on inspectElementPath() inspectedElement = await inspectElementAtIndex(0, () => { inspectElementPath = useInspectElementPath(); }); async function loadPath(path) { await TestUtilsAct(async () => { await TestRendererAct(() => { inspectElementPath(path); }); }); inspectedElement = await inspectElementAtIndex(0); } expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": Dehydrated { "preview_short": {…}, "preview_long": {b: {…}, value: 1}, }, "value": 1, }, } `); await TestUtilsAct(async () => { legacyRender( <Example nestedObject={{ value: 2, a: { value: 2, b: { value: 2, }, }, }} />, container, ); }); await loadPath(['props', 'nestedObject', 'a']); expect(inspectedElement.props).toMatchInlineSnapshot(` { "nestedObject": { "a": { "b": { "value": 2, }, "value": 2, }, "value": 2, }, } `); }); it('should inspect hooks for components that only use context', async () => { const Context = React.createContext(true); const Example = () => { const value = React.useContext(Context); return value; }; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example a={1} b="abc" />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement).toMatchInlineSnapshot(` { "context": null, "events": undefined, "hooks": [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "Example", "lineNumber": "removed by Jest serializer", }, "id": null, "isStateEditable": false, "name": "Context", "subHooks": [], "value": true, }, ], "id": 2, "owners": null, "props": { "a": 1, "b": "abc", }, "rootType": "render()", "state": null, } `); }); it('should enable inspected values to be stored as global variables', async () => { const Example = () => null; const nestedObject = { a: { value: 1, b: { value: 1, c: { value: 1, }, }, }, }; await utils.actAsync(() => legacyRender( <Example nestedObject={nestedObject} />, document.createElement('div'), ), ); let storeAsGlobal: StoreAsGlobal = ((null: any): StoreAsGlobal); const id = ((store.getElementIDAtIndex(0): any): number); await inspectElementAtIndex(0, () => { storeAsGlobal = (path: Array<string | number>) => { const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { const { storeAsGlobal: storeAsGlobalAPI, } = require('react-devtools-shared/src/backendAPI'); storeAsGlobalAPI({ bridge, id, path, rendererID, }); } }; }); jest.spyOn(console, 'log').mockImplementation(() => {}); // Should store the whole value (not just the hydrated parts) storeAsGlobal(['props', 'nestedObject']); jest.runOnlyPendingTimers(); expect(console.log).toHaveBeenCalledWith('$reactTemp0'); expect(global.$reactTemp0).toBe(nestedObject); console.log.mockReset(); // Should store the nested property specified (not just the outer value) storeAsGlobal(['props', 'nestedObject', 'a', 'b']); jest.runOnlyPendingTimers(); expect(console.log).toHaveBeenCalledWith('$reactTemp1'); expect(global.$reactTemp1).toBe(nestedObject.a.b); }); it('should enable inspected values to be copied to the clipboard', async () => { const Example = () => null; const nestedObject = { a: { value: 1, b: { value: 1, c: { value: 1, }, }, }, }; await utils.actAsync(() => legacyRender( <Example nestedObject={nestedObject} />, document.createElement('div'), ), ); let copyPath: CopyInspectedElementPath = ((null: any): CopyInspectedElementPath); const id = ((store.getElementIDAtIndex(0): any): number); await inspectElementAtIndex(0, () => { copyPath = (path: Array<string | number>) => { const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { const { copyInspectedElementPath, } = require('react-devtools-shared/src/backendAPI'); copyInspectedElementPath({ bridge, id, path, rendererID, }); } }; }); // Should copy the whole value (not just the hydrated parts) copyPath(['props', 'nestedObject']); jest.runOnlyPendingTimers(); expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1); expect(global.mockClipboardCopy).toHaveBeenCalledWith( JSON.stringify(nestedObject, undefined, 2), ); global.mockClipboardCopy.mockReset(); // Should copy the nested property specified (not just the outer value) copyPath(['props', 'nestedObject', 'a', 'b']); jest.runOnlyPendingTimers(); expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1); expect(global.mockClipboardCopy).toHaveBeenCalledWith( JSON.stringify(nestedObject.a.b, undefined, 2), ); }); it('should enable complex values to be copied to the clipboard', async () => { const Immutable = require('immutable'); const Example = () => null; const set = new Set(['abc', 123]); const map = new Map([ ['name', 'Brian'], ['food', 'sushi'], ]); const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]); const mapOfMaps = new Map([ ['first', map], ['second', map], ]); const typedArray = Int8Array.from([100, -100, 0]); const arrayBuffer = typedArray.buffer; const dataView = new DataView(arrayBuffer); const immutable = Immutable.fromJS({ a: [{hello: 'there'}, 'fixed', true], b: 123, c: { '1': 'xyz', xyz: 1, }, }); const bigInt = BigInt(123); // eslint-disable-line no-undef await utils.actAsync(() => legacyRender( <Example arrayBuffer={arrayBuffer} dataView={dataView} map={map} set={set} mapOfMaps={mapOfMaps} setOfSets={setOfSets} typedArray={typedArray} immutable={immutable} bigInt={bigInt} />, document.createElement('div'), ), ); const id = ((store.getElementIDAtIndex(0): any): number); let copyPath: CopyInspectedElementPath = ((null: any): CopyInspectedElementPath); await inspectElementAtIndex(0, () => { copyPath = (path: Array<string | number>) => { const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { const { copyInspectedElementPath, } = require('react-devtools-shared/src/backendAPI'); copyInspectedElementPath({ bridge, id, path, rendererID, }); } }; }); // Should copy the whole value (not just the hydrated parts) copyPath(['props']); jest.runOnlyPendingTimers(); // Should not error despite lots of unserialized values. global.mockClipboardCopy.mockReset(); // Should copy the nested property specified (not just the outer value) copyPath(['props', 'bigInt']); jest.runOnlyPendingTimers(); expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1); expect(global.mockClipboardCopy).toHaveBeenCalledWith( JSON.stringify('123n', undefined, 2), ); global.mockClipboardCopy.mockReset(); // Should copy the nested property specified (not just the outer value) copyPath(['props', 'typedArray']); jest.runOnlyPendingTimers(); expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1); expect(global.mockClipboardCopy).toHaveBeenCalledWith( JSON.stringify({0: 100, 1: -100, 2: 0}, undefined, 2), ); }); it('should display complex values of useDebugValue', async () => { const container = document.createElement('div'); function useDebuggableHook() { React.useDebugValue({foo: 2}); React.useState(1); return 1; } function DisplayedComplexValue() { useDebuggableHook(); return null; } await utils.actAsync(() => legacyRender(<DisplayedComplexValue />, container), ); const {hooks} = await inspectElementAtIndex(0); expect(hooks).toMatchInlineSnapshot(` [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "DisplayedComplexValue", "lineNumber": "removed by Jest serializer", }, "id": null, "isStateEditable": false, "name": "DebuggableHook", "subHooks": [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "useDebuggableHook", "lineNumber": "removed by Jest serializer", }, "id": 0, "isStateEditable": true, "name": "State", "subHooks": [], "value": 1, }, ], "value": { "foo": 2, }, }, ] `); }); // See github.com/facebook/react/issues/21654 it('should support Proxies that dont return an iterator', async () => { const Example = () => null; const proxy = new Proxy( {}, { get: (target, prop, receiver) => { target[prop] = value => {}; return target[prop]; }, }, ); const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example proxy={proxy} />, container), ); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.props).toMatchInlineSnapshot(` { "proxy": { "$$typeof": Dehydrated { "preview_short": ƒ () {}, "preview_long": ƒ () {}, }, "Symbol(Symbol.iterator)": Dehydrated { "preview_short": ƒ () {}, "preview_long": ƒ () {}, }, "constructor": Dehydrated { "preview_short": ƒ () {}, "preview_long": ƒ () {}, }, }, } `); }); // Regression test for github.com/facebook/react/issues/22099 it('should not error when an unchanged component is re-inspected after component filters changed', async () => { const Example = () => <div />; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example />, container)); // Select/inspect element let inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement).toMatchInlineSnapshot(` { "context": null, "events": undefined, "hooks": null, "id": 2, "owners": null, "props": {}, "rootType": "render()", "state": null, } `); await utils.actAsync(async () => { // Ignore transient warning this causes utils.withErrorsOrWarningsIgnored(['No element found with id'], () => { store.componentFilters = []; // Flush events to the renderer. jest.runOnlyPendingTimers(); }); }, false); // HACK: Recreate TestRenderer instance because we rely on default state values // from props like defaultSelectedElementID and it's easier to reset here than // to read the TreeDispatcherContext and update the selected ID that way. // We're testing the inspected values here, not the context wiring, so that's ok. utils.withErrorsOrWarningsIgnored( ['An update to %s inside a test was not wrapped in act'], () => { testRendererInstance = TestRenderer.create(null, { isConcurrent: true, }); }, ); // Select/inspect the same element again inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement).toMatchInlineSnapshot(` { "context": null, "events": undefined, "hooks": null, "id": 2, "owners": null, "props": {}, "rootType": "render()", "state": null, } `); }); it('should display the root type for ReactDOM.hydrate', async () => { const Example = () => <div />; await utils.actAsync(() => { const container = document.createElement('div'); container.innerHTML = '<div></div>'; withErrorsOrWarningsIgnored( ['ReactDOM.hydrate is no longer supported in React 18'], () => { ReactDOM.hydrate(<Example />, container); }, ); }, false); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.rootType).toMatchInlineSnapshot(`"hydrate()"`); }); it('should display the root type for ReactDOM.render', async () => { const Example = () => <div />; await utils.actAsync(() => { const container = document.createElement('div'); legacyRender(<Example />, container); }, false); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.rootType).toMatchInlineSnapshot(`"render()"`); }); it('should display the root type for ReactDOMClient.hydrateRoot', async () => { const Example = () => <div />; await utils.actAsync(() => { const container = document.createElement('div'); container.innerHTML = '<div></div>'; ReactDOMClient.hydrateRoot(container, <Example />); }, false); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.rootType).toMatchInlineSnapshot(`"hydrateRoot()"`); }); it('should display the root type for ReactDOMClient.createRoot', async () => { const Example = () => <div />; await utils.actAsync(() => { const container = document.createElement('div'); ReactDOMClient.createRoot(container).render(<Example />); }, false); const inspectedElement = await inspectElementAtIndex(0); expect(inspectedElement.rootType).toMatchInlineSnapshot(`"createRoot()"`); }); it('should gracefully surface backend errors on the frontend rather than timing out', async () => { jest.spyOn(console, 'error').mockImplementation(() => {}); let shouldThrow = false; const Example = () => { const [count] = React.useState(0); if (shouldThrow) { throw Error('Expected'); } else { return count; } }; await utils.actAsync(() => { const container = document.createElement('div'); ReactDOMClient.createRoot(container).render(<Example />); }, false); shouldThrow = true; const value = await inspectElementAtIndex(0, noop, true); expect(value).toBe(null); const error = errorBoundaryInstance.state.error; expect(error.message).toBe('Expected'); expect(error.stack).toContain('inspectHooksOfFiber'); }); describe('$r', () => { it('should support function components', async () => { const Example = () => { const [count] = React.useState(1); return count; }; const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example a={1} b="abc" />, container), ); await inspectElementAtIndex(0); expect(global.$r).toMatchInlineSnapshot(` { "hooks": [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "Example", "lineNumber": "removed by Jest serializer", }, "id": 0, "isStateEditable": true, "name": "State", "subHooks": [], "value": 1, }, ], "props": { "a": 1, "b": "abc", }, "type": [Function], } `); }); it('should support memoized function components', async () => { const Example = React.memo(function Example(props) { const [count] = React.useState(1); return count; }); const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example a={1} b="abc" />, container), ); await inspectElementAtIndex(0); expect(global.$r).toMatchInlineSnapshot(` { "hooks": [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "Example", "lineNumber": "removed by Jest serializer", }, "id": 0, "isStateEditable": true, "name": "State", "subHooks": [], "value": 1, }, ], "props": { "a": 1, "b": "abc", }, "type": [Function], } `); }); it('should support forward refs', async () => { const Example = React.forwardRef(function Example(props, ref) { const [count] = React.useState(1); return count; }); const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example a={1} b="abc" />, container), ); await inspectElementAtIndex(0); expect(global.$r).toMatchInlineSnapshot(` { "hooks": [ { "hookSource": { "columnNumber": "removed by Jest serializer", "fileName": "react-devtools-shared/src/__tests__/inspectedElement-test.js", "functionName": "Example", "lineNumber": "removed by Jest serializer", }, "id": 0, "isStateEditable": true, "name": "State", "subHooks": [], "value": 1, }, ], "props": { "a": 1, "b": "abc", }, "type": [Function], } `); }); it('should support class components', async () => { class Example extends React.Component { state = { count: 0, }; render() { return null; } } const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<Example a={1} b="abc" />, container), ); await inspectElementAtIndex(0); expect(global.$r.props).toMatchInlineSnapshot(` { "a": 1, "b": "abc", } `); expect(global.$r.state).toMatchInlineSnapshot(` { "count": 0, } `); }); }); describe('inline errors and warnings', () => { async function getErrorsAndWarningsForElementAtIndex(index) { const id = ((store.getElementIDAtIndex(index): any): number); if (id == null) { throw Error(`Element at index "${index}"" not found in store`); } let errors = null; let warnings = null; function Suspender({target}) { const inspectedElement = useInspectedElement(); errors = inspectedElement.errors; warnings = inspectedElement.warnings; return null; } let root; await utils.actAsync(() => { root = TestRenderer.create( <Contexts defaultSelectedElementID={id} defaultSelectedElementIndex={index}> <React.Suspense fallback={null}> <Suspender target={id} /> </React.Suspense> </Contexts>, {isConcurrent: true}, ); }, false); await utils.actAsync(() => { root.unmount(); }, false); return {errors, warnings}; } it('during render get recorded', async () => { const Example = () => { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; }; const container = document.createElement('div'); await withErrorsOrWarningsIgnored(['test-only: '], async () => { await utils.actAsync(() => legacyRender(<Example repeatWarningCount={1} />, container), ); }); const data = await getErrorsAndWarningsForElementAtIndex(0); expect(data).toMatchInlineSnapshot(` { "errors": [ [ "test-only: render error", 1, ], ], "warnings": [ [ "test-only: render warning", 1, ], ], } `); }); it('during render get deduped', async () => { const Example = () => { console.error('test-only: render error'); console.error('test-only: render error'); console.warn('test-only: render warning'); console.warn('test-only: render warning'); console.warn('test-only: render warning'); return null; }; const container = document.createElement('div'); await utils.withErrorsOrWarningsIgnored(['test-only:'], async () => { await utils.actAsync(() => legacyRender(<Example repeatWarningCount={1} />, container), ); }); const data = await getErrorsAndWarningsForElementAtIndex(0); expect(data).toMatchInlineSnapshot(` { "errors": [ [ "test-only: render error", 2, ], ], "warnings": [ [ "test-only: render warning", 3, ], ], } `); }); it('during layout (mount) get recorded', async () => { const Example = () => { // Note we only test mount because once the component unmounts, // it is no longer in the store and warnings are ignored. React.useLayoutEffect(() => { console.error('test-only: useLayoutEffect error'); console.warn('test-only: useLayoutEffect warning'); }, []); return null; }; const container = document.createElement('div'); await utils.withErrorsOrWarningsIgnored(['test-only:'], async () => { await utils.actAsync(() => legacyRender(<Example repeatWarningCount={1} />, container), ); }); const data = await getErrorsAndWarningsForElementAtIndex(0); expect(data).toMatchInlineSnapshot(` { "errors": [ [ "test-only: useLayoutEffect error", 1, ], ], "warnings": [ [ "test-only: useLayoutEffect warning", 1, ], ], } `); }); it('during passive (mount) get recorded', async () => { const Example = () => { // Note we only test mount because once the component unmounts, // it is no longer in the store and warnings are ignored. React.useEffect(() => { console.error('test-only: useEffect error'); console.warn('test-only: useEffect warning'); }, []); return null; }; const container = document.createElement('div'); await utils.withErrorsOrWarningsIgnored(['test-only:'], async () => { await utils.actAsync(() => legacyRender(<Example repeatWarningCount={1} />, container), ); }); const data = await getErrorsAndWarningsForElementAtIndex(0); expect(data).toMatchInlineSnapshot(` { "errors": [ [ "test-only: useEffect error", 1, ], ], "warnings": [ [ "test-only: useEffect warning", 1, ], ], } `); }); it('from react get recorded without a component stack', async () => { const Example = () => { return [<div />]; }; const container = document.createElement('div'); await utils.withErrorsOrWarningsIgnored( ['Warning: Each child in a list should have a unique "key" prop.'], async () => { await utils.actAsync(() => legacyRender(<Example repeatWarningCount={1} />, container), ); }, ); const data = await getErrorsAndWarningsForElementAtIndex(0); expect(data).toMatchInlineSnapshot(` { "errors": [ [ "Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information. at Example", 1, ], ], "warnings": [], } `); }); it('can be cleared for the whole app', async () => { const Example = () => { console.error('test-only: render error'); console.warn('test-only: render warning'); return null; }; const container = document.createElement('div'); await utils.withErrorsOrWarningsIgnored(['test-only:'], async () => { await utils.actAsync(() => legacyRender(<Example repeatWarningCount={1} />, container), ); }); const { clearErrorsAndWarnings, } = require('react-devtools-shared/src/backendAPI'); clearErrorsAndWarnings({bridge, store}); // Flush events to the renderer. jest.runOnlyPendingTimers(); const data = await getErrorsAndWarningsForElementAtIndex(0); expect(data).toMatchInlineSnapshot(` { "errors": [], "warnings": [], } `); }); it('can be cleared for a particular Fiber (only warnings)', async () => { const Example = ({id}) => { console.error(`test-only: render error #${id}`); console.warn(`test-only: render warning #${id}`); return null; }; const container = document.createElement('div'); await utils.withErrorsOrWarningsIgnored(['test-only:'], async () => { await utils.actAsync(() => legacyRender( <React.Fragment> <Example id={1} /> <Example id={2} /> </React.Fragment>, container, ), ); }); let 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.runOnlyPendingTimers(); let data = [ await getErrorsAndWarningsForElementAtIndex(0), await getErrorsAndWarningsForElementAtIndex(1), ]; expect(data).toMatchInlineSnapshot(` [ { "errors": [ [ "test-only: render error #1", 1, ], ], "warnings": [ [ "test-only: render warning #1", 1, ], ], }, { "errors": [ [ "test-only: render error #2", 1, ], ], "warnings": [], }, ] `); id = ((store.getElementIDAtIndex(0): any): number); clearWarningsForElement({bridge, id, rendererID}); // Flush events to the renderer. jest.runOnlyPendingTimers(); data = [ await getErrorsAndWarningsForElementAtIndex(0), await getErrorsAndWarningsForElementAtIndex(1), ]; expect(data).toMatchInlineSnapshot(` [ { "errors": [ [ "test-only: render error #1", 1, ], ], "warnings": [], }, { "errors": [ [ "test-only: render error #2", 1, ], ], "warnings": [], }, ] `); }); it('can be cleared for a particular Fiber (only errors)', async () => { const Example = ({id}) => { console.error(`test-only: render error #${id}`); console.warn(`test-only: render warning #${id}`); return null; }; const container = document.createElement('div'); await utils.withErrorsOrWarningsIgnored(['test-only:'], async () => { await utils.actAsync(() => legacyRender( <React.Fragment> <Example id={1} /> <Example id={2} /> </React.Fragment>, container, ), ); }); let 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.runOnlyPendingTimers(); let data = [ await getErrorsAndWarningsForElementAtIndex(0), await getErrorsAndWarningsForElementAtIndex(1), ]; expect(data).toMatchInlineSnapshot(` [ { "errors": [ [ "test-only: render error #1", 1, ], ], "warnings": [ [ "test-only: render warning #1", 1, ], ], }, { "errors": [], "warnings": [ [ "test-only: render warning #2", 1, ], ], }, ] `); id = ((store.getElementIDAtIndex(0): any): number); clearErrorsForElement({bridge, id, rendererID}); // Flush events to the renderer. jest.runOnlyPendingTimers(); data = [ await getErrorsAndWarningsForElementAtIndex(0), await getErrorsAndWarningsForElementAtIndex(1), ]; expect(data).toMatchInlineSnapshot(` [ { "errors": [], "warnings": [ [ "test-only: render warning #1", 1, ], ], }, { "errors": [], "warnings": [ [ "test-only: render warning #2", 1, ], ], }, ] `); }); }); it('inspecting nested renderers should not throw', async () => { // Ignoring react art warnings jest.spyOn(console, 'error').mockImplementation(() => {}); const ReactArt = require('react-art'); const ArtSVGMode = require('art/modes/svg'); const ARTCurrentMode = require('art/modes/current'); store.componentFilters = []; ARTCurrentMode.setCurrent(ArtSVGMode); const {Surface, Group} = ReactArt; function Child() { return ( <Surface width={1} height={1}> <Group /> </Surface> ); } function App() { return <Child />; } await utils.actAsync(() => { legacyRender(<App />, document.createElement('div')); }); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> ▾ <Child> ▾ <Surface> <svg> [root] <Group> `); const inspectedElement = await inspectElementAtIndex(4); expect(inspectedElement.owners).toMatchInlineSnapshot(` [ { "compiledWithForget": false, "displayName": "Child", "hocDisplayNames": null, "id": 3, "key": null, "type": 5, }, { "compiledWithForget": false, "displayName": "App", "hocDisplayNames": null, "id": 2, "key": null, "type": 5, }, ] `); }); describe('error boundary', () => { it('can toggle error', async () => { class LocalErrorBoundary extends React.Component<any> { state = {hasError: false}; static getDerivedStateFromError(error) { return {hasError: true}; } render() { const {hasError} = this.state; return hasError ? 'has-error' : this.props.children; } } const Example = () => 'example'; await utils.actAsync(() => legacyRender( <LocalErrorBoundary> <Example /> </LocalErrorBoundary>, document.createElement('div'), ), ); const targetErrorBoundaryID = ((store.getElementIDAtIndex( 0, ): any): number); const inspect = index => { // HACK: Recreate TestRenderer instance so we can inspect different elements utils.withErrorsOrWarningsIgnored( ['An update to %s inside a test was not wrapped in act'], () => { testRendererInstance = TestRenderer.create(null, { isConcurrent: true, }); }, ); return inspectElementAtIndex(index); }; const toggleError = async forceError => { await withErrorsOrWarningsIgnored(['ErrorBoundary'], async () => { await TestUtilsAct(async () => { bridge.send('overrideError', { id: targetErrorBoundaryID, rendererID: store.getRendererIDForElement(targetErrorBoundaryID), forceError, }); }); }); await TestUtilsAct(async () => { jest.runOnlyPendingTimers(); }); }; // Inspect <ErrorBoundary /> and see that we cannot toggle error state // on error boundary itself let inspectedElement = await inspect(0); expect(inspectedElement.canToggleError).toBe(false); expect(inspectedElement.targetErrorBoundaryID).toBe(null); // Inspect <Example /> inspectedElement = await inspect(1); expect(inspectedElement.canToggleError).toBe(true); expect(inspectedElement.isErrored).toBe(false); expect(inspectedElement.targetErrorBoundaryID).toBe( targetErrorBoundaryID, ); // Suppress expected error and warning. const consoleErrorMock = jest .spyOn(console, 'error') .mockImplementation(() => {}); const consoleWarnMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); // now force error state on <Example /> await toggleError(true); consoleErrorMock.mockRestore(); consoleWarnMock.mockRestore(); // we are in error state now, <Example /> won't show up withErrorsOrWarningsIgnored(['Invalid index'], () => { expect(store.getElementIDAtIndex(1)).toBe(null); }); // Inpsect <ErrorBoundary /> to toggle off the error state inspectedElement = await inspect(0); expect(inspectedElement.canToggleError).toBe(true); expect(inspectedElement.isErrored).toBe(true); // its error boundary ID is itself because it's caught the error expect(inspectedElement.targetErrorBoundaryID).toBe( targetErrorBoundaryID, ); await toggleError(false); // We can now inspect <Example /> with ability to toggle again inspectedElement = await inspect(1); expect(inspectedElement.canToggleError).toBe(true); expect(inspectedElement.isErrored).toBe(false); expect(inspectedElement.targetErrorBoundaryID).toBe( targetErrorBoundaryID, ); }); }); });
26.149862
141
0.520076
owtf
/** * Supports render.html, a piece of the hydration fixture. See /hydration */ 'use strict'; (function () { var Fixture = null; var output = document.getElementById('output'); var status = document.getElementById('status'); var hydrate = document.getElementById('hydrate'); var reload = document.getElementById('reload'); var renders = 0; var failed = false; var needsReactDOM = getBooleanQueryParam('needsReactDOM'); var needsCreateElement = getBooleanQueryParam('needsCreateElement'); function unmountComponent(node) { // ReactDOM was moved into a separate package in 0.14 if (needsReactDOM) { ReactDOM.unmountComponentAtNode(node); } else if (React.unmountComponentAtNode) { React.unmountComponentAtNode(node); } else { // Unmounting for React 0.4 and lower React.unmountAndReleaseReactRootNode(node); } } function createElement(value) { // React.createElement replaced function invocation in 0.12 if (needsCreateElement) { return React.createElement(value); } else { return value(); } } function getQueryParam(key) { var pattern = new RegExp(key + '=([^&]+)(&|$)'); var matches = window.location.search.match(pattern); if (matches) { return decodeURIComponent(matches[1]); } handleError(new Error('No key found for' + key)); } function getBooleanQueryParam(key) { return getQueryParam(key) === 'true'; } function setStatus(label) { status.innerHTML = label; } function prerender() { setStatus('Generating markup'); return Promise.resolve() .then(function () { const element = createElement(Fixture); // Server rendering moved to a separate package along with ReactDOM // in 0.14.0 if (needsReactDOM) { return ReactDOMServer.renderToString(element); } // React.renderComponentToString was renamed in 0.12 if (React.renderToString) { return React.renderToString(element); } // React.renderComponentToString became synchronous in React 0.9.0 if (React.renderComponentToString.length === 1) { return React.renderComponentToString(element); } // Finally, React 0.4 and lower emits markup in a callback return new Promise(function (resolve) { React.renderComponentToString(element, resolve); }); }) .then(function (string) { output.innerHTML = string; setStatus('Markup only (No React)'); }) .catch(handleError); } function render() { setStatus('Hydrating'); var element = createElement(Fixture); // ReactDOM was split out into another package in 0.14 if (needsReactDOM) { // Hydration changed to a separate method in React 16 if (ReactDOM.hydrate) { ReactDOM.hydrate(element, output); } else { ReactDOM.render(element, output); } } else if (React.render) { // React.renderComponent was renamed in 0.12 React.render(element, output); } else { React.renderComponent(element, output); } setStatus(renders > 0 ? 'Re-rendered (' + renders + 'x)' : 'Hydrated'); renders += 1; hydrate.innerHTML = 'Re-render'; } function handleError(error) { console.log(error); failed = true; setStatus('Javascript Error'); output.innerHTML = error; } function loadScript(src) { return new Promise(function (resolve, reject) { var script = document.createElement('script'); script.async = true; script.src = src; script.onload = resolve; script.onerror = function (error) { reject(new Error('Unable to load ' + src)); }; document.body.appendChild(script); }); } function injectFixture(src) { Fixture = new Function(src + '\nreturn Fixture;')(); if (typeof Fixture === 'undefined') { setStatus('Failed'); output.innerHTML = 'Please name your root component "Fixture"'; } else { prerender().then(function () { if (getBooleanQueryParam('hydrate')) { render(); } }); } } function reloadFixture(code) { renders = 0; unmountComponent(output); injectFixture(code); } window.onerror = handleError; reload.onclick = function () { window.location.reload(); }; hydrate.onclick = render; loadScript(getQueryParam('reactPath')) .then(function () { if (needsReactDOM) { return Promise.all([ loadScript(getQueryParam('reactDOMPath')), loadScript(getQueryParam('reactDOMServerPath')), ]); } }) .then(function () { if (failed) { return; } window.addEventListener('message', function (event) { var data = JSON.parse(event.data); switch (data.type) { case 'code': reloadFixture(data.payload); break; default: throw new Error( 'Renderer Error: Unrecognized message "' + data.type + '"' ); } }); window.parent.postMessage(JSON.stringify({type: 'ready'}), '*'); }) .catch(handleError); })();
24.910891
75
0.611122
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. */ 'use strict'; // TODO: Move flattenStyle into react function flattenStyle() {} module.exports = flattenStyle;
19.4
66
0.718033
owtf
import React from 'react'; import {createElement} from 'glamor/react'; // eslint-disable-line /* @jsx createElement */ import {MultiGrid, AutoSizer} from 'react-virtualized'; import 'react-virtualized/styles.css'; import FileSaver from 'file-saver'; import { inject as injectErrorOverlay, uninject as uninjectErrorOverlay, } from 'react-error-overlay/lib/overlay'; import attributes from './attributes'; const types = [ { name: 'string', testValue: 'a string', testDisplayValue: "'a string'", }, { name: 'empty string', testValue: '', testDisplayValue: "''", }, { name: 'array with string', testValue: ['string'], testDisplayValue: "['string']", }, { name: 'empty array', testValue: [], testDisplayValue: '[]', }, { name: 'object', testValue: { toString() { return 'result of toString()'; }, }, testDisplayValue: "{ toString() { return 'result of toString()'; } }", }, { name: 'numeric string', testValue: '42', displayValue: "'42'", }, { name: '-1', testValue: -1, }, { name: '0', testValue: 0, }, { name: 'integer', testValue: 1, }, { name: 'NaN', testValue: NaN, }, { name: 'float', testValue: 99.99, }, { name: 'true', testValue: true, }, { name: 'false', testValue: false, }, { name: "string 'true'", testValue: 'true', displayValue: "'true'", }, { name: "string 'false'", testValue: 'false', displayValue: "'false'", }, { name: "string 'on'", testValue: 'on', displayValue: "'on'", }, { name: "string 'off'", testValue: 'off', displayValue: "'off'", }, { name: 'symbol', testValue: Symbol('foo'), testDisplayValue: "Symbol('foo')", }, { name: 'function', testValue: function f() {}, }, { name: 'null', testValue: null, }, { name: 'undefined', testValue: undefined, }, ]; const ALPHABETICAL = 'alphabetical'; const REV_ALPHABETICAL = 'reverse_alphabetical'; const GROUPED_BY_ROW_PATTERN = 'grouped_by_row_pattern'; const ALL = 'all'; const COMPLETE = 'complete'; const INCOMPLETE = 'incomplete'; function getCanonicalizedValue(value) { switch (typeof value) { case 'undefined': return '<undefined>'; case 'object': if (value === null) { return '<null>'; } if ('baseVal' in value) { return getCanonicalizedValue(value.baseVal); } if (value instanceof SVGLength) { return '<SVGLength: ' + value.valueAsString + '>'; } if (value instanceof SVGRect) { return ( '<SVGRect: ' + [value.x, value.y, value.width, value.height].join(',') + '>' ); } if (value instanceof SVGPreserveAspectRatio) { return ( '<SVGPreserveAspectRatio: ' + value.align + '/' + value.meetOrSlice + '>' ); } if (value instanceof SVGNumber) { return value.value; } if (value instanceof SVGMatrix) { return ( '<SVGMatrix ' + value.a + ' ' + value.b + ' ' + value.c + ' ' + value.d + ' ' + value.e + ' ' + value.f + '>' ); } if (value instanceof SVGTransform) { return ( getCanonicalizedValue(value.matrix) + '/' + value.type + '/' + value.angle ); } if (typeof value.length === 'number') { return ( '[' + Array.from(value) .map(v => getCanonicalizedValue(v)) .join(', ') + ']' ); } let name = (value.constructor && value.constructor.name) || 'object'; return '<' + name + '>'; case 'function': return '<function>'; case 'symbol': return '<symbol>'; case 'number': return `<number: ${value}>`; case 'string': if (value === '') { return '<empty string>'; } return '"' + value + '"'; case 'boolean': return `<boolean: ${value}>`; default: throw new Error('Switch statement should be exhaustive.'); } } let _didWarn = false; function warn(str) { if (str.includes('ReactDOM.render is no longer supported')) { return; } _didWarn = true; } const UNKNOWN_HTML_TAGS = new Set(['keygen', 'time', 'command']); function getRenderedAttributeValue( react, renderer, serverRenderer, attribute, type ) { const originalConsoleError = console.error; console.error = warn; const containerTagName = attribute.containerTagName || 'div'; const tagName = attribute.tagName || 'div'; function createContainer() { if (containerTagName === 'svg') { return document.createElementNS('http://www.w3.org/2000/svg', 'svg'); } else if (containerTagName === 'document') { return document.implementation.createHTMLDocument(''); } else if (containerTagName === 'head') { return document.implementation.createHTMLDocument('').head; } else { return document.createElement(containerTagName); } } const read = attribute.read; let testValue = type.testValue; if (attribute.overrideStringValue !== undefined) { switch (type.name) { case 'string': testValue = attribute.overrideStringValue; break; case 'array with string': testValue = [attribute.overrideStringValue]; break; default: break; } } let baseProps = { ...attribute.extraProps, }; if (attribute.type) { baseProps.type = attribute.type; } const props = { ...baseProps, [attribute.name]: testValue, }; let defaultValue; let canonicalDefaultValue; let result; let canonicalResult; let ssrResult; let canonicalSsrResult; let didWarn; let didError; let ssrDidWarn; let ssrDidError; _didWarn = false; try { let container = createContainer(); renderer.render(react.createElement(tagName, baseProps), container); defaultValue = read(container.lastChild); canonicalDefaultValue = getCanonicalizedValue(defaultValue); container = createContainer(); renderer.render(react.createElement(tagName, props), container); result = read(container.lastChild); canonicalResult = getCanonicalizedValue(result); didWarn = _didWarn; didError = false; } catch (error) { result = null; didWarn = _didWarn; didError = true; } _didWarn = false; let hasTagMismatch = false; let hasUnknownElement = false; try { let container; if (containerTagName === 'document') { const html = serverRenderer.renderToString( react.createElement(tagName, props) ); container = createContainer(); container.innerHTML = html; } else if (containerTagName === 'head') { const html = serverRenderer.renderToString( react.createElement(tagName, props) ); container = createContainer(); container.innerHTML = html; } else { const html = serverRenderer.renderToString( react.createElement( containerTagName, null, react.createElement(tagName, props) ) ); const outerContainer = document.createElement('div'); outerContainer.innerHTML = html; container = outerContainer.firstChild; } if ( !container.lastChild || container.lastChild.tagName.toLowerCase() !== tagName.toLowerCase() ) { hasTagMismatch = true; } if ( container.lastChild instanceof HTMLUnknownElement && !UNKNOWN_HTML_TAGS.has(container.lastChild.tagName.toLowerCase()) ) { hasUnknownElement = true; } ssrResult = read(container.lastChild); canonicalSsrResult = getCanonicalizedValue(ssrResult); ssrDidWarn = _didWarn; ssrDidError = false; } catch (error) { ssrResult = null; ssrDidWarn = _didWarn; ssrDidError = true; } console.error = originalConsoleError; if (hasTagMismatch) { throw new Error('Tag mismatch. Expected: ' + tagName); } if (hasUnknownElement) { throw new Error('Unexpected unknown element: ' + tagName); } let ssrHasSameBehavior; let ssrHasSameBehaviorExceptWarnings; if (didError && ssrDidError) { ssrHasSameBehavior = true; } else if (!didError && !ssrDidError) { if (canonicalResult === canonicalSsrResult) { ssrHasSameBehaviorExceptWarnings = true; ssrHasSameBehavior = didWarn === ssrDidWarn; } ssrHasSameBehavior = didWarn === ssrDidWarn && canonicalResult === canonicalSsrResult; } else { ssrHasSameBehavior = false; } return { tagName, containerTagName, testValue, defaultValue, result, canonicalResult, canonicalDefaultValue, didWarn, didError, ssrResult, canonicalSsrResult, ssrDidWarn, ssrDidError, ssrHasSameBehavior, ssrHasSameBehaviorExceptWarnings, }; } function prepareState(initGlobals) { function getRenderedAttributeValues(attribute, type) { const { ReactStable, ReactDOMStable, ReactDOMServerStable, ReactNext, ReactDOMNext, ReactDOMServerNext, } = initGlobals(attribute, type); const reactStableValue = getRenderedAttributeValue( ReactStable, ReactDOMStable, ReactDOMServerStable, attribute, type ); const reactNextValue = getRenderedAttributeValue( ReactNext, ReactDOMNext, ReactDOMServerNext, attribute, type ); let hasSameBehavior; if (reactStableValue.didError && reactNextValue.didError) { hasSameBehavior = true; } else if (!reactStableValue.didError && !reactNextValue.didError) { hasSameBehavior = reactStableValue.didWarn === reactNextValue.didWarn && reactStableValue.canonicalResult === reactNextValue.canonicalResult && reactStableValue.ssrHasSameBehavior === reactNextValue.ssrHasSameBehavior; } else { hasSameBehavior = false; } return { reactStable: reactStableValue, reactNext: reactNextValue, hasSameBehavior, }; } const table = new Map(); const rowPatternHashes = new Map(); // Disable error overlay while testing each attribute uninjectErrorOverlay(); for (let attribute of attributes) { const results = new Map(); let hasSameBehaviorForAll = true; let rowPatternHash = ''; for (let type of types) { const result = getRenderedAttributeValues(attribute, type); results.set(type.name, result); if (!result.hasSameBehavior) { hasSameBehaviorForAll = false; } rowPatternHash += [result.reactStable, result.reactNext] .map(res => [ res.canonicalResult, res.canonicalDefaultValue, res.didWarn, res.didError, ].join('||') ) .join('||'); } const row = { results, hasSameBehaviorForAll, rowPatternHash, // "Good enough" id that we can store in localStorage rowIdHash: `${attribute.name} ${attribute.tagName} ${attribute.overrideStringValue}`, }; const rowGroup = rowPatternHashes.get(rowPatternHash) || new Set(); rowGroup.add(row); rowPatternHashes.set(rowPatternHash, rowGroup); table.set(attribute, row); } // Renable error overlay injectErrorOverlay(); return { table, rowPatternHashes, }; } const successColor = 'white'; const warnColor = 'yellow'; const errorColor = 'red'; function RendererResult({ result, canonicalResult, defaultValue, canonicalDefaultValue, didWarn, didError, ssrHasSameBehavior, ssrHasSameBehaviorExceptWarnings, }) { let backgroundColor; if (didError) { backgroundColor = errorColor; } else if (didWarn) { backgroundColor = warnColor; } else if (canonicalResult !== canonicalDefaultValue) { backgroundColor = 'cyan'; } else { backgroundColor = successColor; } let style = { display: 'flex', alignItems: 'center', position: 'absolute', height: '100%', width: '100%', backgroundColor, }; if (!ssrHasSameBehavior) { const color = ssrHasSameBehaviorExceptWarnings ? 'gray' : 'magenta'; style.border = `3px dotted ${color}`; } return <div css={style}>{canonicalResult}</div>; } function ResultPopover(props) { return ( <pre css={{ padding: '1em', minWidth: '25em', }}> {JSON.stringify( { reactStable: props.reactStable, reactNext: props.reactNext, hasSameBehavior: props.hasSameBehavior, }, null, 2 )} </pre> ); } class Result extends React.Component { state = {showInfo: false}; onMouseEnter = () => { if (this.timeout) { clearTimeout(this.timeout); } this.timeout = setTimeout(() => { this.setState({showInfo: true}); }, 250); }; onMouseLeave = () => { if (this.timeout) { clearTimeout(this.timeout); } this.setState({showInfo: false}); }; componentWillUnmount() { if (this.timeout) { clearTimeout(this.interval); } } render() { const {reactStable, reactNext, hasSameBehavior} = this.props; const style = { position: 'absolute', width: '100%', height: '100%', }; let highlight = null; let popover = null; if (this.state.showInfo) { highlight = ( <div css={{ position: 'absolute', height: '100%', width: '100%', border: '2px solid blue', }} /> ); popover = ( <div css={{ backgroundColor: 'white', border: '1px solid black', position: 'absolute', top: '100%', zIndex: 999, }}> <ResultPopover {...this.props} /> </div> ); } if (!hasSameBehavior) { style.border = '4px solid purple'; } return ( <div css={style} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}> <div css={{position: 'absolute', width: '50%', height: '100%'}}> <RendererResult {...reactStable} /> </div> <div css={{ position: 'absolute', width: '50%', left: '50%', height: '100%', }}> <RendererResult {...reactNext} /> </div> {highlight} {popover} </div> ); } } function ColumnHeader({children}) { return ( <div css={{ position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: 'center', }}> {children} </div> ); } function RowHeader({children, checked, onChange}) { return ( <div css={{ position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: 'center', }}> <input type="checkbox" checked={checked} onChange={onChange} /> {children} </div> ); } function CellContent(props) { const { columnIndex, rowIndex, attributesInSortedOrder, completedHashes, toggleAttribute, table, } = props; const attribute = attributesInSortedOrder[rowIndex - 1]; const type = types[columnIndex - 1]; if (columnIndex === 0) { if (rowIndex === 0) { return null; } const row = table.get(attribute); const rowPatternHash = row.rowPatternHash; return ( <RowHeader checked={completedHashes.has(rowPatternHash)} onChange={() => toggleAttribute(rowPatternHash)}> {row.hasSameBehaviorForAll ? ( attribute.name ) : ( <b css={{color: 'purple'}}>{attribute.name}</b> )} </RowHeader> ); } if (rowIndex === 0) { return <ColumnHeader>{type.name}</ColumnHeader>; } const row = table.get(attribute); const result = row.results.get(type.name); return <Result {...result} />; } function saveToLocalStorage(completedHashes) { const str = JSON.stringify([...completedHashes]); localStorage.setItem('completedHashes', str); } function restoreFromLocalStorage() { const str = localStorage.getItem('completedHashes'); if (str) { const completedHashes = new Set(JSON.parse(str)); return completedHashes; } return new Set(); } const useFastMode = /[?&]fast\b/.test(window.location.href); class App extends React.Component { state = { sortOrder: ALPHABETICAL, filter: ALL, completedHashes: restoreFromLocalStorage(), table: null, rowPatternHashes: null, }; renderCell = ({key, ...props}) => { return ( <div key={key} style={props.style}> <CellContent toggleAttribute={this.toggleAttribute} completedHashes={this.state.completedHashes} table={this.state.table} attributesInSortedOrder={this.attributes} {...props} /> </div> ); }; onUpdateSort = e => { this.setState({sortOrder: e.target.value}); }; onUpdateFilter = e => { this.setState({filter: e.target.value}); }; toggleAttribute = rowPatternHash => { const completedHashes = new Set(this.state.completedHashes); if (completedHashes.has(rowPatternHash)) { completedHashes.delete(rowPatternHash); } else { completedHashes.add(rowPatternHash); } this.setState({completedHashes}, () => saveToLocalStorage(completedHashes)); }; async componentDidMount() { const sources = { ReactStable: 'https://unpkg.com/react@latest/umd/react.development.js', ReactDOMStable: 'https://unpkg.com/react-dom@latest/umd/react-dom.development.js', ReactDOMServerStable: 'https://unpkg.com/react-dom@latest/umd/react-dom-server-legacy.browser.development.js', ReactNext: '/react.development.js', ReactDOMNext: '/react-dom.development.js', ReactDOMServerNext: '/react-dom-server-legacy.browser.development.js', }; const codePromises = Object.values(sources).map(src => fetch(src).then(res => res.text()) ); const codesByIndex = await Promise.all(codePromises); const pool = []; function initGlobals(attribute, type) { if (useFastMode) { // Note: this is not giving correct results for warnings. // But it's much faster. if (pool[0]) { return pool[0].globals; } } else { document.title = `${attribute.name} (${type.name})`; } // Creating globals for every single test is too slow. // However caching them between runs won't work for the same attribute names // because warnings will be deduplicated. As a result, we only share globals // between different attribute names. for (let i = 0; i < pool.length; i++) { if (!pool[i].testedAttributes.has(attribute.name)) { pool[i].testedAttributes.add(attribute.name); return pool[i].globals; } } let globals = {}; Object.keys(sources).forEach((name, i) => { eval.call(window, codesByIndex[i]); // eslint-disable-line globals[name] = window[name.replace(/Stable|Next/g, '')]; }); // Cache for future use (for different attributes). pool.push({ globals, testedAttributes: new Set([attribute.name]), }); return globals; } const {table, rowPatternHashes} = prepareState(initGlobals); document.title = 'Ready'; this.setState({ table, rowPatternHashes, }); } componentWillUpdate(nextProps, nextState) { if ( nextState.sortOrder !== this.state.sortOrder || nextState.filter !== this.state.filter || nextState.completedHashes !== this.state.completedHashes || nextState.table !== this.state.table ) { this.attributes = this.getAttributes( nextState.table, nextState.rowPatternHashes, nextState.sortOrder, nextState.filter, nextState.completedHashes ); if (this.grid) { this.grid.forceUpdateGrids(); } } } getAttributes(table, rowPatternHashes, sortOrder, filter, completedHashes) { // Filter let filteredAttributes; switch (filter) { case ALL: filteredAttributes = attributes.filter(() => true); break; case COMPLETE: filteredAttributes = attributes.filter(attribute => { const row = table.get(attribute); return completedHashes.has(row.rowPatternHash); }); break; case INCOMPLETE: filteredAttributes = attributes.filter(attribute => { const row = table.get(attribute); return !completedHashes.has(row.rowPatternHash); }); break; default: throw new Error('Switch statement should be exhaustive'); } // Sort switch (sortOrder) { case ALPHABETICAL: return filteredAttributes.sort((attr1, attr2) => attr1.name.toLowerCase() < attr2.name.toLowerCase() ? -1 : 1 ); case REV_ALPHABETICAL: return filteredAttributes.sort((attr1, attr2) => attr1.name.toLowerCase() < attr2.name.toLowerCase() ? 1 : -1 ); case GROUPED_BY_ROW_PATTERN: { return filteredAttributes.sort((attr1, attr2) => { const row1 = table.get(attr1); const row2 = table.get(attr2); const patternGroup1 = rowPatternHashes.get(row1.rowPatternHash); const patternGroupSize1 = (patternGroup1 && patternGroup1.size) || 0; const patternGroup2 = rowPatternHashes.get(row2.rowPatternHash); const patternGroupSize2 = (patternGroup2 && patternGroup2.size) || 0; return patternGroupSize2 - patternGroupSize1; }); } default: throw new Error('Switch statement should be exhaustive'); } } handleSaveClick = e => { e.preventDefault(); if (useFastMode) { alert( 'Fast mode is not accurate. Please remove ?fast from the query string, and reload.' ); return; } let log = ''; for (let attribute of attributes) { log += `## \`${attribute.name}\` (on \`<${ attribute.tagName || 'div' }>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`; log += '| Test Case | Flags | Result |\n'; log += '| --- | --- | --- |\n'; const attributeResults = this.state.table.get(attribute).results; for (let type of types) { const { didError, didWarn, canonicalResult, canonicalDefaultValue, ssrDidError, ssrHasSameBehavior, ssrHasSameBehaviorExceptWarnings, } = attributeResults.get(type.name).reactNext; let descriptions = []; if (canonicalResult === canonicalDefaultValue) { descriptions.push('initial'); } else { descriptions.push('changed'); } if (didError) { descriptions.push('error'); } if (didWarn) { descriptions.push('warning'); } if (ssrDidError) { descriptions.push('ssr error'); } if (!ssrHasSameBehavior) { if (ssrHasSameBehaviorExceptWarnings) { descriptions.push('ssr warning'); } else { descriptions.push('ssr mismatch'); } } log += `| \`${attribute.name}=(${type.name})\`` + `| (${descriptions.join(', ')})` + `| \`${canonicalResult || ''}\` |\n`; } log += '\n'; } const blob = new Blob([log], {type: 'text/plain;charset=utf-8'}); FileSaver.saveAs(blob, 'AttributeTableSnapshot.md'); }; render() { if (!this.state.table) { return ( <div> <h1>Loading...</h1> {!useFastMode && ( <h3>The progress is reported in the window title.</h3> )} </div> ); } return ( <div> <div> <select value={this.state.sortOrder} onChange={this.onUpdateSort}> <option value={ALPHABETICAL}>alphabetical</option> <option value={REV_ALPHABETICAL}>reverse alphabetical</option> <option value={GROUPED_BY_ROW_PATTERN}> grouped by row pattern :) </option> </select> <select value={this.state.filter} onChange={this.onUpdateFilter}> <option value={ALL}>all</option> <option value={INCOMPLETE}>incomplete</option> <option value={COMPLETE}>complete</option> </select> <button style={{marginLeft: '10px'}} onClick={this.handleSaveClick}> Save latest results to a file{' '} <span role="img" aria-label="Save"> 💾 </span> </button> </div> <AutoSizer disableHeight={true}> {({width}) => ( <MultiGrid ref={input => { this.grid = input; }} cellRenderer={this.renderCell} columnWidth={200} columnCount={1 + types.length} fixedColumnCount={1} enableFixedColumnScroll={true} enableFixedRowScroll={true} height={1200} rowHeight={40} rowCount={this.attributes.length + 1} fixedRowCount={1} width={width} /> )} </AutoSizer> </div> ); } } export default App;
24.243164
96
0.577066
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 */ export * from './src/test-utils/ReactTestUtils';
22.090909
66
0.695652
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 */ 'use strict'; let React; let ReactNoop; let waitForAll; let waitForThrow; describe('ReactIncrementalErrorReplay', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitForThrow = InternalTestUtils.waitForThrow; }); it('should fail gracefully on error in the host environment', async () => { ReactNoop.render(<errorInBeginPhase />); await waitForThrow('Error in host config.'); }); it("should ignore error if it doesn't throw on retry", async () => { let didInit = false; function badLazyInit() { const needsInit = !didInit; didInit = true; if (needsInit) { throw new Error('Hi'); } } class App extends React.Component { render() { badLazyInit(); return <div />; } } ReactNoop.render(<App />); await waitForAll([]); }); });
22.181818
77
0.634223
owtf
import {createStore} from 'redux'; function reducer(state = 0, action) { switch (action.type) { case 'increment': return state + 1; default: return state; } } // Because this file is declared above both Modern and Legacy folders, // we can import this from either folder without duplicating the object. export const store = createStore(reducer);
23.866667
72
0.698925
owtf
const React = window.React; export default function Home() { return ( <main className="container"> <h1>DOM Test Fixtures</h1> <p> Use this site to test browser quirks and other behavior that can not be captured through unit tests. </p> <section> <h2>Tested Browsers</h2> <table> <thead> <tr> <th>Browser</th> <th>Versions</th> </tr> </thead> <tbody> <tr> <td>Chrome - Desktop</td> <td> 49<sup>*</sup>, Latest </td> </tr> <tr> <td>Chrome - Android</td> <td>Latest</td> </tr> <tr> <td>Firefox Desktop</td> <td> <a href="https://www.mozilla.org/en-US/firefox/organizations/"> ESR<sup>†</sup> </a> , Latest </td> </tr> <tr> <td>Internet Explorer</td> <td>9, 10, 11</td> </tr> <tr> <td>Microsoft Edge</td> <td>14, Latest</td> </tr> <tr> <td>Safari - Desktop</td> <td>7, Latest</td> </tr> <tr> <td>Safari - iOS</td> <td>7, Latest</td> </tr> </tbody> </table> <footer> <small>* Chrome 49 is the last release for Windows XP.</small> <br /> <small> † Firefox Extended Support Release (ESR) is used by many institutions. </small> </footer> </section> <section> <h2>How do I test browsers I don't have access to?</h2> <p> Getting test coverage across all of these browsers can be difficult, particularly for older versions of evergreen browsers. Fortunately there are a handful of tools that make browser testing easy. </p> <section> <h3>Paid services</h3> <ul> <li> <a href="https://browserstack.com">BrowserStack</a> </li> <li> <a href="https://saucelabs.com">Sauce Labs</a> </li> <li> <a href="https://crossbrowsertesting.com/">CrossBrowserTesting</a> </li> </ul> <p> These services provide access to all browsers we test, however they cost money. There is no obligation to pay for them. Maintainers have access to a BrowserStack subscription; feel free to contact a maintainer or mention browsers where extra testing is required. </p> </section> <section> <h3>Browser downloads</h3> <p>A handful of browsers are available for download directly:</p> <ul> <li> <a href="https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/"> Internet Explorer (9-11) and MS Edge virtual machines </a> </li> <li> <a href="https://www.chromium.org/getting-involved/download-chromium#TOC-Downloading-old-builds-of-Chrome-Chromium"> Chromium snapshots (for older versions of Chrome) </a> </li> <li> <a href="https://www.mozilla.org/en-US/firefox/organizations/"> Firefox Extended Support Release (ESR) </a> </li> </ul> </section> </section> </main> ); }
30.252101
130
0.458042
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 {normalizeCodeLocInfo} from './utils'; let React; let ReactDOMClient; let act; let fakeConsole; let legacyRender; let mockError; let mockInfo; let mockGroup; let mockGroupCollapsed; let mockLog; let mockWarn; let patchConsole; let unpatchConsole; let rendererID; describe('console', () => { beforeEach(() => { const Console = require('react-devtools-shared/src/backend/console'); patchConsole = Console.patch; unpatchConsole = Console.unpatch; // Patch a fake console so we can verify with tests below. // Patching the real console is too complicated, // because Jest itself has hooks into it as does our test env setup. mockError = jest.fn(); mockInfo = jest.fn(); mockGroup = jest.fn(); mockGroupCollapsed = jest.fn(); mockLog = jest.fn(); mockWarn = jest.fn(); fakeConsole = { error: mockError, info: mockInfo, log: mockLog, warn: mockWarn, group: mockGroup, groupCollapsed: mockGroupCollapsed, }; Console.dangerous_setTargetConsoleForTesting(fakeConsole); global.__REACT_DEVTOOLS_GLOBAL_HOOK__.dangerous_setTargetConsoleForTesting( fakeConsole, ); const inject = global.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject; global.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject = internals => { rendererID = inject(internals); Console.registerRenderer(internals); return rendererID; }; React = require('react'); ReactDOMClient = require('react-dom/client'); const utils = require('./utils'); act = utils.act; legacyRender = utils.legacyRender; }); // @reactVersion >=18.0 it('should not patch console methods that are not explicitly overridden', () => { expect(fakeConsole.error).not.toBe(mockError); expect(fakeConsole.info).toBe(mockInfo); expect(fakeConsole.log).toBe(mockLog); expect(fakeConsole.warn).not.toBe(mockWarn); expect(fakeConsole.group).toBe(mockGroup); expect(fakeConsole.groupCollapsed).toBe(mockGroupCollapsed); }); // @reactVersion >=18.0 it('should patch the console when appendComponentStack is enabled', () => { unpatchConsole(); expect(fakeConsole.error).toBe(mockError); expect(fakeConsole.warn).toBe(mockWarn); patchConsole({ appendComponentStack: true, breakOnConsoleErrors: false, showInlineWarningsAndErrors: false, }); expect(fakeConsole.error).not.toBe(mockError); expect(fakeConsole.warn).not.toBe(mockWarn); }); // @reactVersion >=18.0 it('should patch the console when breakOnConsoleErrors is enabled', () => { unpatchConsole(); expect(fakeConsole.error).toBe(mockError); expect(fakeConsole.warn).toBe(mockWarn); patchConsole({ appendComponentStack: false, breakOnConsoleErrors: true, showInlineWarningsAndErrors: false, }); expect(fakeConsole.error).not.toBe(mockError); expect(fakeConsole.warn).not.toBe(mockWarn); }); // @reactVersion >=18.0 it('should patch the console when showInlineWarningsAndErrors is enabled', () => { unpatchConsole(); expect(fakeConsole.error).toBe(mockError); expect(fakeConsole.warn).toBe(mockWarn); patchConsole({ appendComponentStack: false, breakOnConsoleErrors: false, showInlineWarningsAndErrors: true, }); expect(fakeConsole.error).not.toBe(mockError); expect(fakeConsole.warn).not.toBe(mockWarn); }); // @reactVersion >=18.0 it('should only patch the console once', () => { const {error, warn} = fakeConsole; patchConsole({ appendComponentStack: true, breakOnConsoleErrors: false, showInlineWarningsAndErrors: false, }); expect(fakeConsole.error).toBe(error); expect(fakeConsole.warn).toBe(warn); }); // @reactVersion >=18.0 it('should un-patch when requested', () => { expect(fakeConsole.error).not.toBe(mockError); expect(fakeConsole.warn).not.toBe(mockWarn); unpatchConsole(); expect(fakeConsole.error).toBe(mockError); expect(fakeConsole.warn).toBe(mockWarn); }); // @reactVersion >=18.0 it('should pass through logs when there is no current fiber', () => { expect(mockLog).toHaveBeenCalledTimes(0); expect(mockWarn).toHaveBeenCalledTimes(0); expect(mockError).toHaveBeenCalledTimes(0); fakeConsole.log('log'); fakeConsole.warn('warn'); fakeConsole.error('error'); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); }); // @reactVersion >=18.0 it('should not append multiple stacks', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true; const Child = ({children}) => { fakeConsole.warn('warn\n in Child (at fake.js:123)'); fakeConsole.error('error', '\n in Child (at fake.js:123)'); return null; }; act(() => legacyRender(<Child />, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe( 'warn\n in Child (at fake.js:123)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(mockError.mock.calls[0][1]).toBe('\n in Child (at fake.js:123)'); }); // @reactVersion >=18.0 it('should append component stacks to errors and warnings logged during render', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true; const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); const Child = ({children}) => { fakeConsole.error('error'); fakeConsole.log('log'); fakeConsole.warn('warn'); return null; }; act(() => legacyRender(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); // @reactVersion >=18.0 it('should append component stacks to errors and warnings logged from effects', () => { const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); const Child = ({children}) => { React.useLayoutEffect(() => { fakeConsole.error('active error'); fakeConsole.log('active log'); fakeConsole.warn('active warn'); }); React.useEffect(() => { fakeConsole.error('passive error'); fakeConsole.log('passive log'); fakeConsole.warn('passive warn'); }); return null; }; act(() => legacyRender(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(2); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('active log'); expect(mockLog.mock.calls[1]).toHaveLength(1); expect(mockLog.mock.calls[1][0]).toBe('passive log'); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('active warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockWarn.mock.calls[1]).toHaveLength(2); expect(mockWarn.mock.calls[1][0]).toBe('passive warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('active error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError.mock.calls[1]).toHaveLength(2); expect(mockError.mock.calls[1][0]).toBe('passive error'); expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); // @reactVersion >=18.0 it('should append component stacks to errors and warnings logged from commit hooks', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true; const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); class Child extends React.Component<any> { componentDidMount() { fakeConsole.error('didMount error'); fakeConsole.log('didMount log'); fakeConsole.warn('didMount warn'); } componentDidUpdate() { fakeConsole.error('didUpdate error'); fakeConsole.log('didUpdate log'); fakeConsole.warn('didUpdate warn'); } render() { return null; } } const container = document.createElement('div'); act(() => legacyRender(<Parent />, container)); act(() => legacyRender(<Parent />, container)); expect(mockLog).toHaveBeenCalledTimes(2); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('didMount log'); expect(mockLog.mock.calls[1]).toHaveLength(1); expect(mockLog.mock.calls[1][0]).toBe('didUpdate log'); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('didMount warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockWarn.mock.calls[1]).toHaveLength(2); expect(mockWarn.mock.calls[1][0]).toBe('didUpdate warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('didMount error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError.mock.calls[1]).toHaveLength(2); expect(mockError.mock.calls[1][0]).toBe('didUpdate error'); expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); // @reactVersion >=18.0 it('should append component stacks to errors and warnings logged from gDSFP', () => { const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); class Child extends React.Component<any, any> { state = {}; static getDerivedStateFromProps() { fakeConsole.error('error'); fakeConsole.log('log'); fakeConsole.warn('warn'); return null; } render() { return null; } } act(() => legacyRender(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); // @reactVersion >=18.0 it('should append stacks after being uninstalled and reinstalled', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = false; const Child = ({children}) => { fakeConsole.warn('warn'); fakeConsole.error('error'); return null; }; act(() => legacyRender(<Child />, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); patchConsole({ appendComponentStack: true, breakOnConsoleErrors: false, showInlineWarningsAndErrors: false, }); act(() => legacyRender(<Child />, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[1]).toHaveLength(2); expect(mockWarn.mock.calls[1][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual( '\n in Child (at **)', ); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[1]).toHaveLength(2); expect(mockError.mock.calls[1][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe( '\n in Child (at **)', ); }); // @reactVersion >=18.0 it('should be resilient to prepareStackTrace', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true; Error.prepareStackTrace = function (error, callsites) { const stack = ['An error occurred:', error.message]; for (let i = 0; i < callsites.length; i++) { const callsite = callsites[i]; stack.push( '\t' + callsite.getFunctionName(), '\t\tat ' + callsite.getFileName(), '\t\ton line ' + callsite.getLineNumber(), ); } return stack.join('\n'); }; const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); const Child = ({children}) => { fakeConsole.error('error'); fakeConsole.log('log'); fakeConsole.warn('warn'); return null; }; act(() => legacyRender(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); // @reactVersion >=18.0 it('should correctly log Symbols', () => { const Component = ({children}) => { fakeConsole.warn('Symbol:', Symbol('')); return null; }; act(() => legacyRender(<Component />, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0][0]).toBe('Symbol:'); }); it('should double log if hideConsoleLogsInStrictMode is disabled in Strict mode', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = false; global.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = false; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); function App() { fakeConsole.log('log'); fakeConsole.warn('warn'); fakeConsole.error('error'); fakeConsole.info('info'); fakeConsole.group('group'); fakeConsole.groupCollapsed('groupCollapsed'); return <div />; } act(() => root.render( <React.StrictMode> <App /> </React.StrictMode>, ), ); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockLog.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`, 'log', ]); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockWarn.mock.calls[1]).toHaveLength(3); expect(mockWarn.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_WARNING_COLOR}`, 'warn', ]); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); expect(mockError.mock.calls[1]).toHaveLength(3); expect(mockError.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_ERROR_COLOR}`, 'error', ]); expect(mockInfo).toHaveBeenCalledTimes(2); expect(mockInfo.mock.calls[0]).toHaveLength(1); expect(mockInfo.mock.calls[0][0]).toBe('info'); expect(mockInfo.mock.calls[1]).toHaveLength(3); expect(mockInfo.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`, 'info', ]); expect(mockGroup).toHaveBeenCalledTimes(2); expect(mockGroup.mock.calls[0]).toHaveLength(1); expect(mockGroup.mock.calls[0][0]).toBe('group'); expect(mockGroup.mock.calls[1]).toHaveLength(3); expect(mockGroup.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`, 'group', ]); expect(mockGroupCollapsed).toHaveBeenCalledTimes(2); expect(mockGroupCollapsed.mock.calls[0]).toHaveLength(1); expect(mockGroupCollapsed.mock.calls[0][0]).toBe('groupCollapsed'); expect(mockGroupCollapsed.mock.calls[1]).toHaveLength(3); expect(mockGroupCollapsed.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`, 'groupCollapsed', ]); }); it('should not double log if hideConsoleLogsInStrictMode is enabled in Strict mode', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = false; global.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = true; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); function App() { console.log( 'CALL', global.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__, ); fakeConsole.log('log'); fakeConsole.warn('warn'); fakeConsole.error('error'); fakeConsole.info('info'); fakeConsole.group('group'); fakeConsole.groupCollapsed('groupCollapsed'); return <div />; } act(() => root.render( <React.StrictMode> <App /> </React.StrictMode>, ), ); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); expect(mockInfo).toHaveBeenCalledTimes(1); expect(mockInfo.mock.calls[0]).toHaveLength(1); expect(mockInfo.mock.calls[0][0]).toBe('info'); expect(mockGroup).toHaveBeenCalledTimes(1); expect(mockGroup.mock.calls[0]).toHaveLength(1); expect(mockGroup.mock.calls[0][0]).toBe('group'); expect(mockGroupCollapsed).toHaveBeenCalledTimes(1); expect(mockGroupCollapsed.mock.calls[0]).toHaveLength(1); expect(mockGroupCollapsed.mock.calls[0][0]).toBe('groupCollapsed'); }); it('should double log in Strict mode initial render for extension', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = false; global.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = false; // This simulates a render that happens before React DevTools have finished // their handshake to attach the React DOM renderer functions to DevTools // In this case, we should still be able to mock the console in Strict mode global.__REACT_DEVTOOLS_GLOBAL_HOOK__.rendererInterfaces.set( rendererID, null, ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); function App() { fakeConsole.log('log'); fakeConsole.warn('warn'); fakeConsole.error('error'); return <div />; } act(() => root.render( <React.StrictMode> <App /> </React.StrictMode>, ), ); expect(mockLog).toHaveBeenCalledTimes(2); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockLog.mock.calls[1]).toHaveLength(3); expect(mockLog.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_LOG_COLOR}`, 'log', ]); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockWarn.mock.calls[1]).toHaveLength(3); expect(mockWarn.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_WARNING_COLOR}`, 'warn', ]); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); expect(mockError.mock.calls[1]).toHaveLength(3); expect(mockError.mock.calls[1]).toEqual([ '%c%s', `color: ${process.env.DARK_MODE_DIMMED_ERROR_COLOR}`, 'error', ]); }); it('should not double log in Strict mode initial render for extension', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = false; global.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = true; // This simulates a render that happens before React DevTools have finished // their handshake to attach the React DOM renderer functions to DevTools // In this case, we should still be able to mock the console in Strict mode global.__REACT_DEVTOOLS_GLOBAL_HOOK__.rendererInterfaces.set( rendererID, null, ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); function App() { fakeConsole.log('log'); fakeConsole.warn('warn'); fakeConsole.error('error'); return <div />; } act(() => root.render( <React.StrictMode> <App /> </React.StrictMode>, ), ); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); }); it('should properly dim component stacks during strict mode double log', () => { global.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = true; global.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = false; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); const Child = ({children}) => { fakeConsole.error('error'); fakeConsole.warn('warn'); return null; }; act(() => root.render( <React.StrictMode> <Parent /> </React.StrictMode>, ), ); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockWarn.mock.calls[1]).toHaveLength(4); expect(mockWarn.mock.calls[1][0]).toEqual('%c%s %s'); expect(mockWarn.mock.calls[1][1]).toMatch('color: rgba('); expect(mockWarn.mock.calls[1][2]).toEqual('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][3]).trim()).toEqual( 'in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[0]).toHaveLength(2); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError.mock.calls[1]).toHaveLength(4); expect(mockError.mock.calls[1][0]).toEqual('%c%s %s'); expect(mockError.mock.calls[1][1]).toMatch('color: rgba('); expect(mockError.mock.calls[1][2]).toEqual('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[1][3]).trim()).toEqual( 'in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); }); describe('console error', () => { beforeEach(() => { jest.resetModules(); const Console = require('react-devtools-shared/src/backend/console'); patchConsole = Console.patch; unpatchConsole = Console.unpatch; // Patch a fake console so we can verify with tests below. // Patching the real console is too complicated, // because Jest itself has hooks into it as does our test env setup. mockError = jest.fn(); mockInfo = jest.fn(); mockGroup = jest.fn(); mockGroupCollapsed = jest.fn(); mockLog = jest.fn(); mockWarn = jest.fn(); fakeConsole = { error: mockError, info: mockInfo, log: mockLog, warn: mockWarn, group: mockGroup, groupCollapsed: mockGroupCollapsed, }; Console.dangerous_setTargetConsoleForTesting(fakeConsole); const inject = global.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject; global.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject = internals => { inject(internals); Console.registerRenderer(internals, () => { throw Error('foo'); }); }; React = require('react'); ReactDOMClient = require('react-dom/client'); const utils = require('./utils'); act = utils.act; legacyRender = utils.legacyRender; }); // @reactVersion >=18.0 it('error in console log throws without interfering with logging', () => { const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); function App() { fakeConsole.log('log'); fakeConsole.warn('warn'); fakeConsole.error('error'); return <div />; } patchConsole({ appendComponentStack: true, breakOnConsoleErrors: false, showInlineWarningsAndErrors: true, hideConsoleLogsInStrictMode: false, }); expect(() => { act(() => { root.render(<App />); }); }).toThrowError('foo'); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); }); });
32.60023
94
0.636058
null
/** * @license React * * 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. */ /* eslint-disable max-len */ 'use strict'; (function (global, factory) { // eslint-disable-next-line ft-flow/no-unused-expressions typeof exports === 'object' && typeof module !== 'undefined' ? (module.exports = factory(require('react'))) : typeof define === 'function' && define.amd // eslint-disable-line no-undef ? define(['react'], factory) // eslint-disable-line no-undef : (global.Scheduler = factory(global)); })(this, function (global) { function unstable_now() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_now.apply( this, arguments ); } function unstable_scheduleCallback() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_scheduleCallback.apply( this, arguments ); } function unstable_cancelCallback() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_cancelCallback.apply( this, arguments ); } function unstable_shouldYield() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_shouldYield.apply( this, arguments ); } function unstable_requestPaint() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_requestPaint.apply( this, arguments ); } function unstable_runWithPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_runWithPriority.apply( this, arguments ); } function unstable_next() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_next.apply( this, arguments ); } function unstable_wrapCallback() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_wrapCallback.apply( this, arguments ); } function unstable_getCurrentPriorityLevel() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getCurrentPriorityLevel.apply( this, arguments ); } function unstable_getFirstCallbackNode() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getFirstCallbackNode.apply( this, arguments ); } function unstable_pauseExecution() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_pauseExecution.apply( this, arguments ); } function unstable_continueExecution() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_continueExecution.apply( this, arguments ); } function unstable_forceFrameRate() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_forceFrameRate.apply( this, arguments ); } return Object.freeze({ unstable_now: unstable_now, unstable_scheduleCallback: unstable_scheduleCallback, unstable_cancelCallback: unstable_cancelCallback, unstable_shouldYield: unstable_shouldYield, unstable_requestPaint: unstable_requestPaint, unstable_runWithPriority: unstable_runWithPriority, unstable_next: unstable_next, unstable_wrapCallback: unstable_wrapCallback, unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel, unstable_continueExecution: unstable_continueExecution, unstable_pauseExecution: unstable_pauseExecution, unstable_getFirstCallbackNode: unstable_getFirstCallbackNode, unstable_forceFrameRate: unstable_forceFrameRate, get unstable_IdlePriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_IdlePriority; }, get unstable_ImmediatePriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_ImmediatePriority; }, get unstable_LowPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_LowPriority; }, get unstable_NormalPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_NormalPriority; }, get unstable_UserBlockingPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_UserBlockingPriority; }, get unstable_Profiling() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_Profiling; }, }); });
31.078431
124
0.701651
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 * from '../ReactServerStreamConfigEdge';
22
66
0.702381
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 */ 'use strict'; let ReactCache; let createResource; let React; let ReactFeatureFlags; let ReactTestRenderer; let Scheduler; let Suspense; let TextResource; let textResourceShouldFail; let waitForAll; let assertLog; let waitForThrow; let act; describe('ReactCache', () => { beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; React = require('react'); Suspense = React.Suspense; ReactCache = require('react-cache'); createResource = ReactCache.unstable_createResource; ReactTestRenderer = require('react-test-renderer'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; waitForThrow = InternalTestUtils.waitForThrow; act = InternalTestUtils.act; TextResource = createResource( ([text, ms = 0]) => { let listeners = null; let status = 'pending'; let value = null; return { then(resolve, reject) { switch (status) { case 'pending': { if (listeners === null) { listeners = [{resolve, reject}]; setTimeout(() => { if (textResourceShouldFail) { Scheduler.log(`Promise rejected [${text}]`); status = 'rejected'; value = new Error('Failed to load: ' + text); listeners.forEach(listener => listener.reject(value)); } else { Scheduler.log(`Promise resolved [${text}]`); status = 'resolved'; value = text; listeners.forEach(listener => listener.resolve(value)); } }, ms); } else { listeners.push({resolve, reject}); } break; } case 'resolved': { resolve(value); break; } case 'rejected': { reject(value); break; } } }, }; }, ([text, ms]) => text, ); textResourceShouldFail = false; }); function Text(props) { Scheduler.log(props.text); return props.text; } function AsyncText(props) { const text = props.text; try { TextResource.read([props.text, props.ms]); Scheduler.log(text); return text; } catch (promise) { if (typeof promise.then === 'function') { Scheduler.log(`Suspend! [${text}]`); } else { Scheduler.log(`Error! [${text}]`); } throw promise; } } it('throws a promise if the requested value is not in the cache', async () => { function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <AsyncText ms={100} text="Hi" /> </Suspense> ); } ReactTestRenderer.create(<App />, { isConcurrent: true, }); await waitForAll(['Suspend! [Hi]', 'Loading...']); jest.advanceTimersByTime(100); assertLog(['Promise resolved [Hi]']); await waitForAll(['Hi']); }); it('throws an error on the subsequent read if the promise is rejected', async () => { function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <AsyncText ms={100} text="Hi" /> </Suspense> ); } const root = ReactTestRenderer.create(<App />, { isConcurrent: true, }); await waitForAll(['Suspend! [Hi]', 'Loading...']); textResourceShouldFail = true; let error; try { await act(() => jest.advanceTimersByTime(100)); } catch (e) { error = e; } expect(error.message).toMatch('Failed to load: Hi'); assertLog(['Promise rejected [Hi]', 'Error! [Hi]', 'Error! [Hi]']); // Should throw again on a subsequent read root.update(<App />); await waitForThrow('Failed to load: Hi'); assertLog(['Error! [Hi]', 'Error! [Hi]']); }); it('warns if non-primitive key is passed to a resource without a hash function', async () => { const BadTextResource = createResource(([text, ms = 0]) => { return new Promise((resolve, reject) => setTimeout(() => { resolve(text); }, ms), ); }); function App() { Scheduler.log('App'); return BadTextResource.read(['Hi', 100]); } ReactTestRenderer.create( <Suspense fallback={<Text text="Loading..." />}> <App /> </Suspense>, { isConcurrent: true, }, ); if (__DEV__) { await expect(async () => { await waitForAll(['App', 'Loading...']); }).toErrorDev([ 'Invalid key type. Expected a string, number, symbol, or ' + 'boolean, but instead received: Hi,100\n\n' + 'To use non-primitive values as keys, you must pass a hash ' + 'function as the second argument to createResource().', ]); } else { await waitForAll(['App', 'Loading...']); } }); it('evicts least recently used values', async () => { ReactCache.unstable_setGlobalCacheLimit(3); // Render 1, 2, and 3 const root = ReactTestRenderer.create( <Suspense fallback={<Text text="Loading..." />}> <AsyncText ms={100} text={1} /> <AsyncText ms={100} text={2} /> <AsyncText ms={100} text={3} /> </Suspense>, { isConcurrent: true, }, ); await waitForAll(['Suspend! [1]', 'Loading...']); jest.advanceTimersByTime(100); assertLog(['Promise resolved [1]']); await waitForAll([1, 'Suspend! [2]']); jest.advanceTimersByTime(100); assertLog(['Promise resolved [2]']); await waitForAll([1, 2, 'Suspend! [3]']); await act(() => jest.advanceTimersByTime(100)); assertLog(['Promise resolved [3]', 1, 2, 3]); expect(root).toMatchRenderedOutput('123'); // Render 1, 4, 5 root.update( <Suspense fallback={<Text text="Loading..." />}> <AsyncText ms={100} text={1} /> <AsyncText ms={100} text={4} /> <AsyncText ms={100} text={5} /> </Suspense>, ); await waitForAll([1, 'Suspend! [4]', 'Loading...']); await act(() => jest.advanceTimersByTime(100)); assertLog([ 'Promise resolved [4]', 1, 4, 'Suspend! [5]', 'Promise resolved [5]', 1, 4, 5, ]); expect(root).toMatchRenderedOutput('145'); // We've now rendered values 1, 2, 3, 4, 5, over our limit of 3. The least // recently used values are 2 and 3. They should have been evicted. root.update( <Suspense fallback={<Text text="Loading..." />}> <AsyncText ms={100} text={1} /> <AsyncText ms={100} text={2} /> <AsyncText ms={100} text={3} /> </Suspense>, ); await waitForAll([ // 1 is still cached 1, // 2 and 3 suspend because they were evicted from the cache 'Suspend! [2]', 'Loading...', ]); await act(() => jest.advanceTimersByTime(100)); assertLog([ 'Promise resolved [2]', 1, 2, 'Suspend! [3]', 'Promise resolved [3]', 1, 2, 3, ]); expect(root).toMatchRenderedOutput('123'); }); it('preloads during the render phase', async () => { function App() { TextResource.preload(['B', 1000]); TextResource.read(['A', 1000]); TextResource.read(['B', 1000]); return <Text text="Result" />; } const root = ReactTestRenderer.create( <Suspense fallback={<Text text="Loading..." />}> <App /> </Suspense>, { isConcurrent: true, }, ); await waitForAll(['Loading...']); await act(() => jest.advanceTimersByTime(1000)); assertLog(['Promise resolved [B]', 'Promise resolved [A]', 'Result']); expect(root).toMatchRenderedOutput('Result'); }); it('if a thenable resolves multiple times, does not update the first cached value', async () => { let resolveThenable; const BadTextResource = createResource( ([text, ms = 0]) => { let listeners = null; const value = null; return { then(resolve, reject) { if (value !== null) { resolve(value); } else { if (listeners === null) { listeners = [resolve]; resolveThenable = v => { listeners.forEach(listener => listener(v)); }; } else { listeners.push(resolve); } } }, }; }, ([text, ms]) => text, ); function BadAsyncText(props) { const text = props.text; try { const actualText = BadTextResource.read([props.text, props.ms]); Scheduler.log(actualText); return actualText; } catch (promise) { if (typeof promise.then === 'function') { Scheduler.log(`Suspend! [${text}]`); } else { Scheduler.log(`Error! [${text}]`); } throw promise; } } const root = ReactTestRenderer.create( <Suspense fallback={<Text text="Loading..." />}> <BadAsyncText text="Hi" /> </Suspense>, { isConcurrent: true, }, ); await waitForAll(['Suspend! [Hi]', 'Loading...']); resolveThenable('Hi'); // This thenable improperly resolves twice. We should not update the // cached value. resolveThenable('Hi muahahaha I am different'); root.update( <Suspense fallback={<Text text="Loading..." />}> <BadAsyncText text="Hi" /> </Suspense>, { isConcurrent: true, }, ); assertLog([]); await waitForAll(['Hi']); expect(root).toMatchRenderedOutput('Hi'); }); it('throws if read is called outside render', () => { expect(() => TextResource.read(['A', 1000])).toThrow( "read and preload may only be called from within a component's render", ); }); it('throws if preload is called outside render', () => { expect(() => TextResource.preload(['A', 1000])).toThrow( "read and preload may only be called from within a component's render", ); }); });
26.05303
99
0.535101
owtf
'use strict'; // This module is the single source of truth for versioning packages that we // publish to npm. // // Packages will not be published unless they are added here. // // The @latest channel uses the version as-is, e.g.: // // 18.3.0 // // The @canary channel appends additional information, with the scheme // <version>-<label>-<commit_sha>, e.g.: // // 18.3.0-canary-a1c2d3e4 // // The @experimental channel doesn't include a version, only a date and a sha, e.g.: // // 0.0.0-experimental-241c4467e-20200129 const ReactVersion = '18.3.0'; // The label used by the @canary channel. Represents the upcoming release's // stability. Most of the time, this will be "canary", but we may temporarily // choose to change it to "alpha", "beta", "rc", etc. // // It only affects the label used in the version string. To customize the // npm dist tags used during publish, refer to .circleci/config.yml. const canaryChannelLabel = 'canary'; const stablePackages = { 'eslint-plugin-react-hooks': '5.0.0', 'jest-react': '0.15.0', react: ReactVersion, 'react-art': ReactVersion, 'react-dom': ReactVersion, 'react-server-dom-webpack': ReactVersion, 'react-server-dom-turbopack': ReactVersion, 'react-is': ReactVersion, 'react-reconciler': '0.30.0', 'react-refresh': '0.15.0', 'react-test-renderer': ReactVersion, 'use-subscription': '1.9.0', 'use-sync-external-store': '1.3.0', scheduler: '0.24.0', }; // These packages do not exist in the @canary or @latest channel, only // @experimental. We don't use semver, just the commit sha, so this is just a // list of package names instead of a map. const experimentalPackages = []; module.exports = { ReactVersion, canaryChannelLabel, stablePackages, experimentalPackages, };
28.949153
84
0.695923
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 {UserTimingMark} from '../types'; import type { Interaction, MouseMoveInteraction, Rect, Size, ViewRefs, } from '../view-base'; import { positioningScaleFactor, timestampToPosition, positionToTimestamp, widthToDuration, } from './utils/positioning'; import { View, Surface, rectContainsPoint, rectIntersectsRect, intersectionOfRects, } from '../view-base'; import { COLORS, TOP_ROW_PADDING, USER_TIMING_MARK_SIZE, BORDER_SIZE, } from './constants'; const ROW_HEIGHT_FIXED = TOP_ROW_PADDING + USER_TIMING_MARK_SIZE + TOP_ROW_PADDING; export class UserTimingMarksView extends View { _marks: UserTimingMark[]; _intrinsicSize: Size; _hoveredMark: UserTimingMark | null = null; onHover: ((mark: UserTimingMark | null) => void) | null = null; constructor( surface: Surface, frame: Rect, marks: UserTimingMark[], duration: number, ) { super(surface, frame); this._marks = marks; this._intrinsicSize = { width: duration, height: ROW_HEIGHT_FIXED, }; } desiredSize(): Size { return this._intrinsicSize; } setHoveredMark(hoveredMark: UserTimingMark | null) { if (this._hoveredMark === hoveredMark) { return; } this._hoveredMark = hoveredMark; this.setNeedsDisplay(); } /** * Draw a single `UserTimingMark` as a circle in the canvas. */ _drawSingleMark( context: CanvasRenderingContext2D, rect: Rect, mark: UserTimingMark, baseY: number, scaleFactor: number, showHoverHighlight: boolean, ) { const {frame} = this; const {timestamp} = mark; const x = timestampToPosition(timestamp, scaleFactor, frame); const size = USER_TIMING_MARK_SIZE; const halfSize = size / 2; const markRect: Rect = { origin: { x: x - halfSize, y: baseY, }, size: {width: size, height: size}, }; if (!rectIntersectsRect(markRect, rect)) { return; // Not in view } const fillStyle = showHoverHighlight ? COLORS.USER_TIMING_HOVER : COLORS.USER_TIMING; if (fillStyle !== null) { const y = baseY + halfSize; context.beginPath(); context.fillStyle = fillStyle; context.moveTo(x, y - halfSize); context.lineTo(x + halfSize, y); context.lineTo(x, y + halfSize); context.lineTo(x - halfSize, y); context.fill(); } } draw(context: CanvasRenderingContext2D) { const {frame, _marks, _hoveredMark, visibleArea} = this; context.fillStyle = COLORS.BACKGROUND; context.fillRect( visibleArea.origin.x, visibleArea.origin.y, visibleArea.size.width, visibleArea.size.height, ); // Draw marks const baseY = frame.origin.y + TOP_ROW_PADDING; const scaleFactor = positioningScaleFactor( this._intrinsicSize.width, frame, ); _marks.forEach(mark => { if (mark === _hoveredMark) { return; } this._drawSingleMark( context, visibleArea, mark, baseY, scaleFactor, false, ); }); // Draw the hovered and/or selected items on top so they stand out. // This is helpful if there are multiple (overlapping) items close to each other. if (_hoveredMark !== null) { this._drawSingleMark( context, visibleArea, _hoveredMark, baseY, scaleFactor, true, ); } // Render bottom border. // Propose border rect, check if intersects with `rect`, draw intersection. const borderFrame: Rect = { origin: { x: frame.origin.x, y: frame.origin.y + ROW_HEIGHT_FIXED - BORDER_SIZE, }, size: { width: frame.size.width, height: BORDER_SIZE, }, }; if (rectIntersectsRect(borderFrame, visibleArea)) { const borderDrawableRect = intersectionOfRects(borderFrame, visibleArea); context.fillStyle = COLORS.PRIORITY_BORDER; context.fillRect( borderDrawableRect.origin.x, borderDrawableRect.origin.y, borderDrawableRect.size.width, borderDrawableRect.size.height, ); } } /** * @private */ _handleMouseMove(interaction: MouseMoveInteraction, viewRefs: ViewRefs) { const {frame, onHover, visibleArea} = this; if (!onHover) { return; } const {location} = interaction.payload; if (!rectContainsPoint(location, visibleArea)) { onHover(null); return; } const {_marks} = this; const scaleFactor = positioningScaleFactor( this._intrinsicSize.width, frame, ); const hoverTimestamp = positionToTimestamp(location.x, scaleFactor, frame); const timestampAllowance = widthToDuration( USER_TIMING_MARK_SIZE / 2, scaleFactor, ); // Because data ranges may overlap, we want to find the last intersecting item. // This will always be the one on "top" (the one the user is hovering over). for (let index = _marks.length - 1; index >= 0; index--) { const mark = _marks[index]; const {timestamp} = mark; if ( timestamp - timestampAllowance <= hoverTimestamp && hoverTimestamp <= timestamp + timestampAllowance ) { viewRefs.hoveredView = this; onHover(mark); return; } } onHover(null); } handleInteraction(interaction: Interaction, viewRefs: ViewRefs) { switch (interaction.type) { case 'mousemove': this._handleMouseMove(interaction, viewRefs); break; } } }
22.745902
85
0.620059
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'; process.on('unhandledRejection', err => { throw err; }); const chalk = require('chalk'); const runFlow = require('../flow/runFlow'); const inlinedHostConfigs = require('../shared/inlinedHostConfigs'); // This script is using `flow status` for a quick check with a server. // Use it for local development. const primaryRenderer = inlinedHostConfigs.find( info => info.isFlowTyped && info.shortName === process.argv[2] ); if (!primaryRenderer) { console.log( 'The ' + chalk.red('yarn flow') + ' command now requires you to pick a primary renderer:' ); console.log(); inlinedHostConfigs.forEach(rendererInfo => { if (rendererInfo.isFlowTyped) { console.log(' * ' + chalk.cyan('yarn flow ' + rendererInfo.shortName)); } }); console.log(); console.log( 'If you are not sure, run ' + chalk.green('yarn flow dom-node') + '.' ); console.log( 'This will still typecheck non-DOM packages, although less precisely.' ); console.log(); console.log('Note that checks for all renderers will run on CI.'); console.log( 'You can also do this locally with ' + chalk.cyan('yarn flow-ci') + ' but it will be slow.' ); console.log(); process.exit(1); } runFlow(primaryRenderer.shortName, ['status']);
25.963636
78
0.661269
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'; let React; let ReactDOM; describe('Component stack trace displaying', () => { beforeEach(() => { React = require('react'); ReactDOM = require('react-dom'); }); // @gate !enableComponentStackLocations || !__DEV__ it('should provide filenames in stack traces', () => { class Component extends React.Component { render() { return [<span>a</span>, <span>b</span>]; } } spyOnDev(console, 'error'); const container = document.createElement('div'); const fileNames = { '': '', '/': '', '\\': '', Foo: 'Foo', 'Bar/Foo': 'Foo', 'Bar\\Foo': 'Foo', 'Baz/Bar/Foo': 'Foo', 'Baz\\Bar\\Foo': 'Foo', 'Foo.js': 'Foo.js', 'Foo.jsx': 'Foo.jsx', '/Foo.js': 'Foo.js', '/Foo.jsx': 'Foo.jsx', '\\Foo.js': 'Foo.js', '\\Foo.jsx': 'Foo.jsx', 'Bar/Foo.js': 'Foo.js', 'Bar/Foo.jsx': 'Foo.jsx', 'Bar\\Foo.js': 'Foo.js', 'Bar\\Foo.jsx': 'Foo.jsx', '/Bar/Foo.js': 'Foo.js', '/Bar/Foo.jsx': 'Foo.jsx', '\\Bar\\Foo.js': 'Foo.js', '\\Bar\\Foo.jsx': 'Foo.jsx', 'Bar/Baz/Foo.js': 'Foo.js', 'Bar/Baz/Foo.jsx': 'Foo.jsx', 'Bar\\Baz\\Foo.js': 'Foo.js', 'Bar\\Baz\\Foo.jsx': 'Foo.jsx', '/Bar/Baz/Foo.js': 'Foo.js', '/Bar/Baz/Foo.jsx': 'Foo.jsx', '\\Bar\\Baz\\Foo.js': 'Foo.js', '\\Bar\\Baz\\Foo.jsx': 'Foo.jsx', 'C:\\funny long (path)/Foo.js': 'Foo.js', 'C:\\funny long (path)/Foo.jsx': 'Foo.jsx', 'index.js': 'index.js', 'index.jsx': 'index.jsx', '/index.js': 'index.js', '/index.jsx': 'index.jsx', '\\index.js': 'index.js', '\\index.jsx': 'index.jsx', 'Bar/index.js': 'Bar/index.js', 'Bar/index.jsx': 'Bar/index.jsx', 'Bar\\index.js': 'Bar/index.js', 'Bar\\index.jsx': 'Bar/index.jsx', '/Bar/index.js': 'Bar/index.js', '/Bar/index.jsx': 'Bar/index.jsx', '\\Bar\\index.js': 'Bar/index.js', '\\Bar\\index.jsx': 'Bar/index.jsx', 'Bar/Baz/index.js': 'Baz/index.js', 'Bar/Baz/index.jsx': 'Baz/index.jsx', 'Bar\\Baz\\index.js': 'Baz/index.js', 'Bar\\Baz\\index.jsx': 'Baz/index.jsx', '/Bar/Baz/index.js': 'Baz/index.js', '/Bar/Baz/index.jsx': 'Baz/index.jsx', '\\Bar\\Baz\\index.js': 'Baz/index.js', '\\Bar\\Baz\\index.jsx': 'Baz/index.jsx', 'C:\\funny long (path)/index.js': 'funny long (path)/index.js', 'C:\\funny long (path)/index.jsx': 'funny long (path)/index.jsx', }; Object.keys(fileNames).forEach((fileName, i) => { Component.displayName = 'Component ' + i; ReactDOM.render( <Component __source={{fileName, lineNumber: i}} />, container, ); }); if (__DEV__) { let i = 0; expect(console.error).toHaveBeenCalledTimes( Object.keys(fileNames).length, ); for (const fileName in fileNames) { if (!fileNames.hasOwnProperty(fileName)) { continue; } const args = console.error.mock.calls[i]; const stack = args[args.length - 1]; const expected = fileNames[fileName]; expect(stack).toContain(`at ${expected}:`); i++; } } }); });
28.948276
71
0.519148
owtf
import FixtureSet from '../../FixtureSet'; import ReorderedInputsTestCase from './ReorderedInputsTestCase'; import OnSelectEventTestCase from './OnSelectEventTestCase'; const React = window.React; export default function SelectionEvents() { return ( <FixtureSet title="Selection Restoration" description=" When React commits changes it may perform operations which cause existing selection state to be lost. This is manually managed by reading the selection state before commits and then restoring it afterwards. "> <ReorderedInputsTestCase /> <OnSelectEventTestCase /> </FixtureSet> ); }
31.55
79
0.729231
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('EventPluginRegistry', () => { let EventPluginRegistry; let createPlugin; beforeEach(() => { jest.resetModules(); // These tests are intentionally testing the private injection interface. // The public API surface of this is covered by other tests so // if `EventPluginRegistry` is ever deleted, these tests should be // safe to remove too. EventPluginRegistry = require('react-native-renderer/src/legacy-events/EventPluginRegistry'); createPlugin = function (properties) { return Object.assign({extractEvents: function () {}}, properties); }; }); it('should be able to inject ordering before plugins', () => { const OnePlugin = createPlugin(); const TwoPlugin = createPlugin(); const ThreePlugin = createPlugin(); EventPluginRegistry.injectEventPluginOrder(['one', 'two', 'three']); EventPluginRegistry.injectEventPluginsByName({ one: OnePlugin, two: TwoPlugin, }); EventPluginRegistry.injectEventPluginsByName({ three: ThreePlugin, }); expect(EventPluginRegistry.plugins.length).toBe(3); expect(EventPluginRegistry.plugins[0]).toBe(OnePlugin); expect(EventPluginRegistry.plugins[1]).toBe(TwoPlugin); expect(EventPluginRegistry.plugins[2]).toBe(ThreePlugin); }); it('should be able to inject plugins before and after ordering', () => { const OnePlugin = createPlugin(); const TwoPlugin = createPlugin(); const ThreePlugin = createPlugin(); EventPluginRegistry.injectEventPluginsByName({ one: OnePlugin, two: TwoPlugin, }); EventPluginRegistry.injectEventPluginOrder(['one', 'two', 'three']); EventPluginRegistry.injectEventPluginsByName({ three: ThreePlugin, }); expect(EventPluginRegistry.plugins.length).toBe(3); expect(EventPluginRegistry.plugins[0]).toBe(OnePlugin); expect(EventPluginRegistry.plugins[1]).toBe(TwoPlugin); expect(EventPluginRegistry.plugins[2]).toBe(ThreePlugin); }); it('should be able to inject repeated plugins and out-of-order', () => { const OnePlugin = createPlugin(); const TwoPlugin = createPlugin(); const ThreePlugin = createPlugin(); EventPluginRegistry.injectEventPluginsByName({ one: OnePlugin, three: ThreePlugin, }); EventPluginRegistry.injectEventPluginOrder(['one', 'two', 'three']); EventPluginRegistry.injectEventPluginsByName({ two: TwoPlugin, three: ThreePlugin, }); expect(EventPluginRegistry.plugins.length).toBe(3); expect(EventPluginRegistry.plugins[0]).toBe(OnePlugin); expect(EventPluginRegistry.plugins[1]).toBe(TwoPlugin); expect(EventPluginRegistry.plugins[2]).toBe(ThreePlugin); }); it('should throw if plugin does not implement `extractEvents`', () => { const BadPlugin = {}; EventPluginRegistry.injectEventPluginOrder(['bad']); expect(function () { EventPluginRegistry.injectEventPluginsByName({ bad: BadPlugin, }); }).toThrowError( 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `bad` does not.', ); }); it('should throw if plugin does not exist in ordering', () => { const OnePlugin = createPlugin(); const RandomPlugin = createPlugin(); EventPluginRegistry.injectEventPluginOrder(['one']); expect(function () { EventPluginRegistry.injectEventPluginsByName({ one: OnePlugin, random: RandomPlugin, }); }).toThrowError( 'EventPluginRegistry: Cannot inject event plugins that do not exist ' + 'in the plugin ordering, `random`.', ); }); it('should throw if ordering is injected more than once', () => { const pluginOrdering = []; EventPluginRegistry.injectEventPluginOrder(pluginOrdering); expect(function () { EventPluginRegistry.injectEventPluginOrder(pluginOrdering); }).toThrowError( 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.', ); }); it('should throw if different plugins injected using same name', () => { const OnePlugin = createPlugin(); const TwoPlugin = createPlugin(); EventPluginRegistry.injectEventPluginsByName({same: OnePlugin}); expect(function () { EventPluginRegistry.injectEventPluginsByName({same: TwoPlugin}); }).toThrowError( 'EventPluginRegistry: Cannot inject two different event plugins using ' + 'the same name, `same`.', ); }); it('should publish registration names of injected plugins', () => { const OnePlugin = createPlugin({ eventTypes: { click: {registrationName: 'onClick'}, focus: {registrationName: 'onFocus'}, }, }); const TwoPlugin = createPlugin({ eventTypes: { magic: { phasedRegistrationNames: { bubbled: 'onMagicBubble', captured: 'onMagicCapture', }, }, }, }); EventPluginRegistry.injectEventPluginsByName({one: OnePlugin}); EventPluginRegistry.injectEventPluginOrder(['one', 'two']); expect( Object.keys(EventPluginRegistry.registrationNameModules).length, ).toBe(2); expect(EventPluginRegistry.registrationNameModules.onClick).toBe(OnePlugin); expect(EventPluginRegistry.registrationNameModules.onFocus).toBe(OnePlugin); EventPluginRegistry.injectEventPluginsByName({two: TwoPlugin}); expect( Object.keys(EventPluginRegistry.registrationNameModules).length, ).toBe(4); expect(EventPluginRegistry.registrationNameModules.onMagicBubble).toBe( TwoPlugin, ); expect(EventPluginRegistry.registrationNameModules.onMagicCapture).toBe( TwoPlugin, ); }); it('should throw if multiple registration names collide', () => { const OnePlugin = createPlugin({ eventTypes: { photoCapture: {registrationName: 'onPhotoCapture'}, }, }); const TwoPlugin = createPlugin({ eventTypes: { photo: { phasedRegistrationNames: { bubbled: 'onPhotoBubble', captured: 'onPhotoCapture', }, }, }, }); EventPluginRegistry.injectEventPluginsByName({ one: OnePlugin, two: TwoPlugin, }); expect(function () { EventPluginRegistry.injectEventPluginOrder(['one', 'two']); }).toThrowError( 'EventPluginRegistry: More than one plugin attempted to publish the same ' + 'registration name, `onPhotoCapture`.', ); }); it('should throw if an invalid event is published', () => { const OnePlugin = createPlugin({ eventTypes: { badEvent: { /* missing configuration */ }, }, }); EventPluginRegistry.injectEventPluginsByName({one: OnePlugin}); expect(function () { EventPluginRegistry.injectEventPluginOrder(['one']); }).toThrowError( 'EventPluginRegistry: Failed to publish event `badEvent` for plugin ' + '`one`.', ); }); });
29.739496
97
0.664252
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 */ // sanity tests to make sure act() works without a mocked scheduler let React; let ReactDOM; let act; let container; let yields; function clearLog() { try { return yields; } finally { yields = []; } } function render(el, dom) { ReactDOM.render(el, dom); } function unmount(dom) { ReactDOM.unmountComponentAtNode(dom); } beforeEach(() => { jest.resetModules(); jest.unmock('scheduler'); yields = []; React = require('react'); ReactDOM = require('react-dom'); act = React.unstable_act; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { unmount(container); document.body.removeChild(container); }); // @gate __DEV__ it('can use act to flush effects', () => { function App() { React.useEffect(() => { yields.push(100); }); return null; } act(() => { render(<App />, container); }); expect(clearLog()).toEqual([100]); }); // @gate __DEV__ it('flushes effects on every call', () => { function App() { const [ctr, setCtr] = React.useState(0); React.useEffect(() => { yields.push(ctr); }); return ( <button id="button" onClick={() => setCtr(x => x + 1)}> {ctr} </button> ); } act(() => { render(<App />, container); }); expect(clearLog()).toEqual([0]); const button = container.querySelector('#button'); function click() { button.dispatchEvent(new MouseEvent('click', {bubbles: true})); } act(() => { click(); click(); click(); }); // it consolidates the 3 updates, then fires the effect expect(clearLog()).toEqual([3]); act(click); expect(clearLog()).toEqual([4]); act(click); expect(clearLog()).toEqual([5]); expect(button.innerHTML).toEqual('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).toEqual('5'); }); // @gate __DEV__ it('should flush effects only on exiting the outermost act', () => { function App() { React.useEffect(() => { yields.push(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 expect(clearLog()).toEqual([]); }); // but after exiting the last one, effects get flushed expect(clearLog()).toEqual([0]); }); // @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(() => { yields.push(state); ticker(); }, [Math.min(state, 4)]); return state; } await act(async () => { render(<App />, container); }); // all 5 ticks present and accounted for expect(clearLog()).toEqual([0, 1, 2, 3, 4]); expect(container.innerHTML).toBe('5'); });
19.893491
68
0.579603
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'; export default function createPublicInstance( tag: number, viewConfig: mixed, internalInstanceHandle: mixed, ): PublicInstance { return { __nativeTag: tag, __internalInstanceHandle: internalInstanceHandle, }; }
22.136364
66
0.726378
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 */ import {enableBinaryFlight} from 'shared/ReactFeatureFlags'; import type {Thenable} from 'shared/ReactTypes'; import type {Response as FlightResponse} from 'react-client/src/ReactFlightClient'; import { createResponse, getRoot, reportGlobalError, processBinaryChunk, close, } from 'react-client/src/ReactFlightClient'; import type {SSRModuleMap} from './ReactFlightClientConfigFBBundler'; type Options = { moduleMap: SSRModuleMap, }; function createResponseFromOptions(options: void | Options) { const moduleMap = options && options.moduleMap; if (moduleMap == null) { throw new Error('Expected `moduleMap` to be defined.'); } return createResponse(moduleMap, null, undefined, undefined); } function processChunk(response: FlightResponse, chunk: string | Uint8Array) { if (enableBinaryFlight) { if (typeof chunk === 'string') { throw new Error( '`enableBinaryFlight` flag is enabled, expected a Uint8Array as input, got string.', ); } } const buffer = typeof chunk !== 'string' ? chunk : encodeString(chunk); processBinaryChunk(response, buffer); } function encodeString(string: string) { const textEncoder = new TextEncoder(); return textEncoder.encode(string); } function startReadingFromStream( response: FlightResponse, stream: ReadableStream, ): void { const reader = stream.getReader(); function progress({ done, value, }: { done: boolean, value: ?any, ... }): void | Promise<void> { if (done) { close(response); return; } const buffer: Uint8Array = (value: any); processChunk(response, buffer); return reader.read().then(progress).catch(error); } function error(e: any) { reportGlobalError(response, e); } reader.read().then(progress).catch(error); } function createFromReadableStream<T>( stream: ReadableStream, options?: Options, ): Thenable<T> { const response: FlightResponse = createResponseFromOptions(options); startReadingFromStream(response, stream); return getRoot(response); } export {createFromReadableStream};
23.956522
92
0.703704
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 {NativeEvent, TimelineData} from '../types'; import type { Interaction, IntrinsicSize, MouseMoveInteraction, Rect, ViewRefs, } from '../view-base'; import { durationToWidth, positioningScaleFactor, positionToTimestamp, timestampToPosition, } from './utils/positioning'; import {drawText} from './utils/text'; import {formatDuration} from '../utils/formatting'; import { View, Surface, rectContainsPoint, rectIntersectsRect, intersectionOfRects, } from '../view-base'; import {COLORS, NATIVE_EVENT_HEIGHT, BORDER_SIZE} from './constants'; const ROW_WITH_BORDER_HEIGHT = NATIVE_EVENT_HEIGHT + BORDER_SIZE; export class NativeEventsView extends View { _depthToNativeEvent: Map<number, NativeEvent[]>; _hoveredEvent: NativeEvent | null = null; _intrinsicSize: IntrinsicSize; _maxDepth: number = 0; _profilerData: TimelineData; onHover: ((event: NativeEvent | null) => void) | null = null; constructor(surface: Surface, frame: Rect, profilerData: TimelineData) { super(surface, frame); this._profilerData = profilerData; this._performPreflightComputations(); } _performPreflightComputations() { this._depthToNativeEvent = new Map(); const {duration, nativeEvents} = this._profilerData; nativeEvents.forEach(event => { const depth = event.depth; this._maxDepth = Math.max(this._maxDepth, depth); if (!this._depthToNativeEvent.has(depth)) { this._depthToNativeEvent.set(depth, [event]); } else { // $FlowFixMe[incompatible-use] This is unnecessary. this._depthToNativeEvent.get(depth).push(event); } }); this._intrinsicSize = { width: duration, height: (this._maxDepth + 1) * ROW_WITH_BORDER_HEIGHT, hideScrollBarIfLessThanHeight: ROW_WITH_BORDER_HEIGHT, }; } desiredSize(): IntrinsicSize { return this._intrinsicSize; } setHoveredEvent(hoveredEvent: NativeEvent | null) { if (this._hoveredEvent === hoveredEvent) { return; } this._hoveredEvent = hoveredEvent; this.setNeedsDisplay(); } /** * Draw a single `NativeEvent` as a box/span with text inside of it. */ _drawSingleNativeEvent( context: CanvasRenderingContext2D, rect: Rect, event: NativeEvent, baseY: number, scaleFactor: number, showHoverHighlight: boolean, ) { const {frame} = this; const {depth, duration, timestamp, type, warning} = event; baseY += depth * ROW_WITH_BORDER_HEIGHT; const xStart = timestampToPosition(timestamp, scaleFactor, frame); const xStop = timestampToPosition(timestamp + duration, scaleFactor, frame); const eventRect: Rect = { origin: { x: xStart, y: baseY, }, size: {width: xStop - xStart, height: NATIVE_EVENT_HEIGHT}, }; if (!rectIntersectsRect(eventRect, rect)) { return; // Not in view } const width = durationToWidth(duration, scaleFactor); if (width < 1) { return; // Too small to render at this zoom level } const drawableRect = intersectionOfRects(eventRect, rect); context.beginPath(); if (warning !== null) { context.fillStyle = showHoverHighlight ? COLORS.WARNING_BACKGROUND_HOVER : COLORS.WARNING_BACKGROUND; } else { context.fillStyle = showHoverHighlight ? COLORS.NATIVE_EVENT_HOVER : COLORS.NATIVE_EVENT; } context.fillRect( drawableRect.origin.x, drawableRect.origin.y, drawableRect.size.width, drawableRect.size.height, ); const label = `${type} - ${formatDuration(duration)}`; drawText(label, context, eventRect, drawableRect); } draw(context: CanvasRenderingContext2D) { const { frame, _profilerData: {nativeEvents}, _hoveredEvent, visibleArea, } = this; context.fillStyle = COLORS.PRIORITY_BACKGROUND; context.fillRect( visibleArea.origin.x, visibleArea.origin.y, visibleArea.size.width, visibleArea.size.height, ); // Draw events const scaleFactor = positioningScaleFactor( this._intrinsicSize.width, frame, ); nativeEvents.forEach(event => { this._drawSingleNativeEvent( context, visibleArea, event, frame.origin.y, scaleFactor, event === _hoveredEvent, ); }); // Render bottom borders. for (let i = 0; i <= this._maxDepth; i++) { const borderFrame: Rect = { origin: { x: frame.origin.x, y: frame.origin.y + NATIVE_EVENT_HEIGHT, }, size: { width: frame.size.width, height: BORDER_SIZE, }, }; if (rectIntersectsRect(borderFrame, visibleArea)) { const borderDrawableRect = intersectionOfRects( borderFrame, visibleArea, ); context.fillStyle = COLORS.PRIORITY_BORDER; context.fillRect( borderDrawableRect.origin.x, borderDrawableRect.origin.y, borderDrawableRect.size.width, borderDrawableRect.size.height, ); } } } /** * @private */ _handleMouseMove(interaction: MouseMoveInteraction, viewRefs: ViewRefs) { const {frame, _intrinsicSize, onHover, visibleArea} = this; if (!onHover) { return; } const {location} = interaction.payload; if (!rectContainsPoint(location, visibleArea)) { onHover(null); return; } const scaleFactor = positioningScaleFactor(_intrinsicSize.width, frame); const hoverTimestamp = positionToTimestamp(location.x, scaleFactor, frame); const adjustedCanvasMouseY = location.y - frame.origin.y; const depth = Math.floor(adjustedCanvasMouseY / ROW_WITH_BORDER_HEIGHT); const nativeEventsAtDepth = this._depthToNativeEvent.get(depth); if (nativeEventsAtDepth) { // Find the event being hovered over. for (let index = nativeEventsAtDepth.length - 1; index >= 0; index--) { const nativeEvent = nativeEventsAtDepth[index]; const {duration, timestamp} = nativeEvent; if ( hoverTimestamp >= timestamp && hoverTimestamp <= timestamp + duration ) { viewRefs.hoveredView = this; onHover(nativeEvent); return; } } } onHover(null); } handleInteraction(interaction: Interaction, viewRefs: ViewRefs) { switch (interaction.type) { case 'mousemove': this._handleMouseMove(interaction, viewRefs); break; } } }
25.119231
80
0.637113
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 node */ 'use strict'; let createReactNativeComponentClass; let React; let ReactNative; describe('createReactNativeComponentClass', () => { beforeEach(() => { jest.resetModules(); createReactNativeComponentClass = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface') .ReactNativeViewConfigRegistry.register; React = require('react'); ReactNative = require('react-native-renderer'); }); it('should register viewConfigs', () => { const textViewConfig = { validAttributes: {}, uiViewClassName: 'Text', }; const viewViewConfig = { validAttributes: {}, uiViewClassName: 'View', }; const Text = createReactNativeComponentClass( textViewConfig.uiViewClassName, () => textViewConfig, ); const View = createReactNativeComponentClass( viewViewConfig.uiViewClassName, () => viewViewConfig, ); expect(Text).not.toBe(View); ReactNative.render(<Text />, 1); ReactNative.render(<View />, 1); }); it('should not allow viewConfigs with duplicate uiViewClassNames to be registered', () => { const textViewConfig = { validAttributes: {}, uiViewClassName: 'Text', }; const altTextViewConfig = { validAttributes: {}, uiViewClassName: 'Text', // Same }; createReactNativeComponentClass( textViewConfig.uiViewClassName, () => textViewConfig, ); expect(() => { createReactNativeComponentClass( altTextViewConfig.uiViewClassName, () => altTextViewConfig, ); }).toThrow('Tried to register two views with the same name Text'); }); });
24.065789
93
0.653361
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 ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOMServer; function initModules() { // Reset warning cache. jest.resetModules(); React = require('react'); ReactDOMServer = require('react-dom/server'); // Make them available to the helpers. return { ReactDOMServer, }; } const {resetModules} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerLifecycles', () => { beforeEach(() => { resetModules(); }); it('should invoke the correct legacy lifecycle hooks', () => { const log = []; class Outer extends React.Component { UNSAFE_componentWillMount() { log.push('outer componentWillMount'); } render() { log.push('outer render'); return <Inner />; } } class Inner extends React.Component { UNSAFE_componentWillMount() { log.push('inner componentWillMount'); } render() { log.push('inner render'); return null; } } ReactDOMServer.renderToString(<Outer />); expect(log).toEqual([ 'outer componentWillMount', 'outer render', 'inner componentWillMount', 'inner render', ]); }); it('should invoke the correct new lifecycle hooks', () => { const log = []; class Outer extends React.Component { state = {}; static getDerivedStateFromProps() { log.push('outer getDerivedStateFromProps'); return null; } render() { log.push('outer render'); return <Inner />; } } class Inner extends React.Component { state = {}; static getDerivedStateFromProps() { log.push('inner getDerivedStateFromProps'); return null; } render() { log.push('inner render'); return null; } } ReactDOMServer.renderToString(<Outer />); expect(log).toEqual([ 'outer getDerivedStateFromProps', 'outer render', 'inner getDerivedStateFromProps', 'inner render', ]); }); it('should not invoke unsafe cWM if static gDSFP is present', () => { class Component extends React.Component { state = {}; static getDerivedStateFromProps() { return null; } UNSAFE_componentWillMount() { throw Error('unexpected'); } render() { return null; } } expect(() => ReactDOMServer.renderToString(<Component />)).toErrorDev( 'Unsafe legacy lifecycles will not be called for components using new component APIs.', ); }); it('should update instance.state with value returned from getDerivedStateFromProps', () => { class Grandparent extends React.Component { state = { foo: 'foo', }; render() { return ( <div> {`Grandparent: ${this.state.foo}`} <Parent /> </div> ); } } class Parent extends React.Component { state = { bar: 'bar', baz: 'baz', }; static getDerivedStateFromProps(props, prevState) { return { bar: `not ${prevState.bar}`, }; } render() { return ( <div> {`Parent: ${this.state.bar}, ${this.state.baz}`} <Child />; </div> ); } } class Child extends React.Component { state = {}; static getDerivedStateFromProps() { return { qux: 'qux', }; } render() { return `Child: ${this.state.qux}`; } } const markup = ReactDOMServer.renderToString(<Grandparent />); expect(markup).toContain('Grandparent: foo'); expect(markup).toContain('Parent: not bar, baz'); expect(markup).toContain('Child: qux'); }); it('should warn if getDerivedStateFromProps returns undefined', () => { class Component extends React.Component { state = {}; static getDerivedStateFromProps() {} render() { return null; } } expect(() => ReactDOMServer.renderToString(<Component />)).toErrorDev( 'Component.getDerivedStateFromProps(): A valid state object (or null) must ' + 'be returned. You have returned undefined.', ); // De-duped ReactDOMServer.renderToString(<Component />); }); it('should warn if state is not initialized before getDerivedStateFromProps', () => { class Component extends React.Component { static getDerivedStateFromProps() { return null; } render() { return null; } } expect(() => ReactDOMServer.renderToString(<Component />)).toErrorDev( '`Component` uses `getDerivedStateFromProps` but its initial state is ' + 'undefined. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `Component`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', ); // De-duped ReactDOMServer.renderToString(<Component />); }); it('should invoke both deprecated and new lifecycles if both are present', () => { const log = []; class Component extends React.Component { componentWillMount() { log.push('componentWillMount'); } UNSAFE_componentWillMount() { log.push('UNSAFE_componentWillMount'); } render() { return null; } } expect(() => ReactDOMServer.renderToString(<Component />)).toWarnDev( 'componentWillMount has been renamed', ); expect(log).toEqual(['componentWillMount', 'UNSAFE_componentWillMount']); }); it('tracks state updates across components', () => { class Outer extends React.Component { UNSAFE_componentWillMount() { this.setState({x: 1}); } render() { return <Inner updateParent={this.updateParent}>{this.state.x}</Inner>; } updateParent = () => { this.setState({x: 3}); }; } class Inner extends React.Component { UNSAFE_componentWillMount() { this.setState({x: 2}); this.props.updateParent(); } render() { return <div>{this.props.children + '-' + this.state.x}</div>; } } expect(() => { // Shouldn't be 1-3. expect(ReactDOMServer.renderToStaticMarkup(<Outer />)).toBe( '<div>1-2</div>', ); }).toErrorDev( 'Warning: setState(...): Can only update a mounting component. This ' + 'usually means you called setState() outside componentWillMount() on ' + 'the server. This is a no-op.\n\n' + 'Please check the code for the Outer component.', ); }); it('should not invoke cWM if static gDSFP is present', () => { class Component extends React.Component { state = {}; static getDerivedStateFromProps() { return null; } componentWillMount() { throw Error('unexpected'); } render() { return null; } } expect(() => ReactDOMServer.renderToString(<Component />)).toErrorDev( 'Unsafe legacy lifecycles will not be called for components using new component APIs.', ); }); it('should warn about deprecated lifecycle hooks', () => { class MyComponent extends React.Component { componentWillMount() {} render() { return null; } } expect(() => ReactDOMServer.renderToString(<MyComponent />)).toWarnDev( 'componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) or the constructor.\n\n' + 'Please update the following components: MyComponent', ); // De-duped ReactDOMServer.renderToString(<MyComponent />); }); describe('react-lifecycles-compat', () => { const {polyfill} = require('react-lifecycles-compat'); it('should not warn for components with polyfilled getDerivedStateFromProps', () => { class PolyfilledComponent extends React.Component { state = {}; static getDerivedStateFromProps() { return null; } render() { return null; } } polyfill(PolyfilledComponent); const container = document.createElement('div'); ReactDOMServer.renderToString( <React.StrictMode> <PolyfilledComponent /> </React.StrictMode>, container, ); }); it('should not warn for components with polyfilled getSnapshotBeforeUpdate', () => { class PolyfilledComponent extends React.Component { getSnapshotBeforeUpdate() { return null; } componentDidUpdate() {} render() { return null; } } polyfill(PolyfilledComponent); const container = document.createElement('div'); ReactDOMServer.renderToString( <React.StrictMode> <PolyfilledComponent /> </React.StrictMode>, container, ); }); }); });
25.535211
152
0.589872
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'; let Scheduler; let scheduleCallback; let ImmediatePriority; let UserBlockingPriority; let NormalPriority; describe('SchedulerNoDOM', () => { // Scheduler falls back to a naive implementation using setTimeout. // This is only meant to be used for testing purposes, like with jest's fake timer API. beforeEach(() => { jest.resetModules(); jest.useFakeTimers(); delete global.setImmediate; delete global.MessageChannel; jest.unmock('scheduler'); Scheduler = require('scheduler'); scheduleCallback = Scheduler.unstable_scheduleCallback; UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; NormalPriority = Scheduler.unstable_NormalPriority; }); it('runAllTimers flushes all scheduled callbacks', () => { const log = []; scheduleCallback(NormalPriority, () => { log.push('A'); }); scheduleCallback(NormalPriority, () => { log.push('B'); }); scheduleCallback(NormalPriority, () => { log.push('C'); }); expect(log).toEqual([]); jest.runAllTimers(); expect(log).toEqual(['A', 'B', 'C']); }); it('executes callbacks in order of priority', () => { const log = []; scheduleCallback(NormalPriority, () => { log.push('A'); }); scheduleCallback(NormalPriority, () => { log.push('B'); }); scheduleCallback(UserBlockingPriority, () => { log.push('C'); }); scheduleCallback(UserBlockingPriority, () => { log.push('D'); }); expect(log).toEqual([]); jest.runAllTimers(); expect(log).toEqual(['C', 'D', 'A', 'B']); }); it('handles errors', () => { let log = []; scheduleCallback(ImmediatePriority, () => { log.push('A'); throw new Error('Oops A'); }); scheduleCallback(ImmediatePriority, () => { log.push('B'); }); scheduleCallback(ImmediatePriority, () => { log.push('C'); throw new Error('Oops C'); }); expect(() => jest.runAllTimers()).toThrow('Oops A'); expect(log).toEqual(['A']); log = []; // B and C flush in a subsequent event. That way, the second error is not // swallowed. expect(() => jest.runAllTimers()).toThrow('Oops C'); expect(log).toEqual(['B', 'C']); }); }); // See: https://github.com/facebook/react/pull/13088 describe('does not crash non-node SSR environments', () => { it('if setTimeout is undefined', () => { jest.resetModules(); const originalSetTimeout = global.setTimeout; try { delete global.setTimeout; jest.unmock('scheduler'); expect(() => { require('scheduler'); }).not.toThrow(); } finally { global.setTimeout = originalSetTimeout; } }); it('if clearTimeout is undefined', () => { jest.resetModules(); const originalClearTimeout = global.clearTimeout; try { delete global.clearTimeout; jest.unmock('scheduler'); expect(() => { require('scheduler'); }).not.toThrow(); } finally { global.clearTimeout = originalClearTimeout; } }); });
24.592308
89
0.604931
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. */ const {execSync} = require('child_process'); const {readFileSync} = require('fs'); const {resolve} = require('path'); const DARK_MODE_DIMMED_WARNING_COLOR = 'rgba(250, 180, 50, 0.5)'; const DARK_MODE_DIMMED_ERROR_COLOR = 'rgba(250, 123, 130, 0.5)'; const DARK_MODE_DIMMED_LOG_COLOR = 'rgba(125, 125, 125, 0.5)'; const LIGHT_MODE_DIMMED_WARNING_COLOR = 'rgba(250, 180, 50, 0.75)'; const LIGHT_MODE_DIMMED_ERROR_COLOR = 'rgba(250, 123, 130, 0.75)'; const LIGHT_MODE_DIMMED_LOG_COLOR = 'rgba(125, 125, 125, 0.75)'; const GITHUB_URL = 'https://github.com/facebook/react'; function getGitCommit() { try { return execSync('git show -s --no-show-signature --format=%h') .toString() .trim(); } catch (error) { // Mozilla runs this command from a git archive. // In that context, there is no Git revision. return null; } } function getVersionString(packageVersion = null) { if (packageVersion == null) { packageVersion = JSON.parse( readFileSync( resolve(__dirname, '..', 'react-devtools-core', './package.json'), ), ).version; } const commit = getGitCommit(); return `${packageVersion}-${commit}`; } module.exports = { 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, getGitCommit, getVersionString, };
27.086207
74
0.66769
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 {Fiber} from './ReactInternalTypes'; import { enableProfilerCommitHooks, enableProfilerNestedUpdatePhase, enableProfilerTimer, } from 'shared/ReactFeatureFlags'; import {HostRoot, Profiler} from './ReactWorkTags'; // Intentionally not named imports because Rollup would use dynamic dispatch for // CommonJS interop named imports. import * as Scheduler from 'scheduler'; const {unstable_now: now} = Scheduler; export type ProfilerTimer = { getCommitTime(): number, isCurrentUpdateNested(): boolean, markNestedUpdateScheduled(): void, recordCommitTime(): void, startProfilerTimer(fiber: Fiber): void, stopProfilerTimerIfRunning(fiber: Fiber): void, stopProfilerTimerIfRunningAndRecordDelta(fiber: Fiber): void, syncNestedUpdateFlag(): void, ... }; let commitTime: number = 0; let layoutEffectStartTime: number = -1; let profilerStartTime: number = -1; let passiveEffectStartTime: number = -1; /** * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). * * The overall sequence is: * 1. render * 2. commit (and call `onRender`, `onCommit`) * 3. check for nested updates * 4. flush passive effects (and call `onPostCommit`) * * Nested updates are identified in step 3 above, * but step 4 still applies to the work that was just committed. * We use two flags to track nested updates then: * one tracks whether the upcoming update is a nested update, * and the other tracks whether the current update was a nested update. * The first value gets synced to the second at the start of the render phase. */ let currentUpdateIsNested: boolean = false; let nestedUpdateScheduled: boolean = false; function isCurrentUpdateNested(): boolean { return currentUpdateIsNested; } function markNestedUpdateScheduled(): void { if (enableProfilerNestedUpdatePhase) { nestedUpdateScheduled = true; } } function resetNestedUpdateFlag(): void { if (enableProfilerNestedUpdatePhase) { currentUpdateIsNested = false; nestedUpdateScheduled = false; } } function syncNestedUpdateFlag(): void { if (enableProfilerNestedUpdatePhase) { currentUpdateIsNested = nestedUpdateScheduled; nestedUpdateScheduled = false; } } function getCommitTime(): number { return commitTime; } function recordCommitTime(): void { if (!enableProfilerTimer) { return; } commitTime = now(); } function startProfilerTimer(fiber: Fiber): void { if (!enableProfilerTimer) { return; } profilerStartTime = now(); if (((fiber.actualStartTime: any): number) < 0) { fiber.actualStartTime = now(); } } function stopProfilerTimerIfRunning(fiber: Fiber): void { if (!enableProfilerTimer) { return; } profilerStartTime = -1; } function stopProfilerTimerIfRunningAndRecordDelta( fiber: Fiber, overrideBaseTime: boolean, ): void { if (!enableProfilerTimer) { return; } if (profilerStartTime >= 0) { const elapsedTime = now() - profilerStartTime; fiber.actualDuration += elapsedTime; if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } profilerStartTime = -1; } } function recordLayoutEffectDuration(fiber: Fiber): void { if (!enableProfilerTimer || !enableProfilerCommitHooks) { return; } if (layoutEffectStartTime >= 0) { const elapsedTime = now() - layoutEffectStartTime; layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor // Or the root (for the DevTools Profiler to read) let parentFiber = fiber.return; while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: const root = parentFiber.stateNode; root.effectDuration += elapsedTime; return; case Profiler: const parentStateNode = parentFiber.stateNode; parentStateNode.effectDuration += elapsedTime; return; } parentFiber = parentFiber.return; } } } function recordPassiveEffectDuration(fiber: Fiber): void { if (!enableProfilerTimer || !enableProfilerCommitHooks) { return; } if (passiveEffectStartTime >= 0) { const elapsedTime = now() - passiveEffectStartTime; passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor // Or the root (for the DevTools Profiler to read) let parentFiber = fiber.return; while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: const root = parentFiber.stateNode; if (root !== null) { root.passiveEffectDuration += elapsedTime; } return; case Profiler: const parentStateNode = parentFiber.stateNode; if (parentStateNode !== null) { // Detached fibers have their state node cleared out. // In this case, the return pointer is also cleared out, // so we won't be able to report the time spent in this Profiler's subtree. parentStateNode.passiveEffectDuration += elapsedTime; } return; } parentFiber = parentFiber.return; } } } function startLayoutEffectTimer(): void { if (!enableProfilerTimer || !enableProfilerCommitHooks) { return; } layoutEffectStartTime = now(); } function startPassiveEffectTimer(): void { if (!enableProfilerTimer || !enableProfilerCommitHooks) { return; } passiveEffectStartTime = now(); } function transferActualDuration(fiber: Fiber): void { // Transfer time spent rendering these children so we don't lose it // after we rerender. This is used as a helper in special cases // where we should count the work of multiple passes. let child = fiber.child; while (child) { // $FlowFixMe[unsafe-addition] addition with possible null/undefined value fiber.actualDuration += child.actualDuration; child = child.sibling; } } export { getCommitTime, isCurrentUpdateNested, markNestedUpdateScheduled, recordCommitTime, recordLayoutEffectDuration, recordPassiveEffectDuration, resetNestedUpdateFlag, startLayoutEffectTimer, startPassiveEffectTimer, startProfilerTimer, stopProfilerTimerIfRunning, stopProfilerTimerIfRunningAndRecordDelta, syncNestedUpdateFlag, transferActualDuration, };
26.083333
100
0.703339
cybersecurity-penetration-testing
/** * 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. * * @emails react-core */ 'use strict'; describe('ReactDOMInReactServer', () => { beforeEach(() => { jest.resetModules(); jest.mock('react', () => require('react/react.shared-subset')); }); it('can require react-dom', () => { // In RSC this will be aliased. require('react'); require('react-dom'); }); });
21.166667
67
0.619586
null
/** * 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. * * @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; global.Headers = require('node-fetch').Headers; global.Request = require('node-fetch').Request; global.Response = require('node-fetch').Response; let fetchCount = 0; async function fetchMock(resource, options) { fetchCount++; const request = new Request(resource, options); return new Response( request.method + ' ' + request.url + ' ' + JSON.stringify(Array.from(request.headers.entries())), ); } let React; let ReactServer; let ReactServerDOMServer; let ReactServerDOMClient; let use; let cache; describe('ReactFetch', () => { beforeEach(() => { jest.resetModules(); fetchCount = 0; global.fetch = fetchMock; jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-server-dom-webpack/server', () => require('react-server-dom-webpack/server.browser'), ); require('react-server-dom-webpack/src/__tests__/utils/WebpackMock'); ReactServerDOMServer = require('react-server-dom-webpack/server'); ReactServer = require('react'); jest.resetModules(); __unmockReact(); jest.unmock('react-server-dom-webpack/server'); ReactServerDOMClient = require('react-server-dom-webpack/client'); React = require('react'); use = ReactServer.use; cache = ReactServer.cache; }); async function render(Component) { const stream = ReactServerDOMServer.renderToReadableStream(<Component />); return ReactServerDOMClient.createFromReadableStream(stream); } it('can fetch duplicates outside of render', async () => { let response = await fetch('world'); let text = await response.text(); expect(text).toMatchInlineSnapshot(`"GET world []"`); response = await fetch('world'); text = await response.text(); expect(text).toMatchInlineSnapshot(`"GET world []"`); expect(fetchCount).toBe(2); }); // @gate enableFetchInstrumentation && enableCache it('can dedupe fetches inside of render', async () => { function Component() { const response = use(fetch('world')); const text = use(response.text()); return text; } expect(await render(Component)).toMatchInlineSnapshot(`"GET world []"`); expect(fetchCount).toBe(1); }); // @gate enableFetchInstrumentation && enableCache it('can dedupe fetches in micro tasks', async () => { async function getData() { const r1 = await fetch('hello'); const t1 = await r1.text(); const r2 = await fetch('world'); const t2 = await r2.text(); return t1 + ' ' + t2; } function Component() { return use(getData()); } expect(await render(Component)).toMatchInlineSnapshot( `"GET hello [] GET world []"`, ); expect(fetchCount).toBe(2); }); // @gate enableFetchInstrumentation && enableCache it('can dedupe cache in micro tasks', async () => { const cached = cache(async () => { fetchCount++; return 'world'; }); async function getData() { const r1 = await fetch('hello'); const t1 = await r1.text(); const t2 = await cached(); return t1 + ' ' + t2; } function Component() { return use(getData()); } expect(await render(Component)).toMatchInlineSnapshot( `"GET hello [] world"`, ); expect(fetchCount).toBe(2); }); // @gate enableFetchInstrumentation && enableCache it('can dedupe fetches using Request and not', async () => { function Component() { const response = use(fetch('world')); const text = use(response.text()); const sameRequest = new Request('world', {method: 'get'}); const response2 = use(fetch(sameRequest)); const text2 = use(response2.text()); return text + ' ' + text2; } expect(await render(Component)).toMatchInlineSnapshot( `"GET world [] GET world []"`, ); expect(fetchCount).toBe(1); }); // @gate enableFetchInstrumentation && enableCache it('can dedupe fetches using URL and not', async () => { const url = 'http://example.com/'; function Component() { const response = use(fetch(url)); const text = use(response.text()); const response2 = use(fetch(new URL(url))); const text2 = use(response2.text()); return text + ' ' + text2; } expect(await render(Component)).toMatchInlineSnapshot( `"GET ${url} [] GET ${url} []"`, ); expect(fetchCount).toBe(1); }); it('can opt-out of deduping fetches inside of render with custom signal', async () => { const controller = new AbortController(); function useCustomHook() { return use( fetch('world', {signal: controller.signal}).then(response => response.text(), ), ); } function Component() { return useCustomHook() + ' ' + useCustomHook(); } expect(await render(Component)).toMatchInlineSnapshot( `"GET world [] GET world []"`, ); expect(fetchCount).not.toBe(1); }); it('opts out of deduping for POST requests', async () => { function useCustomHook() { return use( fetch('world', {method: 'POST'}).then(response => response.text()), ); } function Component() { return useCustomHook() + ' ' + useCustomHook(); } expect(await render(Component)).toMatchInlineSnapshot( `"POST world [] POST world []"`, ); expect(fetchCount).not.toBe(1); }); // @gate enableFetchInstrumentation && enableCache it('can dedupe fetches using same headers but not different', async () => { function Component() { const response = use(fetch('world', {headers: {a: 'A'}})); const text = use(response.text()); const sameRequest = new Request('world', { headers: new Headers({b: 'B'}), }); const response2 = use(fetch(sameRequest)); const text2 = use(response2.text()); return text + ' ' + text2; } expect(await render(Component)).toMatchInlineSnapshot( `"GET world [["a","A"]] GET world [["b","B"]]"`, ); expect(fetchCount).toBe(2); }); });
29.636792
89
0.624115
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 */ // This is a DevTools fork of ReactFiberComponentStack. // This fork enables DevTools to use the same "native" component stack format, // while still maintaining support for multiple renderer versions // (which use different values for ReactTypeOfWork). import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type {CurrentDispatcherRef, WorkTagMap} from './types'; import { describeBuiltInComponentFrame, describeFunctionComponentFrame, describeClassComponentFrame, } from './DevToolsComponentStackFrame'; export function describeFiber( workTagMap: WorkTagMap, workInProgress: Fiber, currentDispatcherRef: CurrentDispatcherRef, ): string { const { HostComponent, LazyComponent, SuspenseComponent, SuspenseListComponent, FunctionComponent, IndeterminateComponent, SimpleMemoComponent, ForwardRef, ClassComponent, } = workTagMap; const owner: null | Function = __DEV__ ? workInProgress._debugOwner ? workInProgress._debugOwner.type : null : null; switch (workInProgress.tag) { case HostComponent: return describeBuiltInComponentFrame(workInProgress.type, owner); case LazyComponent: return describeBuiltInComponentFrame('Lazy', owner); case SuspenseComponent: return describeBuiltInComponentFrame('Suspense', owner); case SuspenseListComponent: return describeBuiltInComponentFrame('SuspenseList', owner); case FunctionComponent: case IndeterminateComponent: case SimpleMemoComponent: return describeFunctionComponentFrame( workInProgress.type, owner, currentDispatcherRef, ); case ForwardRef: return describeFunctionComponentFrame( workInProgress.type.render, owner, currentDispatcherRef, ); case ClassComponent: return describeClassComponentFrame( workInProgress.type, owner, currentDispatcherRef, ); default: return ''; } } export function getStackByFiberInDevAndProd( workTagMap: WorkTagMap, workInProgress: Fiber, currentDispatcherRef: CurrentDispatcherRef, ): string { try { let info = ''; let node: Fiber = workInProgress; do { info += describeFiber(workTagMap, node, currentDispatcherRef); // $FlowFixMe[incompatible-type] we bail out when we get a null node = node.return; } while (node); return info; } catch (x) { return '\nError generating stack: ' + x.message + '\n' + x.stack; } }
26.887755
78
0.706808
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 * as React from 'react'; import styles from './LoadingAnimation.css'; type Props = { className?: string, }; export default function LoadingAnimation({className = ''}: Props): React.Node { return ( <svg xmlns="http://www.w3.org/2000/svg" className={`${styles.Icon} ${className}`} width="24" height="24" viewBox="0 0 100 100"> <path d="M0 0h100v100H0z" fill="none" /> <circle fill="currentColor" stroke="none" cx="20" cy="50" r="10"> <animate attributeName="opacity" dur="1s" values="0;1;0" repeatCount="indefinite" begin="0.1" /> </circle> <circle fill="currentColor" stroke="none" cx="50" cy="50" r="10"> <animate attributeName="opacity" dur="1s" values="0;1;0" repeatCount="indefinite" begin="0.2" /> </circle> <circle fill="currentColor" stroke="none" cx="80" cy="50" r="10"> <animate attributeName="opacity" dur="1s" values="0;1;0" repeatCount="indefinite" begin="0.3" /> </circle> </svg> ); }
23.910714
79
0.542324
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 */ 'use strict'; let React; let ReactNoop; let Scheduler; let act; let NormalPriority; let IdlePriority; let runWithPriority; let startTransition; let waitForAll; let waitForPaint; let assertLog; let waitFor; describe('ReactSchedulerIntegration', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; NormalPriority = Scheduler.unstable_NormalPriority; IdlePriority = Scheduler.unstable_IdlePriority; runWithPriority = Scheduler.unstable_runWithPriority; startTransition = React.startTransition; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitForPaint = InternalTestUtils.waitForPaint; assertLog = InternalTestUtils.assertLog; waitFor = InternalTestUtils.waitFor; }); // Note: This is based on a similar component we use in www. We can delete // once the extra div wrapper is no longer necessary. function LegacyHiddenDiv({children, mode}) { return ( <div hidden={mode === 'hidden'}> <React.unstable_LegacyHidden mode={mode === 'hidden' ? 'unstable-defer-without-hiding' : mode}> {children} </React.unstable_LegacyHidden> </div> ); } it('passive effects are called before Normal-pri scheduled in layout effects', async () => { const {useEffect, useLayoutEffect} = React; function Effects({step}) { useLayoutEffect(() => { Scheduler.log('Layout Effect'); Scheduler.unstable_scheduleCallback(NormalPriority, () => Scheduler.log('Scheduled Normal Callback from Layout Effect'), ); }); useEffect(() => { Scheduler.log('Passive Effect'); }); return null; } function CleanupEffect() { useLayoutEffect(() => () => { Scheduler.log('Cleanup Layout Effect'); Scheduler.unstable_scheduleCallback(NormalPriority, () => Scheduler.log('Scheduled Normal Callback from Cleanup Layout Effect'), ); }); return null; } await act(() => { ReactNoop.render(<CleanupEffect />); }); assertLog([]); await act(() => { ReactNoop.render(<Effects />); }); assertLog([ 'Cleanup Layout Effect', 'Layout Effect', 'Passive Effect', // These callbacks should be scheduled after the passive effects. 'Scheduled Normal Callback from Cleanup Layout Effect', 'Scheduled Normal Callback from Layout Effect', ]); }); it('requests a paint after committing', async () => { const scheduleCallback = Scheduler.unstable_scheduleCallback; const root = ReactNoop.createRoot(); root.render('Initial'); await waitForAll([]); expect(root).toMatchRenderedOutput('Initial'); scheduleCallback(NormalPriority, () => Scheduler.log('A')); scheduleCallback(NormalPriority, () => Scheduler.log('B')); scheduleCallback(NormalPriority, () => Scheduler.log('C')); // Schedule a React render. React will request a paint after committing it. React.startTransition(() => { root.render('Update'); }); // Perform just a little bit of work. By now, the React task will have // already been scheduled, behind A, B, and C. await waitFor(['A']); // Schedule some additional tasks. These won't fire until after the React // update has finished. scheduleCallback(NormalPriority, () => Scheduler.log('D')); scheduleCallback(NormalPriority, () => Scheduler.log('E')); // Flush everything up to the next paint. Should yield after the // React commit. await waitForPaint(['B', 'C']); expect(root).toMatchRenderedOutput('Update'); // Now flush the rest of the work. await waitForAll(['D', 'E']); }); // @gate www it('idle updates are not blocked by offscreen work', async () => { function Text({text}) { Scheduler.log(text); return text; } function App({label}) { return ( <> <Text text={`Visible: ` + label} /> <LegacyHiddenDiv mode="hidden"> <Text text={`Hidden: ` + label} /> </LegacyHiddenDiv> </> ); } const root = ReactNoop.createRoot(); await act(async () => { root.render(<App label="A" />); // Commit the visible content await waitForPaint(['Visible: A']); expect(root).toMatchRenderedOutput( <> Visible: A <div hidden={true} /> </>, ); // Before the hidden content has a chance to render, schedule an // idle update runWithPriority(IdlePriority, () => { root.render(<App label="B" />); }); // The next commit should only include the visible content await waitForPaint(['Visible: B']); expect(root).toMatchRenderedOutput( <> Visible: B <div hidden={true} /> </>, ); }); // The hidden content commits later assertLog(['Hidden: B']); expect(root).toMatchRenderedOutput( <> Visible: B<div hidden={true}>Hidden: B</div> </>, ); }); }); describe( 'regression test: does not infinite loop if `shouldYield` returns ' + 'true after a partial tree expires', () => { let logDuringShouldYield = false; beforeEach(() => { jest.resetModules(); jest.mock('scheduler', () => { const actual = jest.requireActual('scheduler/unstable_mock'); return { ...actual, unstable_shouldYield() { if (logDuringShouldYield) { actual.log('shouldYield'); } return actual.unstable_shouldYield(); }, }; }); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); startTransition = React.startTransition; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitForPaint = InternalTestUtils.waitForPaint; assertLog = InternalTestUtils.assertLog; waitFor = InternalTestUtils.waitFor; act = InternalTestUtils.act; }); afterEach(() => { jest.mock('scheduler', () => jest.requireActual('scheduler/unstable_mock'), ); }); it('using public APIs to trigger real world scenario', async () => { // This test reproduces a case where React's Scheduler task timed out but // the `shouldYield` method returned true. The bug was that React fell // into an infinite loop, because it would enter the work loop then // immediately yield back to Scheduler. // // (The next test in this suite covers the same case. The difference is // that this test only uses public APIs, whereas the next test mocks // `shouldYield` to check when it is called.) function Text({text}) { return text; } function App({step}) { return ( <> <Text text="A" /> <TriggerErstwhileSchedulerBug /> <Text text="B" /> <TriggerErstwhileSchedulerBug /> <Text text="C" /> </> ); } function TriggerErstwhileSchedulerBug() { // This triggers a once-upon-a-time bug in Scheduler that caused // `shouldYield` to return true even though the current task expired. Scheduler.unstable_advanceTime(10000); Scheduler.unstable_requestPaint(); return null; } await act(async () => { ReactNoop.render(<App />); await waitForPaint([]); await waitForPaint([]); }); }); it('mock Scheduler module to check if `shouldYield` is called', async () => { // This test reproduces a bug where React's Scheduler task timed out but // the `shouldYield` method returned true. Usually we try not to mock // internal methods, but I've made an exception here since the point is // specifically to test that React is resilient to the behavior of a // Scheduler API. That being said, feel free to rewrite or delete this // test if/when the API changes. function Text({text}) { Scheduler.log(text); return text; } function App({step}) { return ( <> <Text text="A" /> <Text text="B" /> <Text text="C" /> </> ); } await act(async () => { // Partially render the tree, then yield startTransition(() => { ReactNoop.render(<App />); }); await waitFor(['A']); // Start logging whenever shouldYield is called logDuringShouldYield = true; // Let's call it once to confirm the mock actually works await waitFor(['shouldYield']); // Expire the task Scheduler.unstable_advanceTime(10000); // Scheduling a new update is a trick to force the expiration to kick // in. We don't check if a update has been starved at the beginning of // working on it, since there's no point — we're already working on it. // We only check before yielding to the main thread (to avoid starvation // by other main thread work) or when receiving an update (to avoid // starvation by incoming updates). startTransition(() => { ReactNoop.render(<App />); }); // Because the render expired, React should finish the tree without // consulting `shouldYield` again await waitFor(['B', 'C']); }); }); }, ); describe('`act` bypasses Scheduler methods completely,', () => { let infiniteLoopGuard; beforeEach(() => { jest.resetModules(); infiniteLoopGuard = 0; jest.mock('scheduler', () => { const actual = jest.requireActual('scheduler/unstable_mock'); return { ...actual, unstable_shouldYield() { // This simulates a bug report where `shouldYield` returns true in a // unit testing environment. Because `act` will keep working until // there's no more work left, it would fall into an infinite loop. // The fix is that when performing work inside `act`, we should bypass // `shouldYield` completely, because we can't trust it to be correct. if (infiniteLoopGuard++ > 100) { throw new Error('Detected an infinite loop'); } return true; }, }; }); React = require('react'); ReactNoop = require('react-noop-renderer'); startTransition = React.startTransition; }); afterEach(() => { jest.mock('scheduler', () => jest.requireActual('scheduler/unstable_mock')); }); // @gate __DEV__ it('inside `act`, does not call `shouldYield`, even during a concurrent render', async () => { function App() { return ( <> <div>A</div> <div>B</div> <div>C</div> </> ); } const root = ReactNoop.createRoot(); const publicAct = React.unstable_act; const prevIsReactActEnvironment = global.IS_REACT_ACT_ENVIRONMENT; try { global.IS_REACT_ACT_ENVIRONMENT = true; await publicAct(async () => { startTransition(() => root.render(<App />)); }); } finally { global.IS_REACT_ACT_ENVIRONMENT = prevIsReactActEnvironment; } expect(root).toMatchRenderedOutput( <> <div>A</div> <div>B</div> <div>C</div> </>, ); }); });
29.377551
96
0.596288
PenetrationTestingScripts
/* global chrome */ import {createElement} from 'react'; import {flushSync} from 'react-dom'; import {createRoot} from 'react-dom/client'; import Bridge from 'react-devtools-shared/src/bridge'; import Store from 'react-devtools-shared/src/devtools/store'; import {getBrowserTheme} from '../utils'; import { localStorageGetItem, localStorageSetItem, } from 'react-devtools-shared/src/storage'; import DevTools from 'react-devtools-shared/src/devtools/views/DevTools'; import { LOCAL_STORAGE_SUPPORTS_PROFILING_KEY, LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY, } from 'react-devtools-shared/src/constants'; import {logEvent} from 'react-devtools-shared/src/Logger'; import { setBrowserSelectionFromReact, setReactSelectionFromBrowser, } from './elementSelection'; import {startReactPolling} from './reactPolling'; import cloneStyleTags from './cloneStyleTags'; import fetchFileWithCaching from './fetchFileWithCaching'; import injectBackendManager from './injectBackendManager'; import syncSavedPreferences from './syncSavedPreferences'; import registerEventsLogger from './registerEventsLogger'; import getProfilingFlags from './getProfilingFlags'; import debounce from './debounce'; import './requestAnimationFramePolyfill'; function createBridge() { bridge = new Bridge({ listen(fn) { const bridgeListener = message => fn(message); // Store the reference so that we unsubscribe from the same object. const portOnMessage = port.onMessage; portOnMessage.addListener(bridgeListener); lastSubscribedBridgeListener = bridgeListener; return () => { port?.onMessage.removeListener(bridgeListener); lastSubscribedBridgeListener = null; }; }, send(event: string, payload: any, transferable?: Array<any>) { port?.postMessage({event, payload}, transferable); }, }); bridge.addListener('reloadAppForProfiling', () => { localStorageSetItem(LOCAL_STORAGE_SUPPORTS_PROFILING_KEY, 'true'); chrome.devtools.inspectedWindow.eval('window.location.reload();'); }); bridge.addListener( 'syncSelectionToNativeElementsPanel', setBrowserSelectionFromReact, ); bridge.addListener('extensionBackendInitialized', () => { // Initialize the renderer's trace-updates setting. // This handles the case of navigating to a new page after the DevTools have already been shown. bridge.send( 'setTraceUpdatesEnabled', localStorageGetItem(LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY) === 'true', ); }); const onBrowserElementSelectionChanged = () => setReactSelectionFromBrowser(bridge); const onBridgeShutdown = () => { chrome.devtools.panels.elements.onSelectionChanged.removeListener( onBrowserElementSelectionChanged, ); }; bridge.addListener('shutdown', onBridgeShutdown); chrome.devtools.panels.elements.onSelectionChanged.addListener( onBrowserElementSelectionChanged, ); } function createBridgeAndStore() { createBridge(); const {isProfiling, supportsProfiling} = getProfilingFlags(); store = new Store(bridge, { isProfiling, supportsReloadAndProfile: __IS_CHROME__ || __IS_EDGE__, supportsProfiling, // At this time, the timeline can only parse Chrome performance profiles. supportsTimeline: __IS_CHROME__, supportsTraceUpdates: true, }); if (!isProfiling) { // We previously stored this in performCleanup function store.profilerStore.profilingData = profilingData; } // Initialize the backend only once the Store has been initialized. // Otherwise, the Store may miss important initial tree op codes. injectBackendManager(chrome.devtools.inspectedWindow.tabId); const viewAttributeSourceFunction = (id, path) => { const rendererID = store.getRendererIDForElement(id); if (rendererID != null) { // Ask the renderer interface to find the specified attribute, // and store it as a global variable on the window. bridge.send('viewAttributeSource', {id, path, rendererID}); setTimeout(() => { // Ask Chrome to display the location of the attribute, // assuming the renderer found a match. chrome.devtools.inspectedWindow.eval(` if (window.$attribute != null) { inspect(window.$attribute); } `); }, 100); } }; const viewElementSourceFunction = id => { const rendererID = store.getRendererIDForElement(id); if (rendererID != null) { // Ask the renderer interface to determine the component function, // and store it as a global variable on the window bridge.send('viewElementSource', {id, rendererID}); setTimeout(() => { // Ask Chrome to display the location of the component function, // or a render method if it is a Class (ideally Class instance, not type) // assuming the renderer found one. chrome.devtools.inspectedWindow.eval(` if (window.$type != null) { if ( window.$type && window.$type.prototype && window.$type.prototype.isReactComponent ) { // inspect Component.render, not constructor inspect(window.$type.prototype.render); } else { // inspect Functional Component inspect(window.$type); } } `); }, 100); } }; // TODO (Webpack 5) Hopefully we can remove this prop after the Webpack 5 migration. const hookNamesModuleLoaderFunction = () => import( /* webpackChunkName: 'parseHookNames' */ 'react-devtools-shared/src/hooks/parseHookNames' ); root = createRoot(document.createElement('div')); render = (overrideTab = mostRecentOverrideTab) => { mostRecentOverrideTab = overrideTab; root.render( createElement(DevTools, { bridge, browserTheme: getBrowserTheme(), componentsPortalContainer, enabledInspectedElementContextMenu: true, fetchFileWithCaching, hookNamesModuleLoaderFunction, overrideTab, profilerPortalContainer, showTabBar: false, store, warnIfUnsupportedVersionDetected: true, viewAttributeSourceFunction, viewElementSourceFunction, viewUrlSourceFunction, }), ); }; } const viewUrlSourceFunction = (url, line, col) => { chrome.devtools.panels.openResource(url, line, col); }; function ensureInitialHTMLIsCleared(container) { if (container._hasInitialHTMLBeenCleared) { return; } container.innerHTML = ''; container._hasInitialHTMLBeenCleared = true; } function createComponentsPanel() { if (componentsPortalContainer) { // Panel is created and user opened it at least once ensureInitialHTMLIsCleared(componentsPortalContainer); render('components'); return; } if (componentsPanel) { // Panel is created, but wasn't opened yet, so no document is present for it return; } chrome.devtools.panels.create( __IS_CHROME__ || __IS_EDGE__ ? '⚛️ Components' : 'Components', __IS_EDGE__ ? 'icons/production.svg' : '', 'panel.html', createdPanel => { componentsPanel = createdPanel; createdPanel.onShown.addListener(portal => { componentsPortalContainer = portal.container; if (componentsPortalContainer != null && render) { ensureInitialHTMLIsCleared(componentsPortalContainer); render('components'); portal.injectStyles(cloneStyleTags); logEvent({event_name: 'selected-components-tab'}); } }); // TODO: we should listen to createdPanel.onHidden to unmount some listeners // and potentially stop highlighting }, ); } function createProfilerPanel() { if (profilerPortalContainer) { // Panel is created and user opened it at least once ensureInitialHTMLIsCleared(profilerPortalContainer); render('profiler'); return; } if (profilerPanel) { // Panel is created, but wasn't opened yet, so no document is present for it return; } chrome.devtools.panels.create( __IS_CHROME__ || __IS_EDGE__ ? '⚛️ Profiler' : 'Profiler', __IS_EDGE__ ? 'icons/production.svg' : '', 'panel.html', createdPanel => { profilerPanel = createdPanel; createdPanel.onShown.addListener(portal => { profilerPortalContainer = portal.container; if (profilerPortalContainer != null && render) { ensureInitialHTMLIsCleared(profilerPortalContainer); render('profiler'); portal.injectStyles(cloneStyleTags); logEvent({event_name: 'selected-profiler-tab'}); } }); }, ); } function performInTabNavigationCleanup() { // Potentially, if react hasn't loaded yet and user performs in-tab navigation clearReactPollingInstance(); if (store !== null) { // Store profiling data, so it can be used later profilingData = store.profilerStore.profilingData; } // If panels were already created, and we have already mounted React root to display // tabs (Components or Profiler), we should unmount root first and render them again if ((componentsPortalContainer || profilerPortalContainer) && root) { // It's easiest to recreate the DevTools panel (to clean up potential stale state). // We can revisit this in the future as a small optimization. // This should also emit bridge.shutdown, but only if this root was mounted flushSync(() => root.unmount()); } else { // In case Browser DevTools were opened, but user never pressed on extension panels // They were never mounted and there is nothing to unmount, but we need to emit shutdown event // because bridge was already created bridge?.shutdown(); } // Do not nullify componentsPanelPortal and profilerPanelPortal on purpose, // They are not recreated when user does in-tab navigation, and they can only be accessed via // callback in onShown listener, which is called only when panel has been shown // This event won't be emitted again after in-tab navigation, if DevTools panel keeps being opened // Do not clean mostRecentOverrideTab on purpose, so we remember last opened // React DevTools tab, when user does in-tab navigation store = null; bridge = null; render = null; root = null; } function performFullCleanup() { // Potentially, if react hasn't loaded yet and user closed the browser DevTools clearReactPollingInstance(); if ((componentsPortalContainer || profilerPortalContainer) && root) { // This should also emit bridge.shutdown, but only if this root was mounted flushSync(() => root.unmount()); } else { bridge?.shutdown(); } componentsPortalContainer = null; profilerPortalContainer = null; root = null; mostRecentOverrideTab = null; store = null; bridge = null; render = null; port?.disconnect(); port = null; } function connectExtensionPort() { if (port) { throw new Error('DevTools port was already connected'); } const tabId = chrome.devtools.inspectedWindow.tabId; port = chrome.runtime.connect({ name: String(tabId), }); // If DevTools port was reconnected and Bridge was already created // We should subscribe bridge to this port events // This could happen if service worker dies and all ports are disconnected, // but later user continues the session and Chrome reconnects all ports // Bridge object is still in-memory, though if (lastSubscribedBridgeListener) { port.onMessage.addListener(lastSubscribedBridgeListener); } // This port may be disconnected by Chrome at some point, this callback // will be executed only if this port was disconnected from the other end // so, when we call `port.disconnect()` from this script, // this should not trigger this callback and port reconnection port.onDisconnect.addListener(() => { port = null; connectExtensionPort(); }); } function mountReactDevTools() { reactPollingInstance = null; registerEventsLogger(); createBridgeAndStore(); setReactSelectionFromBrowser(bridge); createComponentsPanel(); createProfilerPanel(); } let reactPollingInstance = null; function clearReactPollingInstance() { reactPollingInstance?.abort(); reactPollingInstance = null; } function showNoReactDisclaimer() { if (componentsPortalContainer) { componentsPortalContainer.innerHTML = '<h1 class="no-react-disclaimer">Looks like this page doesn\'t have React, or it hasn\'t been loaded yet.</h1>'; delete componentsPortalContainer._hasInitialHTMLBeenCleared; } if (profilerPortalContainer) { profilerPortalContainer.innerHTML = '<h1 class="no-react-disclaimer">Looks like this page doesn\'t have React, or it hasn\'t been loaded yet.</h1>'; delete profilerPortalContainer._hasInitialHTMLBeenCleared; } } function mountReactDevToolsWhenReactHasLoaded() { reactPollingInstance = startReactPolling( mountReactDevTools, 5, // ~5 seconds showNoReactDisclaimer, ); } let bridge = null; let lastSubscribedBridgeListener = null; let store = null; let profilingData = null; let componentsPanel = null; let profilerPanel = null; let componentsPortalContainer = null; let profilerPortalContainer = null; let mostRecentOverrideTab = null; let render = null; let root = null; let port = null; // Re-initialize saved filters on navigation, // since global values stored on window get reset in this case. chrome.devtools.network.onNavigated.addListener(syncSavedPreferences); // In case when multiple navigation events emitted in a short period of time // This debounced callback primarily used to avoid mounting React DevTools multiple times, which results // into subscribing to the same events from Bridge and window multiple times // In this case, we will handle `operations` event twice or more and user will see // `Cannot add node "1" because a node with that id is already in the Store.` const debouncedOnNavigatedListener = debounce(() => { performInTabNavigationCleanup(); mountReactDevToolsWhenReactHasLoaded(); }, 500); // Cleanup previous page state and remount everything chrome.devtools.network.onNavigated.addListener(debouncedOnNavigatedListener); // Should be emitted when browser DevTools are closed if (__IS_FIREFOX__) { // For some reason Firefox doesn't emit onBeforeUnload event window.addEventListener('unload', performFullCleanup); } else { window.addEventListener('beforeunload', performFullCleanup); } connectExtensionPort(); syncSavedPreferences(); mountReactDevToolsWhenReactHasLoaded();
31.141921
118
0.698302
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'; import {insertNodesAndExecuteScripts} from '../test-utils/FizzTestUtils'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; let act; let container; let React; let ReactDOMServer; let ReactDOMClient; let useFormStatus; let useOptimistic; let useFormState; describe('ReactDOMFizzForm', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOMServer = require('react-dom/server.browser'); ReactDOMClient = require('react-dom/client'); useFormStatus = require('react-dom').useFormStatus; useFormState = require('react-dom').useFormState; useOptimistic = require('react').useOptimistic; act = require('internal-test-utils').act; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); }); 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)) { 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('should allow passing a function to form action during SSR', async () => { const ref = React.createRef(); let foo; function action(formData) { foo = formData.get('foo'); } function App() { return ( <form action={action} ref={ref}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); submit(ref.current); expect(foo).toBe('bar'); }); // @gate enableFormActions it('should allow passing a function to an input/button formAction', async () => { const inputRef = React.createRef(); const buttonRef = React.createRef(); let rootActionCalled = false; let savedTitle = null; let deletedTitle = null; function action(formData) { rootActionCalled = true; } function saveItem(formData) { savedTitle = formData.get('title'); } function deleteItem(formData) { deletedTitle = formData.get('title'); } function App() { return ( <form action={action}> <input type="text" name="title" defaultValue="Hello" /> <input type="submit" formAction={saveItem} value="Save" ref={inputRef} /> <button formAction={deleteItem} ref={buttonRef}> Delete </button> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(savedTitle).toBe(null); expect(deletedTitle).toBe(null); submit(inputRef.current); expect(savedTitle).toBe('Hello'); expect(deletedTitle).toBe(null); savedTitle = null; submit(buttonRef.current); expect(savedTitle).toBe(null); expect(deletedTitle).toBe('Hello'); deletedTitle = null; expect(rootActionCalled).toBe(false); }); // @gate enableFormActions || !__DEV__ it('should warn when passing a function action during SSR and string during hydration', async () => { function action(formData) {} function App({isClient}) { return ( <form action={isClient ? 'action' : action}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); await expect(async () => { await act(async () => { ReactDOMClient.hydrateRoot(container, <App isClient={true} />); }); }).toErrorDev( 'Prop `action` did not match. Server: "function" Client: "action"', ); }); // @gate enableFormActions || !__DEV__ it('should ideally warn when passing a string during SSR and function during hydration', async () => { function action(formData) {} function App({isClient}) { return ( <form action={isClient ? action : 'action'}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); // This should ideally warn because only the client provides a function that doesn't line up. await act(async () => { ReactDOMClient.hydrateRoot(container, <App isClient={true} />); }); }); // @gate enableFormActions || !__DEV__ it('should reset form fields after you update away from hydrated function', async () => { const formRef = React.createRef(); const inputRef = React.createRef(); const buttonRef = React.createRef(); function action(formData) {} function App({isUpdate}) { return ( <form action={isUpdate ? 'action' : action} ref={formRef} method={isUpdate ? 'POST' : null}> <input type="submit" formAction={isUpdate ? 'action' : action} ref={inputRef} formTarget={isUpdate ? 'elsewhere' : null} /> <button formAction={isUpdate ? 'action' : action} ref={buttonRef} formEncType={isUpdate ? 'multipart/form-data' : null} /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); let root; await act(async () => { root = ReactDOMClient.hydrateRoot(container, <App />); }); await act(async () => { root.render(<App isUpdate={true} />); }); expect(formRef.current.getAttribute('action')).toBe('action'); expect(formRef.current.hasAttribute('encType')).toBe(false); expect(formRef.current.getAttribute('method')).toBe('POST'); expect(formRef.current.hasAttribute('target')).toBe(false); expect(inputRef.current.getAttribute('formAction')).toBe('action'); expect(inputRef.current.hasAttribute('name')).toBe(false); expect(inputRef.current.hasAttribute('formEncType')).toBe(false); expect(inputRef.current.hasAttribute('formMethod')).toBe(false); expect(inputRef.current.getAttribute('formTarget')).toBe('elsewhere'); expect(buttonRef.current.getAttribute('formAction')).toBe('action'); expect(buttonRef.current.hasAttribute('name')).toBe(false); expect(buttonRef.current.getAttribute('formEncType')).toBe( 'multipart/form-data', ); expect(buttonRef.current.hasAttribute('formMethod')).toBe(false); expect(buttonRef.current.hasAttribute('formTarget')).toBe(false); }); // @gate enableFormActions || !__DEV__ it('should reset form fields after you remove a hydrated function', async () => { const formRef = React.createRef(); const inputRef = React.createRef(); const buttonRef = React.createRef(); function action(formData) {} function App({isUpdate}) { return ( <form action={isUpdate ? undefined : action} ref={formRef}> <input type="submit" formAction={isUpdate ? undefined : action} ref={inputRef} /> <button formAction={isUpdate ? undefined : action} ref={buttonRef} /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); let root; await act(async () => { root = ReactDOMClient.hydrateRoot(container, <App />); }); await act(async () => { root.render(<App isUpdate={true} />); }); expect(formRef.current.hasAttribute('action')).toBe(false); expect(formRef.current.hasAttribute('encType')).toBe(false); expect(formRef.current.hasAttribute('method')).toBe(false); expect(formRef.current.hasAttribute('target')).toBe(false); expect(inputRef.current.hasAttribute('formAction')).toBe(false); expect(inputRef.current.hasAttribute('name')).toBe(false); expect(inputRef.current.hasAttribute('formEncType')).toBe(false); expect(inputRef.current.hasAttribute('formMethod')).toBe(false); expect(inputRef.current.hasAttribute('formTarget')).toBe(false); expect(buttonRef.current.hasAttribute('formAction')).toBe(false); expect(buttonRef.current.hasAttribute('name')).toBe(false); expect(buttonRef.current.hasAttribute('formEncType')).toBe(false); expect(buttonRef.current.hasAttribute('formMethod')).toBe(false); expect(buttonRef.current.hasAttribute('formTarget')).toBe(false); }); // @gate enableFormActions || !__DEV__ it('should restore the form fields even if they were incorrectly set', async () => { const formRef = React.createRef(); const inputRef = React.createRef(); const buttonRef = React.createRef(); function action(formData) {} function App({isUpdate}) { return ( <form action={isUpdate ? 'action' : action} ref={formRef} method="DELETE"> <input type="submit" formAction={isUpdate ? 'action' : action} ref={inputRef} formTarget="elsewhere" /> <button formAction={isUpdate ? 'action' : action} ref={buttonRef} formEncType="text/plain" /> </form> ); } // Specifying the extra form fields are a DEV error, but we expect it // to eventually still be patched up after an update. await expect(async () => { const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); }).toErrorDev([ 'Cannot specify a encType or method for a form that specifies a function as the action.', 'Cannot specify a formTarget for a button that specifies a function as a formAction.', ]); let root; await expect(async () => { await act(async () => { root = ReactDOMClient.hydrateRoot(container, <App />); }); }).toErrorDev(['Prop `formTarget` did not match.']); await act(async () => { root.render(<App isUpdate={true} />); }); expect(formRef.current.getAttribute('action')).toBe('action'); expect(formRef.current.hasAttribute('encType')).toBe(false); expect(formRef.current.getAttribute('method')).toBe('DELETE'); expect(formRef.current.hasAttribute('target')).toBe(false); expect(inputRef.current.getAttribute('formAction')).toBe('action'); expect(inputRef.current.hasAttribute('name')).toBe(false); expect(inputRef.current.hasAttribute('formEncType')).toBe(false); expect(inputRef.current.hasAttribute('formMethod')).toBe(false); expect(inputRef.current.getAttribute('formTarget')).toBe('elsewhere'); expect(buttonRef.current.getAttribute('formAction')).toBe('action'); expect(buttonRef.current.hasAttribute('name')).toBe(false); expect(buttonRef.current.getAttribute('formEncType')).toBe('text/plain'); expect(buttonRef.current.hasAttribute('formMethod')).toBe(false); expect(buttonRef.current.hasAttribute('formTarget')).toBe(false); }); // @gate enableFormActions // @gate enableAsyncActions it('useFormStatus is not pending during server render', async () => { function App() { const {pending} = useFormStatus(); return 'Pending: ' + pending; } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); expect(container.textContent).toBe('Pending: false'); await act(() => ReactDOMClient.hydrateRoot(container, <App />)); expect(container.textContent).toBe('Pending: false'); }); // @gate enableFormActions it('should replay a form action after hydration', async () => { let foo; function action(formData) { foo = formData.get('foo'); } function App() { return ( <form action={action}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); // Dispatch an event before hydration submit(container.getElementsByTagName('form')[0]); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); // It should've now been replayed expect(foo).toBe('bar'); }); // @gate enableFormActions it('should replay input/button formAction', async () => { let rootActionCalled = false; let savedTitle = null; let deletedTitle = null; function action(formData) { rootActionCalled = true; } function saveItem(formData) { savedTitle = formData.get('title'); } function deleteItem(formData) { deletedTitle = formData.get('title'); } function App() { return ( <form action={action}> <input type="text" name="title" defaultValue="Hello" /> <input type="submit" formAction={saveItem} value="Save" /> <button formAction={deleteItem}>Delete</button> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); submit(container.getElementsByTagName('input')[1]); submit(container.getElementsByTagName('button')[0]); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(savedTitle).toBe('Hello'); expect(deletedTitle).toBe('Hello'); expect(rootActionCalled).toBe(false); }); // @gate enableAsyncActions it('useOptimistic returns passthrough value', async () => { function App() { const [optimisticState] = useOptimistic('hi'); return optimisticState; } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); expect(container.textContent).toBe('hi'); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container.textContent).toBe('hi'); }); // @gate enableFormActions // @gate enableAsyncActions it('useFormState returns initial state', async () => { async function action(state) { return state; } function App() { const [state] = useFormState(action, 0); return state; } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); expect(container.textContent).toBe('0'); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(container.textContent).toBe('0'); }); // @gate enableFormActions it('can provide a custom action on the server for actions', async () => { const ref = React.createRef(); let foo; function action(formData) { foo = formData.get('foo'); } action.$$FORM_ACTION = function (identifierPrefix) { const extraFields = new FormData(); extraFields.append(identifierPrefix + 'hello', 'world'); return { action: this.name, name: identifierPrefix, method: 'POST', encType: 'multipart/form-data', target: 'self', data: extraFields, }; }; function App() { return ( <form action={action} ref={ref} method={null}> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); const form = container.firstChild; expect(form.getAttribute('action')).toBe('action'); expect(form.getAttribute('method')).toBe('POST'); expect(form.getAttribute('enctype')).toBe('multipart/form-data'); expect(form.getAttribute('target')).toBe('self'); const formActionName = form.firstChild.getAttribute('name'); expect( container .querySelector('input[name="' + formActionName + 'hello"]') .getAttribute('value'), ).toBe('world'); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); submit(ref.current); expect(foo).toBe('bar'); }); // @gate enableFormActions it('can provide a custom action on buttons the server for actions', async () => { const hiddenRef = React.createRef(); const inputRef = React.createRef(); const buttonRef = React.createRef(); let foo; function action(formData) { foo = formData.get('foo'); } action.$$FORM_ACTION = function (identifierPrefix) { const extraFields = new FormData(); extraFields.append(identifierPrefix + 'hello', 'world'); return { action: this.name, name: identifierPrefix, method: 'POST', encType: 'multipart/form-data', target: 'self', data: extraFields, }; }; function App() { return ( <form> <input type="hidden" name="foo" value="bar" ref={hiddenRef} /> <input type="submit" formAction={action} method={null} ref={inputRef} /> <button formAction={action} ref={buttonRef} target={null} /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); const input = container.getElementsByTagName('input')[1]; const button = container.getElementsByTagName('button')[0]; expect(input.getAttribute('formaction')).toBe('action'); expect(input.getAttribute('formmethod')).toBe('POST'); expect(input.getAttribute('formenctype')).toBe('multipart/form-data'); expect(input.getAttribute('formtarget')).toBe('self'); expect(button.getAttribute('formaction')).toBe('action'); expect(button.getAttribute('formmethod')).toBe('POST'); expect(button.getAttribute('formenctype')).toBe('multipart/form-data'); expect(button.getAttribute('formtarget')).toBe('self'); const inputName = input.getAttribute('name'); const buttonName = button.getAttribute('name'); expect( container .querySelector('input[name="' + inputName + 'hello"]') .getAttribute('value'), ).toBe('world'); expect( container .querySelector('input[name="' + buttonName + 'hello"]') .getAttribute('value'), ).toBe('world'); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(hiddenRef.current.name).toBe('foo'); submit(inputRef.current); expect(foo).toBe('bar'); foo = null; submit(buttonRef.current); expect(foo).toBe('bar'); }); // @gate enableFormActions it('can hydrate hidden fields in the beginning of a form', async () => { const hiddenRef = React.createRef(); let invoked = false; function action(formData) { invoked = true; } action.$$FORM_ACTION = function (identifierPrefix) { const extraFields = new FormData(); extraFields.append(identifierPrefix + 'hello', 'world'); return { action: '', name: identifierPrefix, method: 'POST', encType: 'multipart/form-data', data: extraFields, }; }; function App() { return ( <form action={action}> <input type="hidden" name="bar" defaultValue="baz" ref={hiddenRef} /> <input type="text" name="foo" defaultValue="bar" /> </form> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); const barField = container.querySelector('[name=bar]'); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(hiddenRef.current).toBe(barField); expect(hiddenRef.current.name).toBe('bar'); expect(hiddenRef.current.value).toBe('baz'); expect(container.querySelectorAll('[name=bar]').length).toBe(1); submit(hiddenRef.current.form); expect(invoked).toBe(true); }); });
30.324484
104
0.627301
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. */ 'use strict'; var Circle = require('react-art/Circle'); var React = require('react'); var ReactART = require('react-art'); var Group = ReactART.Group; var Shape = ReactART.Shape; var Surface = ReactART.Surface; var Transform = ReactART.Transform; var MOUSE_UP_DRAG = 0.978; var MOUSE_DOWN_DRAG = 0.9; var MAX_VEL = 11; var CLICK_ACCEL = 3; var BASE_VEL = 0.15; /** * An animated SVG component. */ class VectorWidget extends React.Component { /** * Initialize state members. */ state = {degrees: 0, velocity: 0, drag: MOUSE_UP_DRAG}; /** * When the component is mounted into the document - this is similar to a * constructor, but invoked when the instance is actually mounted into the * document. Here, we'll just set up an animation loop that invokes our * method. Binding of `this.onTick` is not needed because all React methods * are automatically bound before being mounted. */ componentDidMount() { this._interval = window.setInterval(this.onTick, 20); } componentWillUnmount() { window.clearInterval(this._interval); } onTick = () => { var nextDegrees = this.state.degrees + BASE_VEL + this.state.velocity; var nextVelocity = this.state.velocity * this.state.drag; this.setState({degrees: nextDegrees, velocity: nextVelocity}); }; /** * When mousing down, we increase the friction down the velocity. */ handleMouseDown = () => { this.setState({drag: MOUSE_DOWN_DRAG}); }; /** * Cause the rotation to "spring". */ handleMouseUp = () => { var nextVelocity = Math.min(this.state.velocity + CLICK_ACCEL, MAX_VEL); this.setState({velocity: nextVelocity, drag: MOUSE_UP_DRAG}); }; /** * This is the "main" method for any component. The React API allows you to * describe the structure of your UI component at *any* point in time. */ render() { return ( <Surface width={700} height={700} style={{cursor: 'pointer'}}> {this.renderGraphic(this.state.degrees)} </Surface> ); } /** * Better SVG support for React coming soon. */ renderGraphic = rotation => { return ( <Group onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}> <Group x={210} y={135}> <Shape fill="rgba(0,0,0,0.1)" d={BORDER_PATH} /> <Shape fill="#7BC7BA" d={BG_PATH} /> <Shape fill="#DCDCDC" d={BAR_PATH} /> <Shape fill="#D97B76" d={RED_DOT_PATH} /> <Shape fill="#DBBB79" d={YELLOW_DOT_PATH} /> <Shape fill="#A6BD8A" d={GREEN_DOT_PATH} /> <Group x={55} y={29}> <Group rotation={rotation} originX={84} originY={89}> <Group x={84} y={89}> <Circle fill="#FFFFFF" radius={16} /> </Group> <Group> <Shape d={RING_ONE_PATH} stroke="#FFFFFF" strokeWidth={8} /> <Shape d={RING_TWO_PATH} transform={RING_TWO_ROTATE} stroke="#FFFFFF" strokeWidth={8} /> <Shape d={RING_THREE_PATH} transform={RING_THREE_ROTATE} stroke="#FFFFFF" strokeWidth={8} /> </Group> </Group> </Group> </Group> </Group> ); }; } var BORDER_PATH = 'M3.00191459,4 C1.34400294,4 0,5.34785514 0,7.00550479 L0,220.994495 C0,222.65439 1.34239483,224 3.00191459,224 L276.998085,224 C278.655997,224 280,222.652145 280,220.994495 L280,7.00550479 C280,5.34561033 278.657605,4 276.998085,4 L3.00191459,4 Z M3.00191459,4'; var BG_PATH = 'M3.00191459,1 C1.34400294,1 0,2.34785514 0,4.00550479 L0,217.994495 C0,219.65439 1.34239483,221 3.00191459,221 L276.998085,221 C278.655997,221 280,219.652145 280,217.994495 L280,4.00550479 C280,2.34561033 278.657605,1 276.998085,1 L3.00191459,1 Z M3.00191459,1'; var BAR_PATH = 'M3.00191459,0 C1.34400294,0 0,1.34559019 0,3.00878799 L0,21 C0,21 0,21 0,21 L280,21 C280,21 280,21 280,21 L280,3.00878799 C280,1.34708027 278.657605,0 276.998085,0 L3.00191459,0 Z M3.00191459,0'; var RED_DOT_PATH = 'M12.5,17 C16.0898511,17 19,14.0898511 19,10.5 C19,6.91014895 16.0898511,4 12.5,4 C8.91014895,4 6,6.91014895 6,10.5 C6,14.0898511 8.91014895,17 12.5,17 Z M12.5,17'; var YELLOW_DOT_PATH = 'M31.5,17 C35.0898511,17 38,14.0898511 38,10.5 C38,6.91014895 35.0898511,4 31.5,4 C27.9101489,4 25,6.91014895 25,10.5 C25,14.0898511 27.9101489,17 31.5,17 Z M31.5,17'; var GREEN_DOT_PATH = 'M50.5,17 C54.0898511,17 57,14.0898511 57,10.5 C57,6.91014895 54.0898511,4 50.5,4 C46.9101489,4 44,6.91014895 44,10.5 C44,14.0898511 46.9101489,17 50.5,17 Z M50.5,17'; var RING_ONE_PATH = 'M84,121 C130.391921,121 168,106.673113 168,89 C168,71.3268871 130.391921,57 84,57 C37.6080787,57 0,71.3268871 0,89 C0,106.673113 37.6080787,121 84,121 Z M84,121'; var RING_TWO_PATH = 'M84,121 C130.391921,121 168,106.673113 168,89 C168,71.3268871 130.391921,57 84,57 C37.6080787,57 0,71.3268871 0,89 C0,106.673113 37.6080787,121 84,121 Z M84,121'; var RING_THREE_PATH = 'M84,121 C130.391921,121 168,106.673113 168,89 C168,71.3268871 130.391921,57 84,57 C37.6080787,57 0,71.3268871 0,89 C0,106.673113 37.6080787,121 84,121 Z M84,121'; var RING_TWO_ROTATE = new Transform() .translate(84.0, 89.0) .rotate(-240.0) .translate(-84.0, -89.0); var RING_THREE_ROTATE = new Transform() .translate(84.0, 89.0) .rotate(-300.0) .translate(-84.0, -89.0); module.exports = VectorWidget;
37.369128
265
0.636459
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 = require('react'); let ReactDOM = require('react-dom'); let ReactFeatureFlags = require('shared/ReactFeatureFlags'); let ReactTestUtils = require('react-dom/test-utils'); // This is testing if string refs are deleted from `instance.refs` // Once support for string refs is removed, this test can be removed. // Detaching is already tested in refs-detruction-test.js describe('reactiverefs', () => { let container; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactTestUtils = require('react-dom/test-utils'); }); afterEach(() => { if (container) { document.body.removeChild(container); container = null; } }); /** * Counts clicks and has a renders an item for each click. Each item rendered * has a ref of the form "clickLogN". */ class ClickCounter extends React.Component { state = {count: this.props.initialCount}; triggerReset = () => { this.setState({count: this.props.initialCount}); }; handleClick = () => { this.setState({count: this.state.count + 1}); }; render() { const children = []; let i; for (i = 0; i < this.state.count; i++) { children.push( <div className="clickLogDiv" key={'clickLog' + i} ref={'clickLog' + i} />, ); } return ( <span className="clickIncrementer" onClick={this.handleClick}> {children} </span> ); } } const expectClickLogsLengthToBe = function (instance, length) { const clickLogs = ReactTestUtils.scryRenderedDOMComponentsWithClass( instance, 'clickLogDiv', ); expect(clickLogs.length).toBe(length); expect(Object.keys(instance.refs.myCounter.refs).length).toBe(length); }; /** * Render a TestRefsComponent and ensure that the main refs are wired up. */ const renderTestRefsComponent = function () { /** * Only purpose is to test that refs are tracked even when applied to a * component that is injected down several layers. Ref systems are difficult to * build in such a way that ownership is maintained in an airtight manner. */ class GeneralContainerComponent extends React.Component { render() { return <div>{this.props.children}</div>; } } /** * Notice how refs ownership is maintained even when injecting a component * into a different parent. */ class TestRefsComponent extends React.Component { doReset = () => { this.refs.myCounter.triggerReset(); }; render() { return ( <div> <div ref="resetDiv" onClick={this.doReset}> Reset Me By Clicking This. </div> <GeneralContainerComponent ref="myContainer"> <ClickCounter ref="myCounter" initialCount={1} /> </GeneralContainerComponent> </div> ); } } container = document.createElement('div'); document.body.appendChild(container); let testRefsComponent; expect(() => { testRefsComponent = ReactDOM.render(<TestRefsComponent />, container); }).toErrorDev([ 'Warning: Component "div" contains the string ref "resetDiv". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref\n' + ' in div (at **)\n' + ' in TestRefsComponent (at **)', 'Warning: Component "span" contains the string ref "clickLog0". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref\n' + ' in span (at **)\n' + ' in ClickCounter (at **)\n' + ' in div (at **)\n' + ' in GeneralContainerComponent (at **)\n' + ' in div (at **)\n' + ' in TestRefsComponent (at **)', ]); expect(testRefsComponent instanceof TestRefsComponent).toBe(true); const generalContainer = testRefsComponent.refs.myContainer; expect(generalContainer instanceof GeneralContainerComponent).toBe(true); const counter = testRefsComponent.refs.myCounter; expect(counter instanceof ClickCounter).toBe(true); return testRefsComponent; }; /** * Ensure that for every click log there is a corresponding ref (from the * perspective of the injected ClickCounter component. */ it('Should increase refs with an increase in divs', () => { const testRefsComponent = renderTestRefsComponent(); const clickIncrementer = ReactTestUtils.findRenderedDOMComponentWithClass( testRefsComponent, 'clickIncrementer', ); expectClickLogsLengthToBe(testRefsComponent, 1); // After clicking the reset, there should still only be one click log ref. testRefsComponent.refs.resetDiv.click(); expectClickLogsLengthToBe(testRefsComponent, 1); // Begin incrementing clicks (and therefore refs). clickIncrementer.click(); expectClickLogsLengthToBe(testRefsComponent, 2); clickIncrementer.click(); expectClickLogsLengthToBe(testRefsComponent, 3); // Now reset again testRefsComponent.refs.resetDiv.click(); expectClickLogsLengthToBe(testRefsComponent, 1); }); }); if (!ReactFeatureFlags.disableModulePatternComponents) { describe('factory components', () => { it('Should correctly get the ref', () => { function Comp() { return { elemRef: React.createRef(), render() { return <div ref={this.elemRef} />; }, }; } let inst; expect( () => (inst = ReactTestUtils.renderIntoDocument(<Comp />)), ).toErrorDev( 'Warning: The <Comp /> component appears to be a function component that returns a class instance. ' + 'Change Comp to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + '`Comp.prototype = React.Component.prototype`. ' + "Don't use an arrow function since it cannot be called with `new` by React.", ); expect(inst.elemRef.current.tagName).toBe('DIV'); }); }); } /** * Tests that when a ref hops around children, we can track that correctly. */ describe('ref swapping', () => { let RefHopsAround; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactTestUtils = require('react-dom/test-utils'); RefHopsAround = class extends React.Component { state = {count: 0}; hopRef = React.createRef(); divOneRef = React.createRef(); divTwoRef = React.createRef(); divThreeRef = React.createRef(); moveRef = () => { this.setState({count: this.state.count + 1}); }; render() { const count = this.state.count; /** * What we have here, is three divs with refs (div1/2/3), but a single * moving cursor ref `hopRef` that "hops" around the three. We'll call the * `moveRef()` function several times and make sure that the hop ref * points to the correct divs. */ return ( <div> <div className="first" ref={count % 3 === 0 ? this.hopRef : this.divOneRef} /> <div className="second" ref={count % 3 === 1 ? this.hopRef : this.divTwoRef} /> <div className="third" ref={count % 3 === 2 ? this.hopRef : this.divThreeRef} /> </div> ); } }; }); it('Allow refs to hop around children correctly', () => { const refHopsAround = ReactTestUtils.renderIntoDocument(<RefHopsAround />); const firstDiv = ReactTestUtils.findRenderedDOMComponentWithClass( refHopsAround, 'first', ); const secondDiv = ReactTestUtils.findRenderedDOMComponentWithClass( refHopsAround, 'second', ); const thirdDiv = ReactTestUtils.findRenderedDOMComponentWithClass( refHopsAround, 'third', ); expect(refHopsAround.hopRef.current).toEqual(firstDiv); expect(refHopsAround.divTwoRef.current).toEqual(secondDiv); expect(refHopsAround.divThreeRef.current).toEqual(thirdDiv); refHopsAround.moveRef(); expect(refHopsAround.divOneRef.current).toEqual(firstDiv); expect(refHopsAround.hopRef.current).toEqual(secondDiv); expect(refHopsAround.divThreeRef.current).toEqual(thirdDiv); refHopsAround.moveRef(); expect(refHopsAround.divOneRef.current).toEqual(firstDiv); expect(refHopsAround.divTwoRef.current).toEqual(secondDiv); expect(refHopsAround.hopRef.current).toEqual(thirdDiv); /** * Make sure that after the third, we're back to where we started and the * refs are completely restored. */ refHopsAround.moveRef(); expect(refHopsAround.hopRef.current).toEqual(firstDiv); expect(refHopsAround.divTwoRef.current).toEqual(secondDiv); expect(refHopsAround.divThreeRef.current).toEqual(thirdDiv); }); it('always has a value for this.refs', () => { class Component extends React.Component { render() { return <div />; } } const instance = ReactTestUtils.renderIntoDocument(<Component />); expect(!!instance.refs).toBe(true); }); it('ref called correctly for stateless component', () => { let refCalled = 0; function Inner(props) { return <a ref={props.saveA} />; } class Outer extends React.Component { saveA = () => { refCalled++; }; componentDidMount() { this.setState({}); } render() { return <Inner saveA={this.saveA} />; } } ReactTestUtils.renderIntoDocument(<Outer />); expect(refCalled).toBe(1); }); it('coerces numbers to strings', () => { class A extends React.Component { render() { return <div ref={1} />; } } let a; expect(() => { a = ReactTestUtils.renderIntoDocument(<A />); }).toErrorDev([ 'Warning: Component "A" contains the string ref "1". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref\n' + ' in A (at **)', ]); expect(a.refs[1].nodeName).toBe('DIV'); }); it('provides an error for invalid refs', () => { expect(() => { ReactTestUtils.renderIntoDocument(<div ref={10} />); }).toThrow( 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.', ); expect(() => { ReactTestUtils.renderIntoDocument(<div ref={true} />); }).toThrow( 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.', ); expect(() => { ReactTestUtils.renderIntoDocument(<div ref={Symbol('foo')} />); }).toThrow( 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.', ); // This works ReactTestUtils.renderIntoDocument(<div ref={undefined} />); ReactTestUtils.renderIntoDocument({ $$typeof: Symbol.for('react.element'), type: 'div', props: {}, key: null, ref: null, }); // But this doesn't expect(() => { ReactTestUtils.renderIntoDocument({ $$typeof: Symbol.for('react.element'), type: 'div', props: {}, key: null, ref: undefined, }); }).toThrow( 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.', ); }); }); describe('root level refs', () => { it('attaches and detaches root refs', () => { let inst = null; // host node let ref = jest.fn(value => (inst = value)); const container = document.createElement('div'); let result = ReactDOM.render(<div ref={ref} />, container); expect(ref).toHaveBeenCalledTimes(1); expect(ref.mock.calls[0][0]).toBeInstanceOf(HTMLDivElement); expect(result).toBe(ref.mock.calls[0][0]); ReactDOM.unmountComponentAtNode(container); expect(ref).toHaveBeenCalledTimes(2); expect(ref.mock.calls[1][0]).toBe(null); // composite class Comp extends React.Component { method() { return true; } render() { return <div>Comp</div>; } } inst = null; ref = jest.fn(value => (inst = value)); result = ReactDOM.render(<Comp ref={ref} />, container); expect(ref).toHaveBeenCalledTimes(1); expect(inst).toBeInstanceOf(Comp); expect(result).toBe(inst); // ensure we have the correct instance expect(result.method()).toBe(true); expect(inst.method()).toBe(true); ReactDOM.unmountComponentAtNode(container); expect(ref).toHaveBeenCalledTimes(2); expect(ref.mock.calls[1][0]).toBe(null); // fragment inst = null; ref = jest.fn(value => (inst = value)); let divInst = null; const ref2 = jest.fn(value => (divInst = value)); result = ReactDOM.render( [ <Comp ref={ref} key="a" />, 5, <div ref={ref2} key="b"> Hello </div>, ], container, ); // first call should be `Comp` expect(ref).toHaveBeenCalledTimes(1); expect(ref.mock.calls[0][0]).toBeInstanceOf(Comp); expect(result).toBe(ref.mock.calls[0][0]); expect(ref2).toHaveBeenCalledTimes(1); expect(divInst).toBeInstanceOf(HTMLDivElement); expect(result).not.toBe(divInst); ReactDOM.unmountComponentAtNode(container); expect(ref).toHaveBeenCalledTimes(2); expect(ref.mock.calls[1][0]).toBe(null); expect(ref2).toHaveBeenCalledTimes(2); expect(ref2.mock.calls[1][0]).toBe(null); // null result = ReactDOM.render(null, container); expect(result).toBe(null); // primitives result = ReactDOM.render(5, container); expect(result).toBeInstanceOf(Text); }); }); describe('creating element with string ref in constructor', () => { class RefTest extends React.Component { constructor(props) { super(props); this.p = <p ref="p">Hello!</p>; } render() { return <div>{this.p}</div>; } } it('throws an error', () => { ReactTestUtils = require('react-dom/test-utils'); expect(function () { ReactTestUtils.renderIntoDocument(<RefTest />); }).toThrowError( 'Element ref was specified as a string (p) but no owner was set. This could happen for one of' + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.', ); }); }); describe('strings refs across renderers', () => { it('does not break', () => { class Parent extends React.Component { render() { // This component owns both refs. return ( <Indirection child1={<div ref="child1" />} child2={<div ref="child2" />} /> ); } } class Indirection extends React.Component { componentDidUpdate() { // One ref is being rendered later using another renderer copy. jest.resetModules(); const AnotherCopyOfReactDOM = require('react-dom'); AnotherCopyOfReactDOM.render(this.props.child2, div2); } render() { // The other one is being rendered directly. return this.props.child1; } } const div1 = document.createElement('div'); const div2 = document.createElement('div'); let inst; expect(() => { inst = ReactDOM.render(<Parent />, div1); }).toErrorDev([ 'Warning: Component "Indirection" contains the string ref "child1". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref\n' + ' in Indirection (at **)\n' + ' in Parent (at **)', ]); // Only the first ref has rendered yet. expect(inst.refs.child1.tagName).toBe('DIV'); expect(inst.refs.child1).toBe(div1.firstChild); expect(() => { // Now both refs should be rendered. ReactDOM.render(<Parent />, div1); }).toErrorDev( [ 'Warning: Component "Root" contains the string ref "child2". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', ], {withoutStack: true}, ); expect(inst.refs.child1.tagName).toBe('DIV'); expect(inst.refs.child1).toBe(div1.firstChild); expect(inst.refs.child2.tagName).toBe('DIV'); expect(inst.refs.child2).toBe(div2.firstChild); }); }); describe('refs return clean up function', () => { it('calls clean up function if it exists', () => { const container = document.createElement('div'); let cleanUp = jest.fn(); let setup = jest.fn(); ReactDOM.render( <div ref={_ref => { setup(_ref); return cleanUp; }} />, container, ); ReactDOM.render( <div ref={_ref => { setup(_ref); }} />, container, ); expect(setup).toHaveBeenCalledTimes(2); expect(cleanUp).toHaveBeenCalledTimes(1); expect(cleanUp.mock.calls[0][0]).toBe(undefined); ReactDOM.render(<div ref={_ref => {}} />, container); expect(cleanUp).toHaveBeenCalledTimes(1); expect(setup).toHaveBeenCalledTimes(3); expect(setup.mock.calls[2][0]).toBe(null); cleanUp = jest.fn(); setup = jest.fn(); ReactDOM.render( <div ref={_ref => { setup(_ref); return cleanUp; }} />, container, ); expect(setup).toHaveBeenCalledTimes(1); expect(cleanUp).toHaveBeenCalledTimes(0); ReactDOM.render( <div ref={_ref => { setup(_ref); return cleanUp; }} />, container, ); expect(setup).toHaveBeenCalledTimes(2); expect(cleanUp).toHaveBeenCalledTimes(1); }); it('handles ref functions with stable identity', () => { const container = document.createElement('div'); const cleanUp = jest.fn(); const setup = jest.fn(); function _onRefChange(_ref) { setup(_ref); return cleanUp; } ReactDOM.render(<div ref={_onRefChange} />, container); expect(setup).toHaveBeenCalledTimes(1); expect(cleanUp).toHaveBeenCalledTimes(0); ReactDOM.render( <div className="niceClassName" ref={_onRefChange} />, container, ); expect(setup).toHaveBeenCalledTimes(1); expect(cleanUp).toHaveBeenCalledTimes(0); ReactDOM.render(<div />, container); expect(setup).toHaveBeenCalledTimes(1); expect(cleanUp).toHaveBeenCalledTimes(1); }); it('warns if clean up function is returned when called with null', () => { const container = document.createElement('div'); const cleanUp = jest.fn(); const setup = jest.fn(); let returnCleanUp = false; ReactDOM.render( <div ref={_ref => { setup(_ref); if (returnCleanUp) { return cleanUp; } }} />, container, ); expect(setup).toHaveBeenCalledTimes(1); expect(cleanUp).toHaveBeenCalledTimes(0); returnCleanUp = true; expect(() => { ReactDOM.render( <div ref={_ref => { setup(_ref); if (returnCleanUp) { return cleanUp; } }} />, container, ); }).toErrorDev('Unexpected return value from a callback ref in div'); }); });
28.686525
111
0.604597
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 */ /** * CSS properties which accept numbers but are not in units of "px". */ const unitlessNumbers = new Set([ 'animationIterationCount', 'aspectRatio', 'borderImageOutset', 'borderImageSlice', 'borderImageWidth', 'boxFlex', 'boxFlexGroup', 'boxOrdinalGroup', 'columnCount', 'columns', 'flex', 'flexGrow', 'flexPositive', 'flexShrink', 'flexNegative', 'flexOrder', 'gridArea', 'gridRow', 'gridRowEnd', 'gridRowSpan', 'gridRowStart', 'gridColumn', 'gridColumnEnd', 'gridColumnSpan', 'gridColumnStart', 'fontWeight', 'lineClamp', 'lineHeight', 'opacity', 'order', 'orphans', 'scale', 'tabSize', 'widows', 'zIndex', 'zoom', 'fillOpacity', // SVG-related properties 'floodOpacity', 'stopOpacity', 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth', 'MozAnimationIterationCount', // Known Prefixed Properties 'MozBoxFlex', // TODO: Remove these since they shouldn't be used in modern code 'MozBoxFlexGroup', 'MozLineClamp', 'msAnimationIterationCount', 'msFlex', 'msZoom', 'msFlexGrow', 'msFlexNegative', 'msFlexOrder', 'msFlexPositive', 'msFlexShrink', 'msGridColumn', 'msGridColumnSpan', 'msGridRow', 'msGridRowSpan', 'WebkitAnimationIterationCount', 'WebkitBoxFlex', 'WebKitBoxFlexGroup', 'WebkitBoxOrdinalGroup', 'WebkitColumnCount', 'WebkitColumns', 'WebkitFlex', 'WebkitFlexGrow', 'WebkitFlexPositive', 'WebkitFlexShrink', 'WebkitLineClamp', ]); export default function (name: string): boolean { return unitlessNumbers.has(name); }
19.460674
81
0.682418
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 */ export opaque type CrossOriginString: string = string; export function getCrossOriginString(input: ?string): ?CrossOriginString { if (typeof input === 'string') { return input === 'use-credentials' ? input : ''; } return undefined; } export function getCrossOriginStringAs( as: ?string, input: ?string, ): ?CrossOriginString { if (as === 'font') { return ''; } if (typeof input === 'string') { return input === 'use-credentials' ? input : ''; } return undefined; }
21.709677
74
0.655761
owtf
/* * Copyright (c) Facebook, Inc. and its affiliates. */ exports.siteConfig = { // -------------------------------------- // Translations should replace these lines: languageCode: 'en', hasLegacySite: true, isRTL: false, // -------------------------------------- copyright: `Copyright © ${new Date().getFullYear()} Facebook Inc. All Rights Reserved.`, repoUrl: 'https://github.com/facebook/react', twitterUrl: 'https://twitter.com/reactjs', algolia: { appId: '1FCF9AYYAT', apiKey: 'e8451218980a351815563de007648b00', indexName: 'beta-react', }, };
26.904762
90
0.577778
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'; export * from './src/forks/SchedulerPostTask';
22.181818
66
0.708661
owtf
export default function BigComponent() { return ( <article> <section> <h2>Description</h2> <p> This page has repeating sections purposefully to create very large trees that stress the rendering and streaming capabilities of Fizz </p> </section> <section> <h2>Another Section</h2> <p>this section has a list</p> <ul> <li>item one</li> <li>item two</li> <li>item three</li> <li>item four</li> <li>item five</li> </ul> <p>it isn't a very interesting list</p> </section> <section> <h2>Smiley Section</h2> <p>here is a list of smiley emojis</p> <ol> <li>😀</li> <li>😃</li> <li>😄</li> <li>😁</li> <li>😆</li> <li>😅</li> <li>😂</li> <li>🤣</li> <li>🥲</li> <li>☺️</li> <li>😊</li> <li>😇</li> <li>🙂</li> <li>🙃</li> <li>😉</li> <li>😌</li> <li>😍</li> <li>🥰</li> <li>😘</li> <li>😗</li> <li>😙</li> <li>😚</li> <li>😋</li> <li>😛</li> <li>😝</li> <li>😜</li> <li>🤪</li> <li>🤨</li> <li>🧐</li> <li>🤓</li> <li>😎</li> <li>🥸</li> <li>🤩</li> <li>🥳</li> <li>😏</li> <li>😒</li> <li>😞</li> <li>😔</li> <li>😟</li> <li>😕</li> <li>🙁</li> <li>☹️</li> <li>😣</li> <li>😖</li> <li>😫</li> <li>😩</li> <li>🥺</li> <li>😢</li> <li>😭</li> <li>😤</li> <li>😠</li> <li>😡</li> <li>🤬</li> <li>🤯</li> <li>😳</li> <li>🥵</li> <li>🥶</li> <li>😱</li> <li>😨</li> <li>😰</li> <li>😥</li> <li>😓</li> <li>🤗</li> <li>🤔</li> <li>🤭</li> <li>🤫</li> <li>🤥</li> <li>😶</li> <li>😐</li> <li>😑</li> <li>😬</li> <li>🙄</li> <li>😯</li> <li>😦</li> <li>😧</li> <li>😮</li> <li>😲</li> <li>🥱</li> <li>😴</li> <li>🤤</li> <li>😪</li> <li>😵</li> <li>🤐</li> <li>🥴</li> <li>🤢</li> <li>🤮</li> <li>🤧</li> <li>😷</li> <li>🤒</li> <li>🤕</li> <li>🤑</li> <li>🤠</li> <li>😈</li> <li>👿</li> <li>👹</li> <li>👺</li> <li>🤡</li> <li>💩</li> <li>👻</li> <li>💀</li> <li>☠️</li> <li>👽</li> <li>👾</li> <li>🤖</li> <li>🎃</li> <li>😺</li> <li>😸</li> <li>😹</li> <li>😻</li> <li>😼</li> <li>😽</li> <li>🙀</li> <li>😿</li> <li>😾</li> </ol> </section> <section> <h2>Translation Section</h2> <p>This is the final section you will see before the sections repeat</p> <p> English: This is a text block translated from English to another language in Google Translate. </p> <p> Korean: 이것은 Google 번역에서 영어에서 다른 언어로 번역된 텍스트 블록입니다. </p> <p> Hindi: यह Google अनुवाद में अंग्रेज़ी से दूसरी भाषा में अनुवादित टेक्स्ट ब्लॉक है। </p> <p> Lithuanian: Tai teksto blokas, išverstas iš anglų kalbos į kitą „Google“ vertėjo kalbą. </p> <div> <div> <div> <div> <div> <div> <span> we're deep in some nested divs here, not that you can tell visually </span> </div> </div> </div> </div> </div> </div> </section> </article> ); }
22.291209
80
0.303445
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 spyOn = jest.spyOn; // Spying on console methods in production builds can mask errors. // This is why we added an explicit spyOnDev() helper. // It's too easy to accidentally use the more familiar spyOn() helper though, // So we disable it entirely. // Spying on both dev and prod will require using both spyOnDev() and spyOnProd(). global.spyOn = function () { throw new Error( 'Do not use spyOn(). ' + 'It can accidentally hide unexpected errors in production builds. ' + 'Use spyOnDev(), spyOnProd(), or spyOnDevAndProd() instead.' ); }; global.spyOnDev = function (...args) { if (__DEV__) { return spyOn(...args); } }; global.spyOnDevAndProd = spyOn; global.spyOnProd = function (...args) { if (!__DEV__) { return spyOn(...args); } }; expect.extend({ ...require('../matchers/reactTestMatchers'), ...require('../matchers/toThrow'), ...require('../matchers/toWarnDev'), });
24.840909
82
0.661972
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. */ import getActiveElement from './getActiveElement'; import {getOffsets, setOffsets} from './ReactDOMSelection'; import {ELEMENT_NODE, TEXT_NODE} from './HTMLNodeType'; function isTextNode(node) { return node && node.nodeType === TEXT_NODE; } function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } function isInDocument(node) { return ( node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node) ); } function isSameOriginFrame(iframe) { try { // Accessing the contentDocument of a HTMLIframeElement can cause the browser // to throw, e.g. if it has a cross-origin src attribute. // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g: // iframe.contentDocument.defaultView; // A safety way is to access one of the cross origin properties: Window or Location // Which might result in "SecurityError" DOM Exception and it is compatible to Safari. // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl return typeof iframe.contentWindow.location.href === 'string'; } catch (err) { return false; } } function getActiveElementDeep() { let win = window; let element = getActiveElement(); while (element instanceof win.HTMLIFrameElement) { if (isSameOriginFrame(element)) { win = element.contentWindow; } else { return element; } element = getActiveElement(win.document); } return element; } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ /** * @hasSelectionCapabilities: we get the element types that support selection * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart` * and `selectionEnd` rows. */ export function hasSelectionCapabilities(elem) { const nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return ( nodeName && ((nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password')) || nodeName === 'textarea' || elem.contentEditable === 'true') ); } export function getSelectionInformation() { const focusedElem = getActiveElementDeep(); return { focusedElem: focusedElem, selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null, }; } /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ export function restoreSelection(priorSelectionInformation) { const curFocusedElem = getActiveElementDeep(); const priorFocusedElem = priorSelectionInformation.focusedElem; const priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if ( priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem) ) { setSelection(priorFocusedElem, priorSelectionRange); } // Focusing a node can change the scroll position, which is undesirable const ancestors = []; let ancestor = priorFocusedElem; while ((ancestor = ancestor.parentNode)) { if (ancestor.nodeType === ELEMENT_NODE) { ancestors.push({ element: ancestor, left: ancestor.scrollLeft, top: ancestor.scrollTop, }); } } if (typeof priorFocusedElem.focus === 'function') { priorFocusedElem.focus(); } for (let i = 0; i < ancestors.length; i++) { const info = ancestors[i]; info.element.scrollLeft = info.left; info.element.scrollTop = info.top; } } } /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ export function getSelection(input) { let selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd, }; } else { // Content editable or old IE textarea. selection = getOffsets(input); } return selection || {start: 0, end: 0}; } /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ export function setSelection(input, offsets) { const start = offsets.start; let end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else { setOffsets(input, offsets); } }
28.774359
110
0.681309
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. */ import {canUseDOM} from 'shared/ExecutionEnvironment'; /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { const prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ const vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd'), }; /** * Event names that have already been detected and prefixed (if applicable). */ const prefixedEventNames = {}; /** * Element to check for prefixes on. */ let style = {}; /** * Bootstrap if a DOM exists. */ if (canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } const prefixMap = vendorPrefixes[eventName]; for (const styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return (prefixedEventNames[eventName] = prefixMap[styleProp]); } } return eventName; } export default getVendorPrefixedEventName;
26.787234
98
0.718882
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'; let React; let ReactDOM; let ReactTestUtils; describe('ReactJSXElement', () => { let Component; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactTestUtils = require('react-dom/test-utils'); Component = class extends React.Component { render() { return <div />; } }; }); it('returns a complete element according to spec', () => { const element = <Component />; expect(element.type).toBe(Component); expect(element.key).toBe(null); expect(element.ref).toBe(null); const expectation = {}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('allows a lower-case to be passed as the string type', () => { const element = <div />; expect(element.type).toBe('div'); expect(element.key).toBe(null); expect(element.ref).toBe(null); const expectation = {}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('allows a string to be passed as the type', () => { const TagName = 'div'; const element = <TagName />; expect(element.type).toBe('div'); expect(element.key).toBe(null); expect(element.ref).toBe(null); const expectation = {}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('returns an immutable element', () => { const element = <Component />; if (__DEV__) { expect(() => (element.type = 'div')).toThrow(); } else { expect(() => (element.type = 'div')).not.toThrow(); } }); it('does not reuse the object that is spread into props', () => { const config = {foo: 1}; const element = <Component {...config} />; expect(element.props.foo).toBe(1); config.foo = 2; expect(element.props.foo).toBe(1); }); it('extracts key and ref from the rest of the props', () => { const ref = React.createRef(); const element = <Component key="12" ref={ref} foo="56" />; expect(element.type).toBe(Component); expect(element.key).toBe('12'); expect(element.ref).toBe(ref); const expectation = {foo: '56'}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('coerces the key to a string', () => { const element = <Component key={12} foo="56" />; expect(element.type).toBe(Component); expect(element.key).toBe('12'); expect(element.ref).toBe(null); const expectation = {foo: '56'}; Object.freeze(expectation); expect(element.props).toEqual(expectation); }); it('merges JSX children onto the children prop', () => { const a = 1; const element = <Component children="text">{a}</Component>; expect(element.props.children).toBe(a); }); it('does not override children if no JSX children are provided', () => { const element = <Component children="text" />; expect(element.props.children).toBe('text'); }); it('overrides children if null is provided as a JSX child', () => { const element = <Component children="text">{null}</Component>; expect(element.props.children).toBe(null); }); it('overrides children if undefined is provided as an argument', () => { const element = <Component children="text">{undefined}</Component>; expect(element.props.children).toBe(undefined); const element2 = React.cloneElement( <Component children="text" />, {}, undefined, ); expect(element2.props.children).toBe(undefined); }); it('merges JSX children onto the children prop in an array', () => { const a = 1; const b = 2; const c = 3; const element = ( <Component> {a} {b} {c} </Component> ); expect(element.props.children).toEqual([1, 2, 3]); }); it('allows static methods to be called using the type property', () => { class StaticMethodComponent { static someStaticMethod() { return 'someReturnValue'; } render() { return <div />; } } const element = <StaticMethodComponent />; expect(element.type.someStaticMethod()).toBe('someReturnValue'); }); it('identifies valid elements', () => { expect(React.isValidElement(<div />)).toEqual(true); expect(React.isValidElement(<Component />)).toEqual(true); expect(React.isValidElement(null)).toEqual(false); expect(React.isValidElement(true)).toEqual(false); expect(React.isValidElement({})).toEqual(false); expect(React.isValidElement('string')).toEqual(false); expect(React.isValidElement(Component)).toEqual(false); expect(React.isValidElement({type: 'div', props: {}})).toEqual(false); }); it('is indistinguishable from a plain object', () => { const element = <div className="foo" />; const object = {}; expect(element.constructor).toBe(object.constructor); }); it('should use default prop value when removing a prop', () => { Component.defaultProps = {fruit: 'persimmon'}; const container = document.createElement('div'); const instance = ReactDOM.render(<Component fruit="mango" />, container); expect(instance.props.fruit).toBe('mango'); ReactDOM.render(<Component />, container); expect(instance.props.fruit).toBe('persimmon'); }); it('should normalize props with default values', () => { class NormalizingComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } NormalizingComponent.defaultProps = {prop: 'testKey'}; const instance = ReactTestUtils.renderIntoDocument( <NormalizingComponent />, ); expect(instance.props.prop).toBe('testKey'); const inst2 = ReactTestUtils.renderIntoDocument( <NormalizingComponent prop={null} />, ); expect(inst2.props.prop).toBe(null); }); });
28.673171
77
0.629069
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'; // This test is a hot mess. It heavily uses internals and relies on DOM even // though the responder plugin is only used in React Native. Sadness ensues. // The coverage is valuable though, so we will keep it for now. const {HostComponent} = require('react-reconciler/src/ReactWorkTags'); let EventBatching; let EventPluginUtils; let ResponderEventPlugin; const touch = function (nodeHandle, i) { return {target: nodeHandle, identifier: i}; }; function injectComponentTree(ComponentTree) { EventPluginUtils.setComponentTree( ComponentTree.getFiberCurrentPropsFromNode, ComponentTree.getInstanceFromNode, ComponentTree.getNodeFromInstance, ); } /** * @param {NodeHandle} nodeHandle @see NodeHandle. Handle of target. * @param {Array<Touch>} touches All active touches. * @param {Array<Touch>} changedTouches Only the touches that have changed. * @return {TouchEvent} Model of a touch event that is compliant with responder * system plugin. */ const touchEvent = function (nodeHandle, touches, changedTouches) { return { target: nodeHandle, changedTouches: changedTouches, touches: touches, }; }; const subsequence = function (arr, indices) { const ret = []; for (let i = 0; i < indices.length; i++) { const index = indices[i]; ret.push(arr[index]); } return ret; }; const antiSubsequence = function (arr, indices) { const ret = []; for (let i = 0; i < arr.length; i++) { if (indices.indexOf(i) === -1) { ret.push(arr[i]); } } return ret; }; /** * Helper for creating touch test config data. * @param allTouchHandles */ const _touchConfig = function ( topType, targetNodeHandle, allTouchHandles, changedIndices, eventTarget, ) { const allTouchObjects = allTouchHandles.map(touch); const changedTouchObjects = subsequence(allTouchObjects, changedIndices); const activeTouchObjects = topType === 'topTouchStart' ? allTouchObjects : topType === 'topTouchMove' ? allTouchObjects : topType === 'topTouchEnd' ? antiSubsequence(allTouchObjects, changedIndices) : topType === 'topTouchCancel' ? antiSubsequence(allTouchObjects, changedIndices) : null; return { nativeEvent: touchEvent( targetNodeHandle, activeTouchObjects, changedTouchObjects, ), topLevelType: topType, targetInst: getInstanceFromNode(targetNodeHandle), }; }; /** * Creates test data for touch events using environment agnostic "node * handles". * * @param {NodeHandle} nodeHandle Environment agnostic handle to DOM node. * @param {Array<NodeHandle>} allTouchHandles Encoding of all "touches" in the * form of a mapping from integer (touch `identifier`) to touch target. This is * encoded in array form. Because of this, it is possible for two separate * touches (meaning two separate indices) to have the same touch target ID - * this corresponds to real world cases where two separate unique touches have * the same target. These touches don't just represent all active touches, * rather it also includes any touches that are not active, but are in the * process of being removed. * @param {Array<NodeHandle>} changedIndices Indices of `allTouchHandles` that * have changed. * @return {object} Config data used by test cases for extracting responder * events. */ const startConfig = function (nodeHandle, allTouchHandles, changedIndices) { return _touchConfig( 'topTouchStart', nodeHandle, allTouchHandles, changedIndices, nodeHandle, ); }; /** * @see `startConfig` */ const moveConfig = function (nodeHandle, allTouchHandles, changedIndices) { return _touchConfig( 'topTouchMove', nodeHandle, allTouchHandles, changedIndices, nodeHandle, ); }; /** * @see `startConfig` */ const endConfig = function (nodeHandle, allTouchHandles, changedIndices) { return _touchConfig( 'topTouchEnd', nodeHandle, allTouchHandles, changedIndices, nodeHandle, ); }; /** * Test config for events that aren't negotiation related, but rather result of * a negotiation. * * Returns object of the form: * * { * responderReject: { * // Whatever "readableIDToID" was passed in. * grandParent: {order: NA, assertEvent: null, returnVal: blah}, * ... * child: {order: NA, assertEvent: null, returnVal: blah}, * } * responderGrant: { * grandParent: {order: NA, assertEvent: null, returnVal: blah}, * ... * child: {order: NA, assertEvent: null, returnVal: blah} * } * ... * } * * After this is created, a test case would configure specific event orderings * and optional assertions. Anything left with an `order` of `NA` will be * required to never be invoked (the test runner will make sure it throws if * ever invoked). * */ const NA = -1; const oneEventLoopTestConfig = function (readableIDToID) { const ret = { // Negotiation scrollShouldSetResponder: {bubbled: {}, captured: {}}, startShouldSetResponder: {bubbled: {}, captured: {}}, moveShouldSetResponder: {bubbled: {}, captured: {}}, responderTerminationRequest: {}, // Non-negotiation responderReject: {}, // These do not bubble capture. responderGrant: {}, responderStart: {}, responderMove: {}, responderTerminate: {}, responderEnd: {}, responderRelease: {}, }; for (const eventName in ret) { for (const readableNodeName in readableIDToID) { if (ret[eventName].bubbled) { // Two phase ret[eventName].bubbled[readableNodeName] = { order: NA, assertEvent: null, returnVal: undefined, }; ret[eventName].captured[readableNodeName] = { order: NA, assertEvent: null, returnVal: undefined, }; } else { ret[eventName][readableNodeName] = { order: NA, assertEvent: null, returnVal: undefined, }; } } } return ret; }; /** * @param {object} eventTestConfig * @param {object} readableIDToID */ const registerTestHandlers = function (eventTestConfig, readableIDToID) { const runs = {dispatchCount: 0}; const neverFire = function (readableID, registrationName) { runs.dispatchCount++; expect('').toBe( 'Event type: ' + registrationName + '\nShould never occur on:' + readableID + '\nFor event test config:\n' + JSON.stringify(eventTestConfig) + '\n', ); }; const registerOneEventType = function ( registrationName, eventTypeTestConfig, ) { for (const readableID in eventTypeTestConfig) { const nodeConfig = eventTypeTestConfig[readableID]; const id = readableIDToID[readableID]; const handler = nodeConfig.order === NA ? neverFire.bind(null, readableID, registrationName) : // We partially apply readableID and nodeConfig, as they change in the // parent closure across iterations. function (rID, config, e) { expect( rID + '->' + registrationName + ' index:' + runs.dispatchCount++, ).toBe(rID + '->' + registrationName + ' index:' + config.order); if (config.assertEvent) { config.assertEvent(e); } return config.returnVal; }.bind(null, readableID, nodeConfig); putListener(getInstanceFromNode(id), registrationName, handler); } }; for (const eventName in eventTestConfig) { const oneEventTypeTestConfig = eventTestConfig[eventName]; const hasTwoPhase = !!oneEventTypeTestConfig.bubbled; if (hasTwoPhase) { registerOneEventType( ResponderEventPlugin.eventTypes[eventName].phasedRegistrationNames .bubbled, oneEventTypeTestConfig.bubbled, ); registerOneEventType( ResponderEventPlugin.eventTypes[eventName].phasedRegistrationNames .captured, oneEventTypeTestConfig.captured, ); } else { registerOneEventType( ResponderEventPlugin.eventTypes[eventName].registrationName, oneEventTypeTestConfig, ); } } return runs; }; const run = function (config, hierarchyConfig, nativeEventConfig) { let max = NA; const searchForMax = function (nodeConfig) { for (const readableID in nodeConfig) { const order = nodeConfig[readableID].order; max = order > max ? order : max; } }; for (const eventName in config) { const eventConfig = config[eventName]; if (eventConfig.bubbled) { searchForMax(eventConfig.bubbled); searchForMax(eventConfig.captured); } else { searchForMax(eventConfig); } } // Register the handlers const runData = registerTestHandlers(config, hierarchyConfig); // Trigger the event const extractedEvents = ResponderEventPlugin.extractEvents( nativeEventConfig.topLevelType, nativeEventConfig.targetInst, nativeEventConfig.nativeEvent, nativeEventConfig.target, 0, ); // At this point the negotiation events have been dispatched as part of the // extraction process, but not the side effectful events. Below, we dispatch // side effectful events. EventBatching.runEventsInBatch(extractedEvents); // Ensure that every event that declared an `order`, was actually dispatched. expect('number of events dispatched:' + runData.dispatchCount).toBe( 'number of events dispatched:' + (max + 1), ); // +1 for extra ++ }; const GRANDPARENT_HOST_NODE = {}; const PARENT_HOST_NODE = {}; const CHILD_HOST_NODE = {}; const CHILD_HOST_NODE2 = {}; // These intentionally look like Fibers. ReactTreeTraversal depends on their field names. // TODO: we could test this with regular DOM nodes (and real fibers) instead. const GRANDPARENT_INST = { return: null, tag: HostComponent, stateNode: GRANDPARENT_HOST_NODE, memoizedProps: {}, }; const PARENT_INST = { return: GRANDPARENT_INST, tag: HostComponent, stateNode: PARENT_HOST_NODE, memoizedProps: {}, }; const CHILD_INST = { return: PARENT_INST, tag: HostComponent, stateNode: CHILD_HOST_NODE, memoizedProps: {}, }; const CHILD_INST2 = { return: PARENT_INST, tag: HostComponent, stateNode: CHILD_HOST_NODE2, memoizedProps: {}, }; GRANDPARENT_HOST_NODE.testInstance = GRANDPARENT_INST; PARENT_HOST_NODE.testInstance = PARENT_INST; CHILD_HOST_NODE.testInstance = CHILD_INST; CHILD_HOST_NODE2.testInstance = CHILD_INST2; const three = { grandParent: GRANDPARENT_HOST_NODE, parent: PARENT_HOST_NODE, child: CHILD_HOST_NODE, }; const siblings = { parent: PARENT_HOST_NODE, childOne: CHILD_HOST_NODE, childTwo: CHILD_HOST_NODE2, }; function getInstanceFromNode(node) { return node.testInstance; } function getNodeFromInstance(inst) { return inst.stateNode; } function getFiberCurrentPropsFromNode(node) { return node.testInstance.memoizedProps; } function putListener(instance, registrationName, handler) { instance.memoizedProps[registrationName] = handler; } function deleteAllListeners(instance) { instance.memoizedProps = {}; } describe('ResponderEventPlugin', () => { beforeEach(() => { jest.resetModules(); EventBatching = require('react-native-renderer/src/legacy-events/EventBatching'); EventPluginUtils = require('react-native-renderer/src/legacy-events/EventPluginUtils'); ResponderEventPlugin = require('react-native-renderer/src/legacy-events/ResponderEventPlugin').default; deleteAllListeners(GRANDPARENT_INST); deleteAllListeners(PARENT_INST); deleteAllListeners(CHILD_INST); deleteAllListeners(CHILD_INST2); injectComponentTree({ getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, }); }); it('should do nothing when no one wants to respond', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false}; config.startShouldSetResponder.bubbled.parent = { order: 4, returnVal: false, }; config.startShouldSetResponder.bubbled.grandParent = { order: 5, returnVal: false, }; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); // Now no handlers should be called on `touchEnd`. config = oneEventLoopTestConfig(three); run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); /** * Simple Start Granting * -------------------- */ it('should grant responder grandParent while capturing', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: true, }; config.responderGrant.grandParent = {order: 1}; config.responderStart.grandParent = {order: 2}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.grandParent), ); config = oneEventLoopTestConfig(three); config.responderEnd.grandParent = {order: 0}; config.responderRelease.grandParent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder parent while capturing', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: true, }; config.responderGrant.parent = {order: 2}; config.responderStart.parent = {order: 3}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); config = oneEventLoopTestConfig(three); config.responderEnd.parent = {order: 0}; config.responderRelease.parent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder child while capturing', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = {order: 2, returnVal: true}; config.responderGrant.child = {order: 3}; config.responderStart.child = {order: 4}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); config = oneEventLoopTestConfig(three); config.responderEnd.child = {order: 0}; config.responderRelease.child = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder child while bubbling', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true}; config.responderGrant.child = {order: 4}; config.responderStart.child = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); config = oneEventLoopTestConfig(three); config.responderEnd.child = {order: 0}; config.responderRelease.child = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder parent while bubbling', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false}; config.startShouldSetResponder.bubbled.parent = {order: 4, returnVal: true}; config.responderGrant.parent = {order: 5}; config.responderStart.parent = {order: 6}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); config = oneEventLoopTestConfig(three); config.responderEnd.parent = {order: 0}; config.responderRelease.parent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder grandParent while bubbling', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: false}; config.startShouldSetResponder.bubbled.parent = { order: 4, returnVal: false, }; config.startShouldSetResponder.bubbled.grandParent = { order: 5, returnVal: true, }; config.responderGrant.grandParent = {order: 6}; config.responderStart.grandParent = {order: 7}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.grandParent), ); config = oneEventLoopTestConfig(three); config.responderEnd.grandParent = {order: 0}; config.responderRelease.grandParent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); /** * Simple Move Granting * -------------------- */ it('should grant responder grandParent while capturing move', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = {order: 0}; config.startShouldSetResponder.captured.parent = {order: 1}; config.startShouldSetResponder.captured.child = {order: 2}; config.startShouldSetResponder.bubbled.child = {order: 3}; config.startShouldSetResponder.bubbled.parent = {order: 4}; config.startShouldSetResponder.bubbled.grandParent = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: true, }; config.responderGrant.grandParent = {order: 1}; config.responderMove.grandParent = {order: 2}; run(config, three, moveConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.grandParent), ); config = oneEventLoopTestConfig(three); config.responderEnd.grandParent = {order: 0}; config.responderRelease.grandParent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder parent while capturing move', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = {order: 0}; config.startShouldSetResponder.captured.parent = {order: 1}; config.startShouldSetResponder.captured.child = {order: 2}; config.startShouldSetResponder.bubbled.child = {order: 3}; config.startShouldSetResponder.bubbled.parent = {order: 4}; config.startShouldSetResponder.bubbled.grandParent = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.captured.parent = {order: 1, returnVal: true}; config.responderGrant.parent = {order: 2}; config.responderMove.parent = {order: 3}; run(config, three, moveConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); config = oneEventLoopTestConfig(three); config.responderEnd.parent = {order: 0}; config.responderRelease.parent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder child while capturing move', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = {order: 0}; config.startShouldSetResponder.captured.parent = {order: 1}; config.startShouldSetResponder.captured.child = {order: 2}; config.startShouldSetResponder.bubbled.child = {order: 3}; config.startShouldSetResponder.bubbled.parent = {order: 4}; config.startShouldSetResponder.bubbled.grandParent = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.moveShouldSetResponder.captured.child = {order: 2, returnVal: true}; config.responderGrant.child = {order: 3}; config.responderMove.child = {order: 4}; run(config, three, moveConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); config = oneEventLoopTestConfig(three); config.responderEnd.child = {order: 0}; config.responderRelease.child = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder child while bubbling move', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = {order: 0}; config.startShouldSetResponder.captured.parent = {order: 1}; config.startShouldSetResponder.captured.child = {order: 2}; config.startShouldSetResponder.bubbled.child = {order: 3}; config.startShouldSetResponder.bubbled.parent = {order: 4}; config.startShouldSetResponder.bubbled.grandParent = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false}; config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: true}; config.responderGrant.child = {order: 4}; config.responderMove.child = {order: 5}; run(config, three, moveConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); config = oneEventLoopTestConfig(three); config.responderEnd.child = {order: 0}; config.responderRelease.child = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder parent while bubbling move', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = {order: 0}; config.startShouldSetResponder.captured.parent = {order: 1}; config.startShouldSetResponder.captured.child = {order: 2}; config.startShouldSetResponder.bubbled.child = {order: 3}; config.startShouldSetResponder.bubbled.parent = {order: 4}; config.startShouldSetResponder.bubbled.grandParent = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false}; config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: false}; config.moveShouldSetResponder.bubbled.parent = {order: 4, returnVal: true}; config.responderGrant.parent = {order: 5}; config.responderMove.parent = {order: 6}; run(config, three, moveConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); config = oneEventLoopTestConfig(three); config.responderEnd.parent = {order: 0}; config.responderRelease.parent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should grant responder grandParent while bubbling move', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = {order: 0}; config.startShouldSetResponder.captured.parent = {order: 1}; config.startShouldSetResponder.captured.child = {order: 2}; config.startShouldSetResponder.bubbled.child = {order: 3}; config.startShouldSetResponder.bubbled.parent = {order: 4}; config.startShouldSetResponder.bubbled.grandParent = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.moveShouldSetResponder.captured.child = {order: 2, returnVal: false}; config.moveShouldSetResponder.bubbled.child = {order: 3, returnVal: false}; config.moveShouldSetResponder.bubbled.parent = {order: 4, returnVal: false}; config.moveShouldSetResponder.bubbled.grandParent = { order: 5, returnVal: true, }; config.responderGrant.grandParent = {order: 6}; config.responderMove.grandParent = {order: 7}; run(config, three, moveConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.grandParent), ); config = oneEventLoopTestConfig(three); config.responderEnd.grandParent = {order: 0}; config.responderRelease.grandParent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); /** * Common ancestor tests * --------------------- */ it('should bubble negotiation to first common ancestor of responder', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: true, }; config.responderGrant.parent = {order: 2}; config.responderStart.parent = {order: 3}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); // While `parent` is still responder, we create new handlers that verify // the ordering of propagation, restarting the count at `0`. config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.bubbled.grandParent = { order: 1, returnVal: false, }; config.responderStart.parent = {order: 2}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); config = oneEventLoopTestConfig(three); config.responderEnd.parent = {order: 0}; config.responderRelease.parent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should bubble negotiation to first common ancestor of responder then transfer', () => { let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: true, }; config.responderGrant.parent = {order: 2}; config.responderStart.parent = {order: 3}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); config = oneEventLoopTestConfig(three); // Parent is responder, and responder is transferred by a second touch start config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: true, }; config.responderGrant.grandParent = {order: 1}; config.responderTerminationRequest.parent = {order: 2, returnVal: true}; config.responderTerminate.parent = {order: 3}; config.responderStart.grandParent = {order: 4}; run( config, three, startConfig(three.child, [three.child, three.child], [1]), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.grandParent), ); config = oneEventLoopTestConfig(three); config.responderEnd.grandParent = {order: 0}; // one remains\ /one ended \ run(config, three, endConfig(three.child, [three.child, three.child], [1])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.grandParent), ); config = oneEventLoopTestConfig(three); config.responderEnd.grandParent = {order: 0}; config.responderRelease.grandParent = {order: 1}; run(config, three, endConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); }); /** * If nothing is responder, then the negotiation should propagate directly to * the deepest target in the second touch. */ it('should negotiate with deepest target on second touch if nothing is responder', () => { // Initially nothing wants to become the responder let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.bubbled.parent = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.grandParent = { order: 3, returnVal: false, }; run(config, three, startConfig(three.parent, [three.parent], [0])); expect(ResponderEventPlugin._getResponder()).toBe(null); config = oneEventLoopTestConfig(three); // Now child wants to become responder. Negotiation should bubble as deep // as the target is because we don't find first common ancestor (with // current responder) because there is no current responder. // (Even if this is the second active touch). config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true}; config.responderGrant.child = {order: 4}; config.responderStart.child = {order: 5}; // / Two active touches \ /one of them new\ run( config, three, startConfig(three.child, [three.parent, three.child], [1]), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); // Now we remove the original first touch, keeping the second touch that // started within the current responder (child). Nothing changes because // there's still touches that started inside of the current responder. config = oneEventLoopTestConfig(three); config.responderEnd.child = {order: 0}; // / one ended\ /one remains \ run( config, three, endConfig(three.child, [three.parent, three.child], [0]), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); // Okay, now let's add back that first touch (nothing should change) and // then we'll try peeling back the touches in the opposite order to make // sure that first removing the second touch instantly causes responder to // be released. config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.bubbled.parent = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.grandParent = { order: 3, returnVal: false, }; // Interesting: child still gets moves even though touch target is parent! // Current responder gets a `responderStart` for any touch while responder. config.responderStart.child = {order: 4}; // / Two active touches \ /one of them new\ run( config, three, startConfig(three.parent, [three.child, three.parent], [1]), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); // Now, move that new touch that had no effect, and did not start within // the current responder. config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.moveShouldSetResponder.bubbled.parent = {order: 2, returnVal: false}; config.moveShouldSetResponder.bubbled.grandParent = { order: 3, returnVal: false, }; // Interesting: child still gets moves even though touch target is parent! // Current responder gets a `responderMove` for any touch while responder. config.responderMove.child = {order: 4}; // / Two active touches \ /one of them moved\ run( config, three, moveConfig(three.parent, [three.child, three.parent], [1]), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); config = oneEventLoopTestConfig(three); config.responderEnd.child = {order: 0}; config.responderRelease.child = {order: 1}; // /child end \ /parent remain\ run( config, three, endConfig(three.child, [three.child, three.parent], [0]), ); expect(ResponderEventPlugin._getResponder()).toBe(null); }); /** * If nothing is responder, then the negotiation should propagate directly to * the deepest target in the second touch. */ it('should negotiate until first common ancestor when there are siblings', () => { // Initially nothing wants to become the responder let config = oneEventLoopTestConfig(siblings); config.startShouldSetResponder.captured.parent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.childOne = { order: 1, returnVal: false, }; config.startShouldSetResponder.bubbled.childOne = { order: 2, returnVal: true, }; config.responderGrant.childOne = {order: 3}; config.responderStart.childOne = {order: 4}; run( config, siblings, startConfig(siblings.childOne, [siblings.childOne], [0]), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(siblings.childOne), ); // If the touch target is the sibling item, the negotiation should only // propagate to first common ancestor of current responder and sibling (so // the parent). config = oneEventLoopTestConfig(siblings); config.startShouldSetResponder.captured.parent = { order: 0, returnVal: false, }; config.startShouldSetResponder.bubbled.parent = { order: 1, returnVal: false, }; config.responderStart.childOne = {order: 2}; const touchConfig = startConfig( siblings.childTwo, [siblings.childOne, siblings.childTwo], [1], ); run(config, siblings, touchConfig); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(siblings.childOne), ); // move childOne config = oneEventLoopTestConfig(siblings); config.moveShouldSetResponder.captured.parent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.bubbled.parent = {order: 1, returnVal: false}; config.responderMove.childOne = {order: 2}; run( config, siblings, moveConfig( siblings.childOne, [siblings.childOne, siblings.childTwo], [0], ), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(siblings.childOne), ); // move childTwo: Only negotiates to `parent`. config = oneEventLoopTestConfig(siblings); config.moveShouldSetResponder.captured.parent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.bubbled.parent = {order: 1, returnVal: false}; config.responderMove.childOne = {order: 2}; run( config, siblings, moveConfig( siblings.childTwo, [siblings.childOne, siblings.childTwo], [1], ), ); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(siblings.childOne), ); }); it('should notify of being rejected. responderStart/Move happens on current responder', () => { // Initially nothing wants to become the responder let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true}; config.responderGrant.child = {order: 4}; config.responderStart.child = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); // Suppose parent wants to become responder on move, and is rejected config = oneEventLoopTestConfig(three); config.moveShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.moveShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.moveShouldSetResponder.bubbled.parent = {order: 2, returnVal: true}; config.responderGrant.parent = {order: 3}; config.responderTerminationRequest.child = {order: 4, returnVal: false}; config.responderReject.parent = {order: 5}; // The start/move should occur on the original responder if new one is rejected config.responderMove.child = {order: 6}; let touchConfig = moveConfig(three.child, [three.child], [0]); run(config, three, touchConfig); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.bubbled.parent = {order: 2, returnVal: true}; config.responderGrant.parent = {order: 3}; config.responderTerminationRequest.child = {order: 4, returnVal: false}; config.responderReject.parent = {order: 5}; // The start/move should occur on the original responder if new one is rejected config.responderStart.child = {order: 6}; touchConfig = startConfig(three.child, [three.child, three.child], [1]); run(config, three, touchConfig); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); }); it('should negotiate scroll', () => { // Initially nothing wants to become the responder let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true}; config.responderGrant.child = {order: 4}; config.responderStart.child = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); // If the touch target is the sibling item, the negotiation should only // propagate to first common ancestor of current responder and sibling (so // the parent). config = oneEventLoopTestConfig(three); config.scrollShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.scrollShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.scrollShouldSetResponder.bubbled.parent = { order: 2, returnVal: true, }; config.responderGrant.parent = {order: 3}; config.responderTerminationRequest.child = {order: 4, returnVal: false}; config.responderReject.parent = {order: 5}; run(config, three, { topLevelType: 'topScroll', targetInst: getInstanceFromNode(three.parent), nativeEvent: {}, }); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); // Now lets let the scroll take control this time. config = oneEventLoopTestConfig(three); config.scrollShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.scrollShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.scrollShouldSetResponder.bubbled.parent = { order: 2, returnVal: true, }; config.responderGrant.parent = {order: 3}; config.responderTerminationRequest.child = {order: 4, returnVal: true}; config.responderTerminate.child = {order: 5}; run(config, three, { topLevelType: 'topScroll', targetInst: getInstanceFromNode(three.parent), nativeEvent: {}, }); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent), ); }); it('should cancel correctly', () => { // Initially our child becomes responder let config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false, }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false, }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false, }; config.startShouldSetResponder.bubbled.child = {order: 3, returnVal: true}; config.responderGrant.child = {order: 4}; config.responderStart.child = {order: 5}; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child), ); config = oneEventLoopTestConfig(three); config.responderEnd.child = {order: 0}; config.responderTerminate.child = {order: 1}; const nativeEvent = _touchConfig( 'topTouchCancel', three.child, [three.child], [0], ); run(config, three, nativeEvent); expect(ResponderEventPlugin._getResponder()).toBe(null); }); it('should determine the first common ancestor correctly', () => { // This test was moved here from the ReactTreeTraversal test since only the // ResponderEventPlugin uses `getLowestCommonAncestor` const React = require('react'); const ReactTestUtils = require('react-dom/test-utils'); const getLowestCommonAncestor = require('react-native-renderer/src/legacy-events/ResponderEventPlugin').getLowestCommonAncestor; // This works by accident and will likely break in the future. const ReactDOMComponentTree = require('react-dom-bindings/src/client/ReactDOMComponentTree'); class ChildComponent extends React.Component { divRef = React.createRef(); div1Ref = React.createRef(); div2Ref = React.createRef(); render() { return ( <div ref={this.divRef} id={this.props.id + '__DIV'}> <div ref={this.div1Ref} id={this.props.id + '__DIV_1'} /> <div ref={this.div2Ref} id={this.props.id + '__DIV_2'} /> </div> ); } } class ParentComponent extends React.Component { pRef = React.createRef(); p_P1Ref = React.createRef(); p_P1_C1Ref = React.createRef(); p_P1_C2Ref = React.createRef(); p_OneOffRef = React.createRef(); render() { return ( <div ref={this.pRef} id="P"> <div ref={this.p_P1Ref} id="P_P1"> <ChildComponent ref={this.p_P1_C1Ref} id="P_P1_C1" /> <ChildComponent ref={this.p_P1_C2Ref} id="P_P1_C2" /> </div> <div ref={this.p_OneOffRef} id="P_OneOff" /> </div> ); } } const parent = ReactTestUtils.renderIntoDocument(<ParentComponent />); const ancestors = [ // Common ancestor with self is self. { one: parent.p_P1_C1Ref.current.div1Ref.current, two: parent.p_P1_C1Ref.current.div1Ref.current, com: parent.p_P1_C1Ref.current.div1Ref.current, }, // Common ancestor with self is self - even if topmost DOM. { one: parent.pRef.current, two: parent.pRef.current, com: parent.pRef.current, }, // Siblings { one: parent.p_P1_C1Ref.current.div1Ref.current, two: parent.p_P1_C1Ref.current.div2Ref.current, com: parent.p_P1_C1Ref.current.divRef.current, }, // Common ancestor with parent is the parent. { one: parent.p_P1_C1Ref.current.div1Ref.current, two: parent.p_P1_C1Ref.current.divRef.current, com: parent.p_P1_C1Ref.current.divRef.current, }, // Common ancestor with grandparent is the grandparent. { one: parent.p_P1_C1Ref.current.div1Ref.current, two: parent.p_P1Ref.current, com: parent.p_P1Ref.current, }, // Grandparent across subcomponent boundaries. { one: parent.p_P1_C1Ref.current.div1Ref.current, two: parent.p_P1_C2Ref.current.div1Ref.current, com: parent.p_P1Ref.current, }, // Something deep with something one-off. { one: parent.p_P1_C1Ref.current.div1Ref.current, two: parent.p_OneOffRef.current, com: parent.pRef.current, }, ]; let i; for (i = 0; i < ancestors.length; i++) { const plan = ancestors[i]; const firstCommon = getLowestCommonAncestor( ReactDOMComponentTree.getInstanceFromNode(plan.one), ReactDOMComponentTree.getInstanceFromNode(plan.two), ); expect(firstCommon).toBe( ReactDOMComponentTree.getInstanceFromNode(plan.com), ); } }); });
32.652965
102
0.66674
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'; module.exports = function dynamicImports() { return { name: 'scripts/rollup/plugins/dynamic-imports', renderDynamicImport({targetModuleId}) { if (targetModuleId === null) { return {left: 'import(', right: ')'}; } return null; }, }; };
23.2
66
0.637681
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. */ /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. * * Note that this module is currently shared and assumed to be stateless. * If this becomes an actual Map, that will break. */ /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ export function remove(key) { key._reactInternals = undefined; } export function get(key) { return key._reactInternals; } export function has(key) { return key._reactInternals !== undefined; } export function set(key, value) { key._reactInternals = value; }
26.394737
78
0.725962
null
'use strict'; module.exports = { rules: { 'no-primitive-constructors': require('./no-primitive-constructors'), 'no-to-warn-dev-within-to-throw': require('./no-to-warn-dev-within-to-throw'), 'warning-args': require('./warning-args'), 'prod-error-codes': require('./prod-error-codes'), 'no-production-logging': require('./no-production-logging'), 'safe-string-coercion': require('./safe-string-coercion'), }, };
32.846154
82
0.653759
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 {LazyComponent} from 'react/src/ReactLazy'; import type {ReactContext, ReactProviderType} from 'shared/ReactTypes'; import { REACT_CONTEXT_TYPE, REACT_FORWARD_REF_TYPE, REACT_FRAGMENT_TYPE, REACT_PORTAL_TYPE, REACT_MEMO_TYPE, REACT_PROFILER_TYPE, REACT_PROVIDER_TYPE, REACT_STRICT_MODE_TYPE, REACT_SUSPENSE_TYPE, REACT_SUSPENSE_LIST_TYPE, REACT_LAZY_TYPE, REACT_CACHE_TYPE, REACT_TRACING_MARKER_TYPE, REACT_SERVER_CONTEXT_TYPE, } from 'shared/ReactSymbols'; import { enableServerContext, enableTransitionTracing, enableCache, } from './ReactFeatureFlags'; // Keep in sync with react-reconciler/getComponentNameFromFiber function getWrappedName( outerType: mixed, innerType: any, wrapperName: string, ): string { const displayName = (outerType: any).displayName; if (displayName) { return displayName; } const functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? `${wrapperName}(${functionName})` : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type: ReactContext<any>) { return type.displayName || 'Context'; } const REACT_CLIENT_REFERENCE = Symbol.for('react.client.reference'); // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. export default function getComponentNameFromType(type: mixed): string | null { if (type == null) { // Host root, text node or just invalid type. return null; } if (typeof type === 'function') { if ((type: any).$$typeof === REACT_CLIENT_REFERENCE) { // TODO: Create a convention for naming client references with debug info. return null; } return (type: any).displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; case REACT_CACHE_TYPE: if (enableCache) { return 'Cache'; } // Fall through case REACT_TRACING_MARKER_TYPE: if (enableTransitionTracing) { return 'TracingMarker'; } } if (typeof type === 'object') { if (__DEV__) { if (typeof (type: any).tag === 'number') { console.error( 'Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.', ); } } switch (type.$$typeof) { case REACT_CONTEXT_TYPE: const context: ReactContext<any> = (type: any); return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: const provider: ReactProviderType<any> = (type: any); return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: const outerName = (type: any).displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { const lazyComponent: LazyComponent<any, any> = (type: any); const payload = lazyComponent._payload; const init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } case REACT_SERVER_CONTEXT_TYPE: if (enableServerContext) { const context2 = ((type: any): ReactContext<any>); return (context2.displayName || context2._globalName) + '.Provider'; } } } return null; }
28.791367
103
0.647826
null
#!/usr/bin/env node 'use strict'; const clear = require('clear'); const {existsSync} = require('fs'); const {readJsonSync} = require('fs-extra'); const {join} = require('path'); const theme = require('../theme'); const {execRead} = require('../utils'); const run = async ({cwd, packages, tags}) => { // Tags are named after the react version. const {version} = readJsonSync( `${cwd}/build/node_modules/react/package.json` ); clear(); if (tags.length === 1 && tags[0] === 'next') { console.log( theme`{header A "next" release} {version ${version}} {header has been published!}` ); } else if (tags.length === 1 && tags[0] === 'experimental') { console.log( theme`{header An "experimental" release} {version ${version}} {header has been published!}` ); } else { const nodeModulesPath = join(cwd, 'build/node_modules'); console.log( theme.caution`The release has been published but you're not done yet!` ); if (tags.includes('latest')) { // All packages are built from a single source revision, // so it is safe to read build info from any one of them. const arbitraryPackageName = packages[0]; // FIXME: New build script does not output build-info.json. It's only used // by this post-publish print job, and only for "latest" releases, so I've // disabled it as a workaround so the publish script doesn't crash for // "next" and "experimental" pre-releases. const {commit} = readJsonSync( join( cwd, 'build', 'node_modules', arbitraryPackageName, 'build-info.json' ) ); console.log(); console.log( theme.header`Please review and commit all local, staged changes.` ); console.log(); console.log('Version numbers have been updated in the following files:'); for (let i = 0; i < packages.length; i++) { const packageName = packages[i]; console.log(theme.path`• packages/%s/package.json`, packageName); } const status = await execRead( 'git diff packages/shared/ReactVersion.js', {cwd} ); if (status) { console.log(theme.path`• packages/shared/ReactVersion.js`); } console.log(); console.log( theme`{header Don't forget to also update and commit the }{path CHANGELOG}` ); // Prompt the release engineer to tag the commit and update the CHANGELOG. // (The script could automatically do this, but this seems safer.) console.log(); console.log( theme.header`Tag the source for this release in Git with the following command:` ); console.log( theme` {command git tag -a v}{version %s} {command -m "v%s"} {version %s}`, version, version, commit ); console.log(theme.command` git push origin --tags`); console.log(); console.log(theme.header`Lastly, please fill in the release on GitHub.`); console.log( theme.link`https://github.com/facebook/react/releases/tag/v%s`, version ); console.log( theme`\nThe GitHub release should also include links to the following artifacts:` ); for (let i = 0; i < packages.length; i++) { const packageName = packages[i]; if (existsSync(join(nodeModulesPath, packageName, 'umd'))) { const {version: packageVersion} = readJsonSync( join(nodeModulesPath, packageName, 'package.json') ); console.log( theme`{path • %s:} {link https://unpkg.com/%s@%s/umd/}`, packageName, packageName, packageVersion ); } } // Update reactjs.org so the React version shown in the header is up to date. console.log(); console.log( theme.header`Once you've pushed changes, update the docs site.` ); console.log( 'This will ensure that any newly-added error codes can be decoded.' ); console.log(); } } }; module.exports = run;
30.669231
97
0.593294
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=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhDdXN0b21Ib29rLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiLCJpc0RhcmtNb2RlIiwidXNlSXNEYXJrTW9kZSIsImZvbyIsInVzZUZvbyIsImhhbmRsZUNsaWNrIiwidXNlRWZmZWN0Q3JlYXRlIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7Ozs7Ozs7O0FBRU8sU0FBU0EsU0FBVCxHQUFxQjtBQUMxQixRQUFNLENBQUNDLEtBQUQsRUFBUUMsUUFBUixJQUFvQixxQkFBUyxDQUFULENBQTFCO0FBQ0EsUUFBTUMsVUFBVSxHQUFHQyxhQUFhLEVBQWhDO0FBQ0EsUUFBTTtBQUFDQyxJQUFBQTtBQUFELE1BQVFDLE1BQU0sRUFBcEI7QUFFQSx3QkFBVSxNQUFNLENBQ2Q7QUFDRCxHQUZELEVBRUcsRUFGSDs7QUFJQSxRQUFNQyxXQUFXLEdBQUcsTUFBTUwsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUFsQzs7QUFFQSxzQkFDRSx5RUFDRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFBaUJFLFVBQWpCLENBREYsZUFFRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFBYUYsS0FBYixDQUZGLGVBR0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FBV0ksR0FBWCxDQUhGLGVBSUU7QUFBUSxJQUFBLE9BQU8sRUFBRUUsV0FBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsb0JBSkYsQ0FERjtBQVFEOztBQUVELFNBQVNILGFBQVQsR0FBeUI7QUFDdkIsUUFBTSxDQUFDRCxVQUFELElBQWUscUJBQVMsS0FBVCxDQUFyQjtBQUVBLHdCQUFVLFNBQVNLLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU9MLFVBQVA7QUFDRDs7QUFFRCxTQUFTRyxNQUFULEdBQWtCO0FBQ2hCLDRCQUFjLEtBQWQ7QUFDQSxTQUFPO0FBQUNELElBQUFBLEdBQUcsRUFBRTtBQUFOLEdBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QsIHt1c2VEZWJ1Z1ZhbHVlLCB1c2VFZmZlY3QsIHVzZVN0YXRlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IFtjb3VudCwgc2V0Q291bnRdID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGlzRGFya01vZGUgPSB1c2VJc0RhcmtNb2RlKCk7XG4gIGNvbnN0IHtmb299ID0gdXNlRm9vKCk7XG5cbiAgdXNlRWZmZWN0KCgpID0+IHtcbiAgICAvLyAuLi5cbiAgfSwgW10pO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gKCkgPT4gc2V0Q291bnQoY291bnQgKyAxKTtcblxuICByZXR1cm4gKFxuICAgIDw+XG4gICAgICA8ZGl2PkRhcmsgbW9kZT8ge2lzRGFya01vZGV9PC9kaXY+XG4gICAgICA8ZGl2PkNvdW50OiB7Y291bnR9PC9kaXY+XG4gICAgICA8ZGl2PkZvbzoge2Zvb308L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSB1c2VTdGF0ZShmYWxzZSk7XG5cbiAgdXNlRWZmZWN0KGZ1bmN0aW9uIHVzZUVmZmVjdENyZWF0ZSgpIHtcbiAgICAvLyBIZXJlIGlzIHdoZXJlIHdlIG1heSBsaXN0ZW4gdG8gYSBcInRoZW1lXCIgZXZlbnQuLi5cbiAgfSwgW10pO1xuXG4gIHJldHVybiBpc0RhcmtNb2RlO1xufVxuXG5mdW5jdGlvbiB1c2VGb28oKSB7XG4gIHVzZURlYnVnVmFsdWUoJ2ZvbycpO1xuICByZXR1cm4ge2ZvbzogdHJ1ZX07XG59XG4iXSwieF9mYWNlYm9va19zb3VyY2VzIjpbW251bGwsW3sibmFtZXMiOlsiPG5vLWhvb2s+IiwiY291bnQiLCJpc0RhcmtNb2RlIl0sIm1hcHBpbmdzIjoiQ0FBRDthNEJDQSxBV0RBO2NsQkVBLEFlRkE7a0NiRUEifV1dXX0=
77.382353
2,848
0.824357
cybersecurity-penetration-testing
'use strict'; function checkDCE() { /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' ) { return; } if (process.env.NODE_ENV !== 'production') { // This branch is unreachable because this function is only called // in production, but the condition is true only in development. // Therefore if the branch is still here, dead code elimination wasn't // properly applied. // Don't change the message. React DevTools relies on it. Also make sure // this message doesn't occur elsewhere in this function, or it will cause // a false positive. throw new Error('^_^'); } try { // Verify that the code above has been dead code eliminated (DCE'd). __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); } catch (err) { // DevTools shouldn't crash React, no matter what. // We should still report in case we break this code. console.error(err); } } if (process.env.NODE_ENV === 'production') { // DCE check should happen before ReactDOM bundle executes so that // DevTools can report bad minification during injection. checkDCE(); module.exports = require('./cjs/react-dom.production.min.js'); } else { module.exports = require('./cjs/react-dom.development.js'); }
33.974359
78
0.67058
null
#!/usr/bin/env node 'use strict'; const clear = require('clear'); const {join, relative} = require('path'); const theme = require('../theme'); module.exports = ({cwd}, isStableRelease) => { const publishPath = relative( process.env.PWD, join(__dirname, '../publish.js') ); clear(); let message; if (isStableRelease) { message = theme` {caution A stable release candidate has been prepared!} You can review the contents of this release in {path build/node_modules/} {header Before publishing, consider testing this release locally with create-react-app!} You can publish this release by running: {path ${publishPath}} `; } else { message = theme` {caution A "next" release candidate has been prepared!} You can review the contents of this release in {path build/node_modules/} You can publish this release by running: {path ${publishPath}} `; } console.log(message.replace(/\n +/g, '\n').trim()); };
23.02381
94
0.640873
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 { Thenable, PendingThenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; import {getWorkInProgressRoot} from './ReactFiberWorkLoop'; import ReactSharedInternals from 'shared/ReactSharedInternals'; const {ReactCurrentActQueue} = ReactSharedInternals; export opaque type ThenableState = Array<Thenable<any>>; // An error that is thrown (e.g. by `use`) to trigger Suspense. If we // detect this is caught by userspace, we'll log a warning in development. export const SuspenseException: mixed = new Error( "Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`", ); export const SuspenseyCommitException: mixed = new Error( 'Suspense Exception: This is not a real error, and should not leak into ' + "userspace. If you're seeing this, it's likely a bug in React.", ); // This is a noop thenable that we use to trigger a fallback in throwException. // TODO: It would be better to refactor throwException into multiple functions // so we can trigger a fallback directly without having to check the type. But // for now this will do. export const noopSuspenseyCommitThenable = { then() { if (__DEV__) { console.error( 'Internal React error: A listener was unexpectedly attached to a ' + '"noop" thenable. This is a bug in React. Please file an issue.', ); } }, }; export function createThenableState(): ThenableState { // The ThenableState is created the first time a component suspends. If it // suspends again, we'll reuse the same state. return []; } export function isThenableResolved(thenable: Thenable<mixed>): boolean { const status = thenable.status; return status === 'fulfilled' || status === 'rejected'; } function noop(): void {} export function trackUsedThenable<T>( thenableState: ThenableState, thenable: Thenable<T>, index: number, ): T { if (__DEV__ && ReactCurrentActQueue.current !== null) { ReactCurrentActQueue.didUsePromise = true; } const previous = thenableState[index]; if (previous === undefined) { thenableState.push(thenable); } else { if (previous !== thenable) { // Reuse the previous thenable, and drop the new one. We can assume // they represent the same value, because components are idempotent. // Avoid an unhandled rejection errors for the Promises that we'll // intentionally ignore. thenable.then(noop, noop); thenable = previous; } } // We use an expando to track the status and result of a thenable so that we // can synchronously unwrap the value. Think of this as an extension of the // Promise API, or a custom interface that is a superset of Thenable. // // If the thenable doesn't have a status, set it to "pending" and attach // a listener that will update its status and result when it resolves. switch (thenable.status) { case 'fulfilled': { const fulfilledValue: T = thenable.value; return fulfilledValue; } case 'rejected': { const rejectedError = thenable.reason; checkIfUseWrappedInAsyncCatch(rejectedError); throw rejectedError; } default: { if (typeof thenable.status === 'string') { // Only instrument the thenable if the status if not defined. If // it's defined, but an unknown value, assume it's been instrumented by // some custom userspace implementation. We treat it as "pending". // Attach a dummy listener, to ensure that any lazy initialization can // happen. Flight lazily parses JSON when the value is actually awaited. thenable.then(noop, noop); } else { // This is an uncached thenable that we haven't seen before. // Detect infinite ping loops caused by uncached promises. const root = getWorkInProgressRoot(); if (root !== null && root.shellSuspendCounter > 100) { // This root has suspended repeatedly in the shell without making any // progress (i.e. committing something). This is highly suggestive of // an infinite ping loop, often caused by an accidental Async Client // Component. // // During a transition, we can suspend the work loop until the promise // to resolve, but this is a sync render, so that's not an option. We // also can't show a fallback, because none was provided. So our last // resort is to throw an error. // // TODO: Remove this error in a future release. Other ways of handling // this case include forcing a concurrent render, or putting the whole // root into offscreen mode. throw new Error( 'async/await is not yet supported in Client Components, only ' + 'Server Components. This error is often caused by accidentally ' + "adding `'use client'` to a module that was originally written " + 'for the server.', ); } const pendingThenable: PendingThenable<T> = (thenable: any); pendingThenable.status = 'pending'; pendingThenable.then( fulfilledValue => { if (thenable.status === 'pending') { const fulfilledThenable: FulfilledThenable<T> = (thenable: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = fulfilledValue; } }, (error: mixed) => { if (thenable.status === 'pending') { const rejectedThenable: RejectedThenable<T> = (thenable: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; } }, ); // Check one more time in case the thenable resolved synchronously. switch (thenable.status) { case 'fulfilled': { const fulfilledThenable: FulfilledThenable<T> = (thenable: any); return fulfilledThenable.value; } case 'rejected': { const rejectedThenable: RejectedThenable<T> = (thenable: any); const rejectedError = rejectedThenable.reason; checkIfUseWrappedInAsyncCatch(rejectedError); throw rejectedError; } } } // Suspend. // // Throwing here is an implementation detail that allows us to unwind the // call stack. But we shouldn't allow it to leak into userspace. Throw an // opaque placeholder value instead of the actual thenable. If it doesn't // get captured by the work loop, log a warning, because that means // something in userspace must have caught it. suspendedThenable = thenable; if (__DEV__) { needsToResetSuspendedThenableDEV = true; } throw SuspenseException; } } } export function suspendCommit(): void { // This extra indirection only exists so it can handle passing // noopSuspenseyCommitThenable through to throwException. // TODO: Factor the thenable check out of throwException suspendedThenable = noopSuspenseyCommitThenable; throw SuspenseyCommitException; } // This is used to track the actual thenable that suspended so it can be // passed to the rest of the Suspense implementation — which, for historical // reasons, expects to receive a thenable. let suspendedThenable: Thenable<any> | null = null; let needsToResetSuspendedThenableDEV = false; export function getSuspendedThenable(): Thenable<mixed> { // This is called right after `use` suspends by throwing an exception. `use` // throws an opaque value instead of the thenable itself so that it can't be // caught in userspace. Then the work loop accesses the actual thenable using // this function. if (suspendedThenable === null) { throw new Error( 'Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.', ); } const thenable = suspendedThenable; suspendedThenable = null; if (__DEV__) { needsToResetSuspendedThenableDEV = false; } return thenable; } export function checkIfUseWrappedInTryCatch(): boolean { if (__DEV__) { // This was set right before SuspenseException was thrown, and it should // have been cleared when the exception was handled. If it wasn't, // it must have been caught by userspace. if (needsToResetSuspendedThenableDEV) { needsToResetSuspendedThenableDEV = false; return true; } } return false; } export function checkIfUseWrappedInAsyncCatch(rejectedReason: any) { // This check runs in prod, too, because it prevents a more confusing // downstream error, where SuspenseException is caught by a promise and // thrown asynchronously. // TODO: Another way to prevent SuspenseException from leaking into an async // execution context is to check the dispatcher every time `use` is called, // or some equivalent. That might be preferable for other reasons, too, since // it matches how we prevent similar mistakes for other hooks. if (rejectedReason === SuspenseException) { throw new Error( 'Hooks are not supported inside an async component. This ' + "error is often caused by accidentally adding `'use client'` " + 'to a module that was originally written for the server.', ); } }
37.862745
80
0.669795
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 './ReactNativeInjectionShared'; import { getFiberCurrentPropsFromNode, getInstanceFromNode, getNodeFromInstance, } from './ReactNativeComponentTree'; import {setComponentTree} from './legacy-events/EventPluginUtils'; import {receiveEvent, receiveTouches} from './ReactNativeEventEmitter'; import ReactNativeGlobalResponderHandler from './ReactNativeGlobalResponderHandler'; import ResponderEventPlugin from './legacy-events/ResponderEventPlugin'; // Module provided by RN: import {RCTEventEmitter} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; /** * Register the event emitter with the native bridge */ RCTEventEmitter.register({ receiveEvent, receiveTouches, }); setComponentTree( getFiberCurrentPropsFromNode, getInstanceFromNode, getNodeFromInstance, ); ResponderEventPlugin.injection.injectGlobalResponderHandler( ReactNativeGlobalResponderHandler, );
25.642857
96
0.794275
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. */ 'use strict'; // Mock of the Native Hooks // Map of viewTag -> {children: [childTag], parent: ?parentTag} const roots = []; const views = new Map(); function autoCreateRoot(tag) { // Seriously, this is how we distinguish roots in RN. if (!views.has(tag) && tag % 10 === 1) { roots.push(tag); views.set(tag, { children: [], parent: null, props: {}, viewName: '<native root>', }); } } function insertSubviewAtIndex(parent, child, index) { const parentInfo = views.get(parent); const childInfo = views.get(child); if (childInfo.parent !== null) { throw new Error( `Inserting view ${child} ${JSON.stringify( childInfo.props, )} which already has parent`, ); } if (0 > index || index > parentInfo.children.length) { throw new Error( `Invalid index ${index} for children ${parentInfo.children}`, ); } parentInfo.children.splice(index, 0, child); childInfo.parent = parent; } function removeChild(parent, child) { const parentInfo = views.get(parent); const childInfo = views.get(child); const index = parentInfo.children.indexOf(child); if (index < 0) { throw new Error(`Missing view ${child} during removal`); } parentInfo.children.splice(index, 1); childInfo.parent = null; } const RCTUIManager = { __dumpHierarchyForJestTestsOnly: function () { function dumpSubtree(tag, indent) { const info = views.get(tag); let out = ''; out += ' '.repeat(indent) + info.viewName + ' ' + JSON.stringify(info.props); // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const child of info.children) { out += '\n' + dumpSubtree(child, indent + 2); } return out; } return roots.map(tag => dumpSubtree(tag, 0)).join('\n'); }, clearJSResponder: jest.fn(), createView: jest.fn(function createView(reactTag, viewName, rootTag, props) { if (views.has(reactTag)) { throw new Error(`Created two native views with tag ${reactTag}`); } views.set(reactTag, { children: [], parent: null, props: props, viewName: viewName, }); }), dispatchViewManagerCommand: jest.fn(), sendAccessibilityEvent: jest.fn(), setJSResponder: jest.fn(), setChildren: jest.fn(function setChildren(parentTag, reactTags) { autoCreateRoot(parentTag); // Native doesn't actually check this but it seems like a good idea if (views.get(parentTag).children.length !== 0) { throw new Error(`Calling .setChildren on nonempty view ${parentTag}`); } // This logic ported from iOS (RCTUIManager.m) reactTags.forEach((tag, i) => { insertSubviewAtIndex(parentTag, tag, i); }); }), manageChildren: jest.fn(function manageChildren( parentTag, moveFromIndices = [], moveToIndices = [], addChildReactTags = [], addAtIndices = [], removeAtIndices = [], ) { autoCreateRoot(parentTag); // This logic ported from iOS (RCTUIManager.m) if (moveFromIndices.length !== moveToIndices.length) { throw new Error( `Mismatched move indices ${moveFromIndices} and ${moveToIndices}`, ); } if (addChildReactTags.length !== addAtIndices.length) { throw new Error( `Mismatched add indices ${addChildReactTags} and ${addAtIndices}`, ); } const parentInfo = views.get(parentTag); const permanentlyRemovedChildren = removeAtIndices.map( index => parentInfo.children[index], ); const temporarilyRemovedChildren = moveFromIndices.map( index => parentInfo.children[index], ); permanentlyRemovedChildren.forEach(tag => removeChild(parentTag, tag)); temporarilyRemovedChildren.forEach(tag => removeChild(parentTag, tag)); permanentlyRemovedChildren.forEach(tag => { views.delete(tag); }); // List of [index, tag] const indicesToInsert = []; temporarilyRemovedChildren.forEach((tag, i) => { indicesToInsert.push([moveToIndices[i], temporarilyRemovedChildren[i]]); }); addChildReactTags.forEach((tag, i) => { indicesToInsert.push([addAtIndices[i], addChildReactTags[i]]); }); indicesToInsert.sort((a, b) => a[0] - b[0]); // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const [i, tag] of indicesToInsert) { insertSubviewAtIndex(parentTag, tag, i); } }), updateView: jest.fn(), removeSubviewsFromContainerWithID: jest.fn(function (parentTag) { views.get(parentTag).children.forEach(tag => removeChild(parentTag, tag)); }), replaceExistingNonRootView: jest.fn(), measure: jest.fn(function measure(tag, callback) { if (typeof tag !== 'number') { throw new Error(`Expected tag to be a number, was passed ${tag}`); } callback(10, 10, 100, 100, 0, 0); }), measureInWindow: jest.fn(function measureInWindow(tag, callback) { if (typeof tag !== 'number') { throw new Error(`Expected tag to be a number, was passed ${tag}`); } callback(10, 10, 100, 100); }), measureLayout: jest.fn( function measureLayout(tag, relativeTag, fail, success) { if (typeof tag !== 'number') { throw new Error(`Expected tag to be a number, was passed ${tag}`); } if (typeof relativeTag !== 'number') { throw new Error( `Expected relativeTag to be a number, was passed ${relativeTag}`, ); } success(1, 1, 100, 100); }, ), __takeSnapshot: jest.fn(), }; module.exports = RCTUIManager;
28.369231
79
0.63657
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 ReactDOMClient; let act; let waitForAll; describe('ReactDOMHooks', () => { let container; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); act = require('internal-test-utils').act; waitForAll = require('internal-test-utils').waitForAll; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); }); it('can ReactDOM.render() from useEffect', async () => { const container2 = document.createElement('div'); const container3 = document.createElement('div'); function Example1({n}) { React.useEffect(() => { ReactDOM.render(<Example2 n={n} />, container2); }); return 1 * n; } function Example2({n}) { React.useEffect(() => { ReactDOM.render(<Example3 n={n} />, container3); }); return 2 * n; } function Example3({n}) { return 3 * n; } ReactDOM.render(<Example1 n={1} />, container); expect(container.textContent).toBe('1'); expect(container2.textContent).toBe(''); expect(container3.textContent).toBe(''); await waitForAll([]); expect(container.textContent).toBe('1'); expect(container2.textContent).toBe('2'); expect(container3.textContent).toBe('3'); ReactDOM.render(<Example1 n={2} />, container); expect(container.textContent).toBe('2'); expect(container2.textContent).toBe('2'); // Not flushed yet expect(container3.textContent).toBe('3'); // Not flushed yet await waitForAll([]); expect(container.textContent).toBe('2'); expect(container2.textContent).toBe('4'); expect(container3.textContent).toBe('6'); }); it('should not bail out when an update is scheduled from within an event handler', () => { const {createRef, useCallback, useState} = React; const Example = ({inputRef, labelRef}) => { const [text, setText] = useState(''); const handleInput = useCallback(event => { setText(event.target.value); }); return ( <> <input ref={inputRef} onInput={handleInput} /> <label ref={labelRef}>{text}</label> </> ); }; const inputRef = createRef(); const labelRef = createRef(); ReactDOM.render( <Example inputRef={inputRef} labelRef={labelRef} />, container, ); inputRef.current.value = 'abc'; inputRef.current.dispatchEvent( new Event('input', {bubbles: true, cancelable: true}), ); expect(labelRef.current.innerHTML).toBe('abc'); }); it('should not bail out when an update is scheduled from within an event handler in Concurrent Mode', async () => { const {createRef, useCallback, useState} = React; const Example = ({inputRef, labelRef}) => { const [text, setText] = useState(''); const handleInput = useCallback(event => { setText(event.target.value); }); return ( <> <input ref={inputRef} onInput={handleInput} /> <label ref={labelRef}>{text}</label> </> ); }; const inputRef = createRef(); const labelRef = createRef(); const root = ReactDOMClient.createRoot(container); root.render(<Example inputRef={inputRef} labelRef={labelRef} />); await waitForAll([]); inputRef.current.value = 'abc'; await act(() => { inputRef.current.dispatchEvent( new Event('input', { bubbles: true, cancelable: true, }), ); }); expect(labelRef.current.innerHTML).toBe('abc'); }); });
25.353333
117
0.607794
PenetrationTestingScripts
/* global chrome */ import setExtensionIconAndPopup from './setExtensionIconAndPopup'; import {executeScriptInMainWorld} from './executeScript'; import {EXTENSION_CONTAINED_VERSIONS} from '../utils'; export function handleReactDevToolsHookMessage(message, sender) { const {payload} = message; switch (payload?.type) { case 'react-renderer-attached': { setExtensionIconAndPopup(payload.reactBuildType, sender.tab.id); break; } } } export function handleBackendManagerMessage(message, sender) { const {payload} = message; switch (payload?.type) { case 'require-backends': { payload.versions.forEach(version => { if (EXTENSION_CONTAINED_VERSIONS.includes(version)) { executeScriptInMainWorld({ target: {tabId: sender.tab.id}, files: [`/build/react_devtools_backend_${version}.js`], }); } }); break; } } } export function handleDevToolsPageMessage(message) { const {payload} = message; switch (payload?.type) { // Proxy this message from DevTools page to content script via chrome.tabs.sendMessage case 'fetch-file-with-cache': { const { payload: {tabId, url}, } = message; if (!tabId) { throw new Error("Couldn't fetch file sources: tabId not specified"); } if (!url) { throw new Error("Couldn't fetch file sources: url not specified"); } chrome.tabs.sendMessage(tabId, { source: 'devtools-page', payload: { type: 'fetch-file-with-cache', url, }, }); break; } case 'inject-backend-manager': { const { payload: {tabId}, } = message; if (!tabId) { throw new Error("Couldn't inject backend manager: tabId not specified"); } executeScriptInMainWorld({ target: {tabId}, files: ['/build/backendManager.js'], }); break; } } } export function handleFetchResourceContentScriptMessage(message) { const {payload} = message; switch (payload?.type) { case 'fetch-file-with-cache-complete': case 'fetch-file-with-cache-error': // Forward the result of fetch-in-page requests back to the DevTools page. // We switch the source here because of inconsistency between Firefox and Chrome // In Chromium this message will be propagated from content script to DevTools page // For Firefox, only background script will get this message, so we need to forward it to DevTools page chrome.runtime.sendMessage({ source: 'react-devtools-background', payload, }); break; } }
24.740385
109
0.626308
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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkV4YW1wbGUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJzZXRDb3VudCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50LCBzZXRDb3VudF0gPSB1c2VTdGF0ZSgwKTtcblxuICByZXR1cm4gKFxuICAgIDxkaXY+XG4gICAgICA8cD5Zb3UgY2xpY2tlZCB7Y291bnR9IHRpbWVzPC9wPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXsoKSA9PiBzZXRDb3VudChjb3VudCArIDEpfT5DbGljayBtZTwvYnV0dG9uPlxuICAgIDwvZGl2PlxuICApO1xufVxuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiIsImNvdW50Il0sIm1hcHBpbmdzIjoiQ0FBRDthNEJDQSxBV0RBIn1dXV19
79.589744
1,384
0.796308
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 node */ // This is a regression test for https://github.com/facebook/react/issues/13188. // It reproduces a combination of conditions that led to a problem. if (global.window) { throw new Error('This test must run in a Node environment.'); } // The issue only reproduced when React was loaded before JSDOM. const React = require('react'); const ReactDOM = require('react-dom'); // Initialize JSDOM separately. // We don't use our normal JSDOM setup because we want to load React first. const {JSDOM} = require('jsdom'); global.requestAnimationFrame = setTimeout; global.cancelAnimationFrame = clearTimeout; const jsdom = new JSDOM(`<div id="app-root"></div>`); global.window = jsdom.window; global.document = jsdom.window.document; global.navigator = jsdom.window.navigator; class Bad extends React.Component { componentDidUpdate() { throw new Error('no'); } render() { return null; } } describe('ReactErrorLoggingRecovery', () => { const originalConsoleError = console.error; beforeEach(() => { console.error = error => { if ( typeof error === 'string' && error.includes('ReactDOM.render is no longer supported in React 18') ) { // Ignore legacy root deprecation warning return; } throw new Error('Buggy console.error'); }; }); afterEach(() => { console.error = originalConsoleError; }); it('should recover from errors in console.error', function () { const div = document.createElement('div'); let didCatch = false; try { ReactDOM.render(<Bad />, div); ReactDOM.render(<Bad />, div); } catch (e) { expect(e.message).toBe('no'); didCatch = true; } expect(didCatch).toBe(true); ReactDOM.render(<span>Hello</span>, div); expect(div.firstChild.textContent).toBe('Hello'); // Verify the console.error bug is surfaced expect(() => { jest.runAllTimers(); }).toThrow('Buggy console.error'); }); });
26.308642
80
0.658526
owtf
/** @license React v0.14.10 * react-jsx-dev-runtime.production.min.js * * 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';require("react");exports.Fragment=60107;if("function"===typeof Symbol&&Symbol.for){var a=Symbol.for;exports.Fragment=a("react.fragment")}exports.jsxDEV=void 0;
42.5
172
0.735023
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-flight.production.min.js'); } else { module.exports = require('./cjs/react-server-flight.development.js'); }
26.375
74
0.688073
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 {default} from 'react-shallow-renderer';
22
66
0.702381
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 {Snapshot, TimelineData} from '../types'; import type { Interaction, Point, Rect, Size, Surface, ViewRefs, } from '../view-base'; import {positioningScaleFactor, timestampToPosition} from './utils/positioning'; import { intersectionOfRects, rectContainsPoint, rectEqualToRect, View, } from '../view-base'; import {BORDER_SIZE, COLORS, SNAPSHOT_SCRUBBER_SIZE} from './constants'; type OnHover = (node: Snapshot | null) => void; export class SnapshotsView extends View { _hoverLocation: Point | null = null; _intrinsicSize: Size; _profilerData: TimelineData; onHover: OnHover | null = null; constructor(surface: Surface, frame: Rect, profilerData: TimelineData) { super(surface, frame); this._intrinsicSize = { width: profilerData.duration, height: profilerData.snapshotHeight, }; this._profilerData = profilerData; } desiredSize(): Size { return this._intrinsicSize; } draw(context: CanvasRenderingContext2D) { const snapshotHeight = this._profilerData.snapshotHeight; const {visibleArea} = this; context.fillStyle = COLORS.BACKGROUND; context.fillRect( visibleArea.origin.x, visibleArea.origin.y, visibleArea.size.width, visibleArea.size.height, ); const y = visibleArea.origin.y; let x = visibleArea.origin.x; // Rather than drawing each snapshot where it occurred, // draw them at fixed intervals and just show the nearest one. while (x < visibleArea.origin.x + visibleArea.size.width) { const snapshot = this._findClosestSnapshot(x); if (snapshot === null) { // This shold never happen. break; } const scaledHeight = snapshotHeight; const scaledWidth = (snapshot.width * snapshotHeight) / snapshot.height; const imageRect: Rect = { origin: { x, y, }, size: {width: scaledWidth, height: scaledHeight}, }; // Lazily create and cache Image objects as we render a snapsho for the first time. if (snapshot.image === null) { const img = (snapshot.image = new Image()); img.onload = () => { this._drawSnapshotImage(context, snapshot, imageRect); }; img.src = snapshot.imageSource; } else { this._drawSnapshotImage(context, snapshot, imageRect); } x += scaledWidth + BORDER_SIZE; } const hoverLocation = this._hoverLocation; if (hoverLocation !== null) { const scrubberWidth = SNAPSHOT_SCRUBBER_SIZE + BORDER_SIZE * 2; const scrubberOffset = scrubberWidth / 2; context.fillStyle = COLORS.SCRUBBER_BORDER; context.fillRect( hoverLocation.x - scrubberOffset, visibleArea.origin.y, scrubberWidth, visibleArea.size.height, ); context.fillStyle = COLORS.SCRUBBER_BACKGROUND; context.fillRect( hoverLocation.x - scrubberOffset + BORDER_SIZE, visibleArea.origin.y, SNAPSHOT_SCRUBBER_SIZE, visibleArea.size.height, ); } } handleInteraction(interaction: Interaction, viewRefs: ViewRefs) { switch (interaction.type) { case 'mousemove': case 'wheel-control': case 'wheel-meta': case 'wheel-plain': case 'wheel-shift': this._updateHover(interaction.payload.location, viewRefs); break; } } _drawSnapshotImage( context: CanvasRenderingContext2D, snapshot: Snapshot, imageRect: Rect, ) { const visibleArea = this.visibleArea; // Prevent snapshot from visibly overflowing its container when clipped. // View clips by default, but since this view may draw async (on Image load) we re-clip. const shouldClip = !rectEqualToRect(imageRect, visibleArea); if (shouldClip) { const clippedRect = intersectionOfRects(imageRect, visibleArea); context.save(); context.beginPath(); context.rect( clippedRect.origin.x, clippedRect.origin.y, clippedRect.size.width, clippedRect.size.height, ); context.closePath(); context.clip(); } context.fillStyle = COLORS.REACT_RESIZE_BAR_BORDER; context.fillRect( imageRect.origin.x, imageRect.origin.y, imageRect.size.width, imageRect.size.height, ); // $FlowFixMe[incompatible-call] Flow doesn't know about the 9 argument variant of drawImage() context.drawImage( snapshot.image, // Image coordinates 0, 0, // Native image size snapshot.width, snapshot.height, // Canvas coordinates imageRect.origin.x + BORDER_SIZE, imageRect.origin.y + BORDER_SIZE, // Scaled image size imageRect.size.width - BORDER_SIZE * 2, imageRect.size.height - BORDER_SIZE * 2, ); if (shouldClip) { context.restore(); } } _findClosestSnapshot(x: number): Snapshot | null { const frame = this.frame; const scaleFactor = positioningScaleFactor( this._intrinsicSize.width, frame, ); const snapshots = this._profilerData.snapshots; let startIndex = 0; let stopIndex = snapshots.length - 1; while (startIndex <= stopIndex) { const currentIndex = Math.floor((startIndex + stopIndex) / 2); const snapshot = snapshots[currentIndex]; const {timestamp} = snapshot; const snapshotX = Math.floor( timestampToPosition(timestamp, scaleFactor, frame), ); if (x < snapshotX) { stopIndex = currentIndex - 1; } else { startIndex = currentIndex + 1; } } return snapshots[stopIndex] || null; } /** * @private */ _updateHover(location: Point, viewRefs: ViewRefs) { const {onHover, visibleArea} = this; if (!onHover) { return; } if (!rectContainsPoint(location, visibleArea)) { if (this._hoverLocation !== null) { this._hoverLocation = null; this.setNeedsDisplay(); } onHover(null); return; } const snapshot = this._findClosestSnapshot(location.x); if (snapshot !== null) { this._hoverLocation = location; onHover(snapshot); } else { this._hoverLocation = null; onHover(null); } // Any time the mouse moves within the boundaries of this view, we need to re-render. // This is because we draw a scrubbing bar that shows the location corresponding to the current tooltip. this.setNeedsDisplay(); } }
24.789272
108
0.634473
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. * * @format * @flow */ 'use strict'; type Options = {+unsafelyIgnoreFunctions?: boolean}; /* * @returns {bool} true if different, false if equal */ function deepDiffer( one: any, two: any, maxDepthOrOptions: Options | number = -1, maybeOptions?: Options, ): boolean { const options = typeof maxDepthOrOptions === 'number' ? maybeOptions : maxDepthOrOptions; const maxDepth = typeof maxDepthOrOptions === 'number' ? maxDepthOrOptions : -1; if (maxDepth === 0) { return true; } if (one === two) { // Short circuit on identical object references instead of traversing them. return false; } if (typeof one === 'function' && typeof two === 'function') { // We consider all functions equal unless explicitly configured otherwise let unsafelyIgnoreFunctions = options == null ? null : options.unsafelyIgnoreFunctions; if (unsafelyIgnoreFunctions == null) { unsafelyIgnoreFunctions = true; } return !unsafelyIgnoreFunctions; } if (typeof one !== 'object' || one === null) { // Primitives can be directly compared return one !== two; } if (typeof two !== 'object' || two === null) { // We know they are different because the previous case would have triggered // otherwise. return true; } if (one.constructor !== two.constructor) { return true; } if (Array.isArray(one)) { // We know two is also an array because the constructors are equal const len = one.length; if (two.length !== len) { return true; } for (let ii = 0; ii < len; ii++) { if (deepDiffer(one[ii], two[ii], maxDepth - 1, options)) { return true; } } } else { for (const key in one) { if (deepDiffer(one[key], two[key], maxDepth - 1, options)) { return true; } } for (const twoKey in two) { // The only case we haven't checked yet is keys that are in two but aren't // in one, which means they are different. if (one[twoKey] === undefined && two[twoKey] !== undefined) { return true; } } } return false; } module.exports = deepDiffer;
26.376471
80
0.623388
Ethical-Hacking-Scripts
/** * 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 Immutable from 'immutable'; const set = new Set(['abc', 123]); const map = new Map([ ['name', 'Brian'], ['food', 'sushi'], ]); const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]); const mapOfMaps = new Map([ ['first', map], ['second', map], ]); const typedArray = Int8Array.from([100, -100, 0]); const arrayBuffer = typedArray.buffer; const dataView = new DataView(arrayBuffer); const immutable = Immutable.fromJS({ a: [{hello: 'there'}, 'fixed', true], b: 123, c: { '1': 'xyz', xyz: 1, }, }); const bigInt = BigInt(123); // eslint-disable-line no-undef class Foo { flag = false; object: Object = { a: {b: {c: {d: 1}}}, }; } export default function UnserializableProps(): React.Node { return ( <ChildComponent arrayBuffer={arrayBuffer} dataView={dataView} map={map} set={set} mapOfMaps={mapOfMaps} setOfSets={setOfSets} typedArray={typedArray} immutable={immutable} bigInt={bigInt} classInstance={new Foo()} /> ); } function ChildComponent(props: any) { return null; }
20.380952
74
0.611441
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-turbopack-client.edge.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-turbopack-client.edge.development.js'); }
31.125
93
0.710938
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'; /** * Change environment support for PointerEvent. */ function emptyFunction() {} export function hasPointerEvent() { return global != null && global.PointerEvent != null; } export function setPointerEvent(bool) { const pointerCaptureFn = name => id => { if (typeof id !== 'number') { if (__DEV__) { console.error('A pointerId must be passed to "%s"', name); } } }; global.PointerEvent = bool ? emptyFunction : undefined; global.HTMLElement.prototype.setPointerCapture = bool ? pointerCaptureFn('setPointerCapture') : undefined; global.HTMLElement.prototype.releasePointerCapture = bool ? pointerCaptureFn('releasePointerCapture') : undefined; } /** * Change environment host platform. */ const platformGetter = jest.spyOn(global.navigator, 'platform', 'get'); export const platform = { clear() { platformGetter.mockClear(); }, get() { return global.navigator.platform === 'MacIntel' ? 'mac' : 'windows'; }, set(name: 'mac' | 'windows') { switch (name) { case 'mac': { platformGetter.mockReturnValue('MacIntel'); break; } case 'windows': { platformGetter.mockReturnValue('Win32'); break; } default: { break; } } }, };
21.367647
72
0.629605
Hands-On-Penetration-Testing-with-Python
"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,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhOZXN0ZWRIb29rcy5qcyJdLCJuYW1lcyI6WyJ1c2VNZW1vIiwidXNlU3RhdGUiLCJyZXF1aXJlIiwiQ29tcG9uZW50IiwicHJvcHMiLCJJbm5lckNvbXBvbmVudCIsInN0YXRlIiwiY2FsbGJhY2siLCJtb2R1bGUiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOztBQUFBOzs7Ozs7OztBQVFBLE1BQU07QUFBQ0EsRUFBQUEsT0FBRDtBQUFVQyxFQUFBQTtBQUFWLElBQXNCQyxPQUFPLENBQUMsT0FBRCxDQUFuQzs7QUFFQSxTQUFTQyxTQUFULENBQW1CQyxLQUFuQixFQUEwQjtBQUN4QixRQUFNQyxjQUFjLEdBQUdMLE9BQU8sQ0FBQyxNQUFNLE1BQU07QUFDekMsVUFBTSxDQUFDTSxLQUFELElBQVVMLFFBQVEsQ0FBQyxDQUFELENBQXhCO0FBRUEsV0FBT0ssS0FBUDtBQUNELEdBSjZCLENBQTlCO0FBS0FGLEVBQUFBLEtBQUssQ0FBQ0csUUFBTixDQUFlRixjQUFmO0FBRUEsU0FBTyxJQUFQO0FBQ0Q7O0FBRURHLE1BQU0sQ0FBQ0MsT0FBUCxHQUFpQjtBQUFDTixFQUFBQTtBQUFELENBQWpCIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5jb25zdCB7dXNlTWVtbywgdXNlU3RhdGV9ID0gcmVxdWlyZSgncmVhY3QnKTtcblxuZnVuY3Rpb24gQ29tcG9uZW50KHByb3BzKSB7XG4gIGNvbnN0IElubmVyQ29tcG9uZW50ID0gdXNlTWVtbygoKSA9PiAoKSA9PiB7XG4gICAgY29uc3QgW3N0YXRlXSA9IHVzZVN0YXRlKDApO1xuXG4gICAgcmV0dXJuIHN0YXRlO1xuICB9KTtcbiAgcHJvcHMuY2FsbGJhY2soSW5uZXJDb21wb25lbnQpO1xuXG4gIHJldHVybiBudWxsO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHtDb21wb25lbnR9O1xuIl19fV19
71.75
1,552
0.910609
Python-for-Offensive-PenTest
/** * 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 { ElementTypeForwardRef, ElementTypeMemo, } from 'react-devtools-shared/src/frontend/types'; import {formatDuration} from './utils'; import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore'; import type {CommitTree} from './types'; export type ChartNode = { id: number, label: string, name: string, value: number, }; export type ChartData = { maxValue: number, nodes: Array<ChartNode>, }; const cachedChartData: Map<string, ChartData> = new Map(); export function getChartData({ commitIndex, commitTree, profilerStore, rootID, }: { commitIndex: number, commitTree: CommitTree, profilerStore: ProfilerStore, rootID: number, }): ChartData { const commitDatum = profilerStore.getCommitData(rootID, commitIndex); const {fiberActualDurations, fiberSelfDurations} = commitDatum; const {nodes} = commitTree; const chartDataKey = `${rootID}-${commitIndex}`; if (cachedChartData.has(chartDataKey)) { return ((cachedChartData.get(chartDataKey): any): ChartData); } let maxSelfDuration = 0; const chartNodes: Array<ChartNode> = []; fiberActualDurations.forEach((actualDuration, id) => { const node = nodes.get(id); if (node == null) { throw Error(`Could not find node with id "${id}" in commit tree`); } const {displayName, key, parentID, type} = node; // Don't show the root node in this chart. if (parentID === 0) { return; } const selfDuration = fiberSelfDurations.get(id) || 0; maxSelfDuration = Math.max(maxSelfDuration, selfDuration); const name = displayName || 'Anonymous'; const maybeKey = key !== null ? ` key="${key}"` : ''; let maybeBadge = ''; if (type === ElementTypeForwardRef) { maybeBadge = ' (ForwardRef)'; } else if (type === ElementTypeMemo) { maybeBadge = ' (Memo)'; } const label = `${name}${maybeBadge}${maybeKey} (${formatDuration( selfDuration, )}ms)`; chartNodes.push({ id, label, name, value: selfDuration, }); }); const chartData = { maxValue: maxSelfDuration, nodes: chartNodes.sort((a, b) => b.value - a.value), }; cachedChartData.set(chartDataKey, chartData); return chartData; } export function invalidateChartData(): void { cachedChartData.clear(); }
22.626168
77
0.661654
diff-droid
"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+Q2xpY2sgbWU8L2J1dHRvbj5cbiAgICA8L2Rpdj5cbiAgKTtcbn1cbiJdLCJ4X3JlYWN0X3NvdXJjZXMiOltbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJjb3VudCJdLCJtYXBwaW5ncyI6IkNBQUQ7ZTRCQ0EsQVdEQSJ9XV19
80.45
1,464
0.798281
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 */ 'use strict'; import type {ReactNodeList} from 'shared/ReactTypes'; import type { RootType, HydrateRootOptions, CreateRootOptions, } from './src/client/ReactDOMRoot'; import { createRoot as createRootImpl, hydrateRoot as hydrateRootImpl, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED as Internals, } from './'; export function createRoot( container: Element | Document | DocumentFragment, options?: CreateRootOptions, ): RootType { if (__DEV__) { Internals.usingClientEntryPoint = true; } try { return createRootImpl(container, options); } finally { if (__DEV__) { Internals.usingClientEntryPoint = false; } } } export function hydrateRoot( container: Document | Element, children: ReactNodeList, options?: HydrateRootOptions, ): RootType { if (__DEV__) { Internals.usingClientEntryPoint = true; } try { return hydrateRootImpl(container, children, options); } finally { if (__DEV__) { Internals.usingClientEntryPoint = false; } } }
20.614035
66
0.683997
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 */ type Info = {tag: string}; export type AncestorInfoDev = { current: ?Info, formTag: ?Info, aTagInScope: ?Info, buttonTagInScope: ?Info, nobrTagInScope: ?Info, pTagInButtonScope: ?Info, listItemTagAutoclosing: ?Info, dlItemTagAutoclosing: ?Info, // <head> or <body> containerTagInScope: ?Info, }; // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special const specialTags = [ 'address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp', ]; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope const inScopeTags = [ 'applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title', ]; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope const buttonScopeTags = __DEV__ ? inScopeTags.concat(['button']) : []; // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags const impliedEndTags = [ 'dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt', ]; const emptyAncestorInfoDev: AncestorInfoDev = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null, containerTagInScope: null, }; function updatedAncestorInfoDev( oldInfo: ?AncestorInfoDev, tag: string, ): AncestorInfoDev { if (__DEV__) { const ancestorInfo = {...(oldInfo || emptyAncestorInfoDev)}; const info = {tag}; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if ( specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p' ) { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } if (tag === '#document' || tag === 'html') { ancestorInfo.containerTagInScope = null; } else if (!ancestorInfo.containerTagInScope) { ancestorInfo.containerTagInScope = info; } return ancestorInfo; } else { return (null: any); } } /** * Returns whether */ function isTagValidWithParent(tag: string, parentTag: ?string): boolean { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return ( tag === 'hr' || tag === 'option' || tag === 'optgroup' || tag === '#text' ); case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return ( tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template' ); // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return ( tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template' ); // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return ( tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template' ); // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return ( tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template' ); // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body' || tag === 'frameset'; case 'frameset': return tag === 'frame'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ( parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6' ); case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frameset': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; } /** * Returns whether */ function findInvalidAncestorForTag( tag: string, ancestorInfo: AncestorInfoDev, ): ?Info { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; } const didWarn: {[string]: boolean} = {}; function validateDOMNesting( childTag: string, ancestorInfo: AncestorInfoDev, ): void { if (__DEV__) { ancestorInfo = ancestorInfo || emptyAncestorInfoDev; const parentInfo = ancestorInfo.current; const parentTag = parentInfo && parentInfo.tag; const invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; const invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); const invalidParentOrAncestor = invalidParent || invalidAncestor; if (!invalidParentOrAncestor) { return; } const ancestorTag = invalidParentOrAncestor.tag; const warnKey = // eslint-disable-next-line react-internal/safe-string-coercion String(!!invalidParent) + '|' + childTag + '|' + ancestorTag; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; const tagDisplayName = '<' + childTag + '>'; if (invalidParent) { let info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.'; } console.error( 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s', tagDisplayName, ancestorTag, info, ); } else { console.error( 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag, ); } } } function validateTextNesting(childText: string, parentTag: string): void { if (__DEV__) { if (isTagValidWithParent('#text', parentTag)) { return; } // eslint-disable-next-line react-internal/safe-string-coercion const warnKey = '#text|' + parentTag; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; if (/\S/.test(childText)) { console.error( 'validateDOMNesting(...): Text nodes cannot appear as a child of <%s>.', parentTag, ); } else { console.error( 'validateDOMNesting(...): Whitespace text nodes cannot appear as a child of <%s>. ' + "Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.', parentTag, ); } } } export {updatedAncestorInfoDev, validateDOMNesting, validateTextNesting};
22.844106
97
0.584722
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'; import { insertNodesAndExecuteScripts, getVisibleChildren, } from '../test-utils/FizzTestUtils'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; let act; let assertLog; let waitForPaint; let container; let React; let Scheduler; let ReactDOMServer; let ReactDOMClient; let useDeferredValue; let Suspense; describe('ReactDOMFizzForm', () => { beforeEach(() => { jest.resetModules(); React = require('react'); Scheduler = require('scheduler'); ReactDOMServer = require('react-dom/server.browser'); ReactDOMClient = require('react-dom/client'); useDeferredValue = React.useDeferredValue; Suspense = React.Suspense; act = require('internal-test-utils').act; assertLog = require('internal-test-utils').assertLog; waitForPaint = require('internal-test-utils').waitForPaint; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); }); 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); } function Text({text}) { Scheduler.log(text); return text; } // @gate enableUseDeferredValueInitialArg it('returns initialValue argument, if provided', async () => { function App() { return useDeferredValue('Final', 'Initial'); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); expect(container.textContent).toEqual('Initial'); // After hydration, it's updated to the final value await act(() => ReactDOMClient.hydrateRoot(container, <App />)); expect(container.textContent).toEqual('Final'); }); // @gate enableUseDeferredValueInitialArg // @gate enablePostpone it( 'if initial value postpones during hydration, it will switch to the ' + 'final value instead', async () => { function Content() { const isInitial = useDeferredValue(false, true); if (isInitial) { React.unstable_postpone(); } return <Text text="Final" />; } function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <Content /> </Suspense> ); } const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); expect(container.textContent).toEqual('Loading...'); // After hydration, it's updated to the final value await act(() => ReactDOMClient.hydrateRoot(container, <App />)); expect(container.textContent).toEqual('Final'); }, ); // @gate enableUseDeferredValueInitialArg it( 'useDeferredValue during hydration has higher priority than remaining ' + 'incremental hydration', async () => { function B() { const text = useDeferredValue('B [Final]', 'B [Initial]'); return <Text text={text} />; } function App() { return ( <div> <span> <Text text="A" /> </span> <Suspense fallback={<Text text="Loading..." />}> <span> <B /> </span> <div> <Suspense fallback={<Text text="Loading..." />}> <span id="C" ref={cRef}> <Text text="C" /> </span> </Suspense> </div> </Suspense> </div> ); } const cRef = React.createRef(); // The server renders using the "initial" value for B. const stream = await ReactDOMServer.renderToReadableStream(<App />); await readIntoContainer(stream); assertLog(['A', 'B [Initial]', 'C']); expect(getVisibleChildren(container)).toEqual( <div> <span>A</span> <span>B [Initial]</span> <div> <span id="C">C</span> </div> </div>, ); const serverRenderedC = document.getElementById('C'); // On the client, we first hydrate the initial value, then upgrade // to final. await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); // First the outermost Suspense boundary hydrates. await waitForPaint(['A']); expect(cRef.current).toBe(null); // Then the next level hydrates. This level includes a useDeferredValue, // so we should prioritize upgrading it before we proceed to hydrating // additional levels. await waitForPaint(['B [Initial]']); expect(getVisibleChildren(container)).toEqual( <div> <span>A</span> <span>B [Initial]</span> <div> <span id="C">C</span> </div> </div>, ); expect(cRef.current).toBe(null); // This paint should only update B. C should still be dehydrated. await waitForPaint(['B [Final]']); expect(getVisibleChildren(container)).toEqual( <div> <span>A</span> <span>B [Final]</span> <div> <span id="C">C</span> </div> </div>, ); expect(cRef.current).toBe(null); }); // Finally we can hydrate C assertLog(['C']); expect(getVisibleChildren(container)).toEqual( <div> <span>A</span> <span>B [Final]</span> <div> <span id="C">C</span> </div> </div>, ); expect(cRef.current).toBe(serverRenderedC); }, ); });
27.261261
80
0.575642
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 type {ReactContext} from 'shared/ReactTypes'; import * as React from 'react'; import { createContext, useContext, useEffect, useLayoutEffect, useMemo, } from 'react'; import { LOCAL_STORAGE_BROWSER_THEME, LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY, LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY, LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, } from 'react-devtools-shared/src/constants'; import { COMFORTABLE_LINE_HEIGHT, COMPACT_LINE_HEIGHT, } from 'react-devtools-shared/src/devtools/constants'; import {useLocalStorage} from '../hooks'; import {BridgeContext} from '../context'; import {logEvent} from 'react-devtools-shared/src/Logger'; import type {BrowserTheme} from 'react-devtools-shared/src/frontend/types'; export type DisplayDensity = 'comfortable' | 'compact'; export type Theme = 'auto' | 'light' | 'dark'; type Context = { displayDensity: DisplayDensity, setDisplayDensity(value: DisplayDensity): void, // Derived from display density. // Specified as a separate prop so it can trigger a re-render of FixedSizeList. lineHeight: number, appendComponentStack: boolean, setAppendComponentStack: (value: boolean) => void, breakOnConsoleErrors: boolean, setBreakOnConsoleErrors: (value: boolean) => void, parseHookNames: boolean, setParseHookNames: (value: boolean) => void, hideConsoleLogsInStrictMode: boolean, setHideConsoleLogsInStrictMode: (value: boolean) => void, showInlineWarningsAndErrors: boolean, setShowInlineWarningsAndErrors: (value: boolean) => void, theme: Theme, setTheme(value: Theme): void, browserTheme: Theme, traceUpdatesEnabled: boolean, setTraceUpdatesEnabled: (value: boolean) => void, }; const SettingsContext: ReactContext<Context> = createContext<Context>( ((null: any): Context), ); SettingsContext.displayName = 'SettingsContext'; function useLocalStorageWithLog<T>( key: string, initialValue: T | (() => T), ): [T, (value: T | (() => T)) => void] { return useLocalStorage<T>(key, initialValue, (v, k) => { logEvent({ event_name: 'settings-changed', metadata: { source: 'localStorage setter', key: k, value: v, }, }); }); } type DocumentElements = Array<HTMLElement>; type Props = { browserTheme: BrowserTheme, children: React$Node, componentsPortalContainer?: Element, profilerPortalContainer?: Element, }; function SettingsContextController({ browserTheme, children, componentsPortalContainer, profilerPortalContainer, }: Props): React.Node { const bridge = useContext(BridgeContext); const [displayDensity, setDisplayDensity] = useLocalStorageWithLog<DisplayDensity>( 'React::DevTools::displayDensity', 'compact', ); const [theme, setTheme] = useLocalStorageWithLog<Theme>( LOCAL_STORAGE_BROWSER_THEME, 'auto', ); const [appendComponentStack, setAppendComponentStack] = useLocalStorageWithLog<boolean>( LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY, true, ); const [breakOnConsoleErrors, setBreakOnConsoleErrors] = useLocalStorageWithLog<boolean>( LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS, false, ); const [parseHookNames, setParseHookNames] = useLocalStorageWithLog<boolean>( LOCAL_STORAGE_PARSE_HOOK_NAMES_KEY, false, ); const [hideConsoleLogsInStrictMode, setHideConsoleLogsInStrictMode] = useLocalStorageWithLog<boolean>( LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE, false, ); const [showInlineWarningsAndErrors, setShowInlineWarningsAndErrors] = useLocalStorageWithLog<boolean>( LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY, true, ); const [traceUpdatesEnabled, setTraceUpdatesEnabled] = useLocalStorageWithLog<boolean>( LOCAL_STORAGE_TRACE_UPDATES_ENABLED_KEY, false, ); const documentElements = useMemo<DocumentElements>(() => { const array: Array<HTMLElement> = [ ((document.documentElement: any): HTMLElement), ]; if (componentsPortalContainer != null) { array.push( ((componentsPortalContainer.ownerDocument .documentElement: any): HTMLElement), ); } if (profilerPortalContainer != null) { array.push( ((profilerPortalContainer.ownerDocument .documentElement: any): HTMLElement), ); } return array; }, [componentsPortalContainer, profilerPortalContainer]); useLayoutEffect(() => { switch (displayDensity) { case 'comfortable': updateDisplayDensity('comfortable', documentElements); break; case 'compact': updateDisplayDensity('compact', documentElements); break; default: throw Error(`Unsupported displayDensity value "${displayDensity}"`); } }, [displayDensity, documentElements]); useLayoutEffect(() => { switch (theme) { case 'light': updateThemeVariables('light', documentElements); break; case 'dark': updateThemeVariables('dark', documentElements); break; case 'auto': updateThemeVariables(browserTheme, documentElements); break; default: throw Error(`Unsupported theme value "${theme}"`); } }, [browserTheme, theme, documentElements]); useEffect(() => { bridge.send('updateConsolePatchSettings', { appendComponentStack, breakOnConsoleErrors, showInlineWarningsAndErrors, hideConsoleLogsInStrictMode, browserTheme, }); }, [ bridge, appendComponentStack, breakOnConsoleErrors, showInlineWarningsAndErrors, hideConsoleLogsInStrictMode, browserTheme, ]); useEffect(() => { bridge.send('setTraceUpdatesEnabled', traceUpdatesEnabled); }, [bridge, traceUpdatesEnabled]); const value = useMemo( () => ({ appendComponentStack, breakOnConsoleErrors, displayDensity, lineHeight: displayDensity === 'compact' ? COMPACT_LINE_HEIGHT : COMFORTABLE_LINE_HEIGHT, parseHookNames, setAppendComponentStack, setBreakOnConsoleErrors, setDisplayDensity, setParseHookNames, setTheme, setTraceUpdatesEnabled, setShowInlineWarningsAndErrors, showInlineWarningsAndErrors, setHideConsoleLogsInStrictMode, hideConsoleLogsInStrictMode, theme, browserTheme, traceUpdatesEnabled, }), [ appendComponentStack, breakOnConsoleErrors, displayDensity, parseHookNames, setAppendComponentStack, setBreakOnConsoleErrors, setDisplayDensity, setParseHookNames, setTheme, setTraceUpdatesEnabled, setShowInlineWarningsAndErrors, showInlineWarningsAndErrors, setHideConsoleLogsInStrictMode, hideConsoleLogsInStrictMode, theme, browserTheme, traceUpdatesEnabled, ], ); return ( <SettingsContext.Provider value={value}> {children} </SettingsContext.Provider> ); } export function updateDisplayDensity( displayDensity: DisplayDensity, documentElements: DocumentElements, ): void { // Sizes and paddings/margins are all rem-based, // so update the root font-size as well when the display preference changes. const computedStyle = getComputedStyle((document.body: any)); const fontSize = computedStyle.getPropertyValue( `--${displayDensity}-root-font-size`, ); const root = ((document.querySelector(':root'): any): HTMLElement); root.style.fontSize = fontSize; } export function updateThemeVariables( theme: Theme, documentElements: DocumentElements, ): void { // Update scrollbar color to match theme. // this CSS property is currently only supported in Firefox, // but it makes a significant UI improvement in dark mode. // https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-color documentElements.forEach(documentElement => { // $FlowFixMe[prop-missing] scrollbarColor is missing in CSSStyleDeclaration documentElement.style.scrollbarColor = `var(${`--${theme}-color-scroll-thumb`}) var(${`--${theme}-color-scroll-track`})`; }); } export {SettingsContext, SettingsContextController};
27.415282
125
0.696094
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 ReactDOMServer; // In standard React, TextComponent keeps track of different Text templates // using comments. However, in React Fiber, those comments are not outputted due // to the way Fiber keeps track of the templates. // This function "Normalizes" childNodes lists to avoid the presence of comments // and make the child list identical in standard React and Fiber function filterOutComments(nodeList) { return [].slice.call(nodeList).filter(node => !(node instanceof Comment)); } describe('ReactDOMTextComponent', () => { beforeEach(() => { React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); }); it('updates a mounted text component in place', () => { const el = document.createElement('div'); let inst = ReactDOM.render( <div> <span /> {'foo'} {'bar'} </div>, el, ); let nodes = filterOutComments(inst.childNodes); const foo = nodes[1]; const bar = nodes[2]; expect(foo.data).toBe('foo'); expect(bar.data).toBe('bar'); inst = ReactDOM.render( <div> <span /> {'baz'} {'qux'} </div>, el, ); // After the update, the text nodes should have stayed in place (as opposed // to getting unmounted and remounted) nodes = filterOutComments(inst.childNodes); expect(nodes[1]).toBe(foo); expect(nodes[2]).toBe(bar); expect(foo.data).toBe('baz'); expect(bar.data).toBe('qux'); }); it('can be toggled in and out of the markup', () => { const el = document.createElement('div'); let inst = ReactDOM.render( <div> {'foo'} <div /> {'bar'} </div>, el, ); let childNodes = filterOutComments(inst.childNodes); const childDiv = childNodes[1]; inst = ReactDOM.render( <div> {null} <div /> {null} </div>, el, ); childNodes = filterOutComments(inst.childNodes); expect(childNodes.length).toBe(1); expect(childNodes[0]).toBe(childDiv); inst = ReactDOM.render( <div> {'foo'} <div /> {'bar'} </div>, el, ); childNodes = filterOutComments(inst.childNodes); expect(childNodes.length).toBe(3); expect(childNodes[0].data).toBe('foo'); expect(childNodes[1]).toBe(childDiv); expect(childNodes[2].data).toBe('bar'); }); /** * The following Node.normalize() tests are intentionally failing. * See #9836 tracking whether we'll need to fix this or if it's unnecessary. */ xit('can reconcile text merged by Node.normalize() alongside other elements', () => { const el = document.createElement('div'); let inst = ReactDOM.render( <div> {'foo'} {'bar'} {'baz'} <span /> {'qux'} </div>, el, ); inst.normalize(); inst = ReactDOM.render( <div> {'bar'} {'baz'} {'qux'} <span /> {'foo'} </div>, el, ); expect(inst.textContent).toBe('barbazquxfoo'); }); xit('can reconcile text merged by Node.normalize()', () => { const el = document.createElement('div'); let inst = ReactDOM.render( <div> {'foo'} {'bar'} {'baz'} </div>, el, ); inst.normalize(); inst = ReactDOM.render( <div> {'bar'} {'baz'} {'qux'} </div>, el, ); expect(inst.textContent).toBe('barbazqux'); }); it('can reconcile text from pre-rendered markup', () => { const el = document.createElement('div'); let reactEl = ( <div> {'foo'} {'bar'} {'baz'} </div> ); el.innerHTML = ReactDOMServer.renderToString(reactEl); ReactDOM.hydrate(reactEl, el); expect(el.textContent).toBe('foobarbaz'); ReactDOM.unmountComponentAtNode(el); reactEl = ( <div> {''} {''} {''} </div> ); el.innerHTML = ReactDOMServer.renderToString(reactEl); ReactDOM.hydrate(reactEl, el); expect(el.textContent).toBe(''); }); xit('can reconcile text arbitrarily split into multiple nodes', () => { const el = document.createElement('div'); let inst = ReactDOM.render( <div> <span /> {'foobarbaz'} </div>, el, ); const childNodes = filterOutComments(inst.childNodes); const textNode = childNodes[1]; textNode.textContent = 'foo'; inst.insertBefore( document.createTextNode('bar'), childNodes[1].nextSibling, ); inst.insertBefore( document.createTextNode('baz'), childNodes[1].nextSibling, ); inst = ReactDOM.render( <div> <span /> {'barbazqux'} </div>, el, ); expect(inst.textContent).toBe('barbazqux'); }); xit('can reconcile text arbitrarily split into multiple nodes on some substitutions only', () => { const el = document.createElement('div'); let inst = ReactDOM.render( <div> <span /> {'bar'} <span /> {'foobarbaz'} {'foo'} {'barfoo'} <span /> </div>, el, ); const childNodes = filterOutComments(inst.childNodes); const textNode = childNodes[3]; textNode.textContent = 'foo'; inst.insertBefore( document.createTextNode('bar'), childNodes[3].nextSibling, ); inst.insertBefore( document.createTextNode('baz'), childNodes[3].nextSibling, ); const secondTextNode = childNodes[5]; secondTextNode.textContent = 'bar'; inst.insertBefore( document.createTextNode('foo'), childNodes[5].nextSibling, ); inst = ReactDOM.render( <div> <span /> {'baz'} <span /> {'barbazqux'} {'bar'} {'bazbar'} <span /> </div>, el, ); expect(inst.textContent).toBe('bazbarbazquxbarbazbar'); }); xit('can unmount normalized text nodes', () => { const el = document.createElement('div'); ReactDOM.render( <div> {''} {'foo'} {'bar'} </div>, el, ); el.normalize(); ReactDOM.render(<div />, el); expect(el.innerHTML).toBe('<div></div>'); }); it('throws for Temporal-like text nodes', () => { const el = document.createElement('div'); class TemporalLike { valueOf() { // Throwing here is the behavior of ECMAScript "Temporal" date/time API. // See https://tc39.es/proposal-temporal/docs/plaindate.html#valueOf throw new TypeError('prod message'); } toString() { return '2020-01-01'; } } expect(() => ReactDOM.render(<div>{new TemporalLike()}</div>, el), ).toThrowError( new Error( 'Objects are not valid as a React child (found: object with keys {}).' + ' If you meant to render a collection of children, use an array instead.', ), ); }); });
22.580645
100
0.557805
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 */ const {useDebugValue} = require('react'); function Component(props) { useCustomHookOne(); const [bar] = useCustomHookTwo(); const {foo} = useCustomHookThree(); return `${bar}-${foo}`; } function useCustomHookOne() { // DebugValue hook should not appear in log. useDebugValue('example1'); } function useCustomHookTwo() { // DebugValue hook should not appear in log. useDebugValue('example2'); return [true]; } function useCustomHookThree() { useDebugValue('example3'); return {foo: true}; } module.exports = {Component};
19.888889
66
0.69241
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 */ import type { Request, ReactClientValue, } from 'react-server/src/ReactFlightServer'; import type {Destination} from 'react-server/src/ReactServerStreamConfigNode'; import type {ClientManifest} from './ReactFlightServerConfigESMBundler'; 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, } from './ReactFlightESMReferences'; function createDrainHandler(destination: Destination, request: Request) { return () => startFlowing(request, destination); } 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, moduleBasePath: ClientManifest, options?: Options, ): PipeableStream { const request = createRequest( model, moduleBasePath, 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)); return destination; }, abort(reason: mixed) { stopFlowing(request); abort(request, reason); }, }; } function decodeReplyFromBusboy<T>( busboyStream: Busboy, moduleBasePath: ServerManifest, ): Thenable<T> { const response = createResponse(moduleBasePath, ''); 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, moduleBasePath: ServerManifest, ): Thenable<T> { if (typeof body === 'string') { const form = new FormData(); form.append('0', body); body = form; } const response = createResponse(moduleBasePath, '', body); const root = getRoot<T>(response); close(response); return root; } export { renderToPipeableStream, decodeReplyFromBusboy, decodeReply, decodeAction, decodeFormState, };
26.327684
86
0.673904
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 RootTag = 0 | 1; export const LegacyRoot = 0; export const ConcurrentRoot = 1;
20.214286
66
0.699324
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. * */ 'use strict'; const babelRegister = require('@babel/register'); babelRegister({ ignore: [/[\\\/](build|server\/server|node_modules)[\\\/]/], presets: [['react-app', {runtime: 'automatic'}]], plugins: ['@babel/transform-modules-commonjs'], }); const express = require('express'); const compress = require('compression'); const {readFileSync} = require('fs'); const path = require('path'); const render = require('./render'); const {JS_BUNDLE_DELAY} = require('./delays'); const PORT = process.env.PORT || 4000; const app = express(); app.use((req, res, next) => { if (req.url.endsWith('.js')) { // Artificially delay serving JS // to demonstrate streaming HTML. setTimeout(next, JS_BUNDLE_DELAY); } else { next(); } }); app.use(compress()); app.get( '/', handleErrors(async function (req, res) { await waitForWebpack(); render(req.url, res); }) ); app.use(express.static('build')); app.use(express.static('public')); app .listen(PORT, () => { console.log(`Listening at ${PORT}...`); }) .on('error', function (error) { if (error.syscall !== 'listen') { throw error; } const isPipe = portOrPipe => Number.isNaN(portOrPipe); const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT; switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } }); function handleErrors(fn) { return async function (req, res, next) { try { return await fn(req, res); } catch (x) { next(x); } }; } async function waitForWebpack() { while (true) { try { readFileSync(path.resolve(__dirname, '../build/main.js')); return; } catch (err) { console.log( 'Could not find webpack build output. Will retry in a second...' ); await new Promise(resolve => setTimeout(resolve, 1000)); } } }
22.65625
72
0.598238
hackipy
/** * 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 */ throw new Error( 'The React Server cannot be used outside a react-server environment. ' + 'You must configure Node.js using the `--conditions react-server` flag.', );
26
77
0.700265
PenetrationTestingScripts
/** @flow */ 'use strict'; const {runOnlyForReactRange} = require('./utils'); const listAppUtils = require('./list-app-utils'); const devToolsUtils = require('./devtools-utils'); const {test, expect} = require('@playwright/test'); const config = require('../../playwright.config'); const semver = require('semver'); test.use(config); test.describe('Components', () => { let page; test.beforeEach(async ({browser}) => { page = await browser.newPage(); await page.goto(config.use.url, { waitUntil: 'domcontentloaded', }); await page.waitForSelector('#iframe'); await devToolsUtils.clickButton(page, 'TabBarButton-components'); }); test('Should display initial React components', async () => { const appRowCount = await page.evaluate(() => { const {createTestNameSelector, findAllNodes} = window.REACT_DOM_APP; const container = document.getElementById('iframe').contentDocument; const rows = findAllNodes(container, [ createTestNameSelector('ListItem'), ]); return rows.length; }); expect(appRowCount).toBe(3); const devToolsRowCount = await devToolsUtils.getElementCount( page, 'ListItem' ); expect(devToolsRowCount).toBe(3); }); test('Should display newly added React components', async () => { await listAppUtils.addItem(page, 'four'); const count = await devToolsUtils.getElementCount(page, 'ListItem'); expect(count).toBe(4); }); test('Should allow elements to be inspected', async () => { // Select the first list item in DevTools. await devToolsUtils.selectElement(page, 'ListItem', 'List\nApp'); // Prop names/values may not be editable based on the React version. // If they're not editable, make sure they degrade gracefully const isEditableName = semver.gte(config.use.react_version, '17.0.0'); const isEditableValue = semver.gte(config.use.react_version, '16.8.0'); // Then read the inspected values. const [propName, propValue, sourceText] = await page.evaluate( isEditable => { const {createTestNameSelector, findAllNodes} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); // Get name of first prop const selectorName = isEditable.name ? 'EditableName' : 'NonEditableName'; const nameElement = findAllNodes(container, [ createTestNameSelector('InspectedElementPropsTree'), createTestNameSelector(selectorName), ])[0]; const name = isEditable.name ? nameElement.value : nameElement.innerText; // Get value of first prop const selectorValue = isEditable.value ? 'EditableValue' : 'NonEditableValue'; const valueElement = findAllNodes(container, [ createTestNameSelector('InspectedElementPropsTree'), createTestNameSelector(selectorValue), ])[0]; const source = findAllNodes(container, [ createTestNameSelector('InspectedElementView-Source'), ])[0]; const value = isEditable.value ? valueElement.value : valueElement.innerText; return [name, value, source.innerText]; }, {name: isEditableName, value: isEditableValue} ); expect(propName).toBe('label'); expect(propValue).toBe('"one"'); expect(sourceText).toMatch(/ListApp[a-zA-Z]*\.js/); }); test('should allow props to be edited', async () => { runOnlyForReactRange('>=16.8'); // Select the first list item in DevTools. await devToolsUtils.selectElement(page, 'ListItem', 'List\nApp'); // Then edit the label prop. await page.evaluate(() => { const {createTestNameSelector, focusWithin} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); focusWithin(container, [ createTestNameSelector('InspectedElementPropsTree'), createTestNameSelector('EditableValue'), ]); }); page.keyboard.press('Backspace'); // " page.keyboard.press('Backspace'); // e page.keyboard.press('Backspace'); // n page.keyboard.press('Backspace'); // o page.keyboard.insertText('new"'); page.keyboard.press('Enter'); await page.waitForFunction(() => { const {createTestNameSelector, findAllNodes} = window.REACT_DOM_APP; const container = document.getElementById('iframe').contentDocument; const rows = findAllNodes(container, [ createTestNameSelector('ListItem'), ])[0]; return rows.innerText === 'new'; }); }); test('should load and parse hook names for the inspected element', async () => { runOnlyForReactRange('>=16.8'); // Select the List component DevTools. await devToolsUtils.selectElement(page, 'List', 'App'); // Then click to load and parse hook names. await devToolsUtils.clickButton(page, 'LoadHookNamesButton'); // Make sure the expected hook names are parsed and displayed eventually. await page.waitForFunction( hookNames => { const {createTestNameSelector, findAllNodes} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const hooksTree = findAllNodes(container, [ createTestNameSelector('InspectedElementHooksTree'), ])[0]; if (!hooksTree) { return false; } const hooksTreeText = hooksTree.innerText; for (let i = 0; i < hookNames.length; i++) { if (!hooksTreeText.includes(hookNames[i])) { return false; } } return true; }, ['State(items)', 'Ref(inputRef)'] ); }); test('should allow searching for component by name', async () => { async function getComponentSearchResultsCount() { return await page.evaluate(() => { const {createTestNameSelector, findAllNodes} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); const element = findAllNodes(container, [ createTestNameSelector('ComponentSearchInput-ResultsCount'), ])[0]; return element.innerText; }); } async function focusComponentSearch() { await page.evaluate(() => { const {createTestNameSelector, focusWithin} = window.REACT_DOM_DEVTOOLS; const container = document.getElementById('devtools'); focusWithin(container, [ createTestNameSelector('ComponentSearchInput-Input'), ]); }); } await focusComponentSearch(); page.keyboard.insertText('List'); let count = await getComponentSearchResultsCount(); expect(count).toBe('1 | 4'); page.keyboard.insertText('Item'); count = await getComponentSearchResultsCount(); expect(count).toBe('1 | 3'); page.keyboard.press('Enter'); count = await getComponentSearchResultsCount(); expect(count).toBe('2 | 3'); page.keyboard.press('Enter'); count = await getComponentSearchResultsCount(); expect(count).toBe('3 | 3'); page.keyboard.press('Enter'); count = await getComponentSearchResultsCount(); expect(count).toBe('1 | 3'); page.keyboard.press('Shift+Enter'); count = await getComponentSearchResultsCount(); expect(count).toBe('3 | 3'); page.keyboard.press('Shift+Enter'); count = await getComponentSearchResultsCount(); expect(count).toBe('2 | 3'); page.keyboard.press('Shift+Enter'); count = await getComponentSearchResultsCount(); expect(count).toBe('1 | 3'); }); });
31.317797
82
0.643981
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 type ImportManifestEntry = { id: string, // chunks is a double indexed array of chunkId / chunkFilename pairs chunks: Array<string>, name: string, }; // This is the parsed shape of the wire format which is why it is // condensed to only the essentialy information export type ImportMetadata = | [ /* id */ string, /* chunks id/filename pairs, double indexed */ Array<string>, /* name */ string, /* async */ 1, ] | [ /* id */ string, /* chunks id/filename pairs, double indexed */ Array<string>, /* name */ string, ]; export const ID = 0; export const CHUNKS = 1; export const NAME = 2; // export const ASYNC = 3; // This logic is correct because currently only include the 4th tuple member // when the module is async. If that changes we will need to actually assert // the value is true. We don't index into the 4th slot because flow does not // like the potential out of bounds access export function isAsyncImport(metadata: ImportMetadata): boolean { return metadata.length === 4; }
27.75
76
0.676424
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 * as React from 'react'; import {Fragment, useContext, useEffect} from 'react'; import {BridgeContext} from './context'; import {ModalDialogContext} from './ModalDialog'; import styles from './WarnIfLegacyBackendDetected.css'; export default function WarnIfLegacyBackendDetected(_: {}): null { const bridge = useContext(BridgeContext); const {dispatch} = useContext(ModalDialogContext); // Detect pairing with legacy v3 backend. // We do this by listening to a message that it broadcasts but the v4 backend doesn't. // In this case the frontend should show upgrade instructions. useEffect(() => { // Wall.listen returns a cleanup function let unlisten: $FlowFixMe = bridge.wall.listen(message => { switch (message.type) { case 'call': case 'event': case 'many-events': // Any of these types indicate the v3 backend. dispatch({ canBeDismissed: false, id: 'WarnIfLegacyBackendDetected', type: 'SHOW', title: 'DevTools v4 is incompatible with this version of React', content: <InvalidBackendDetected />, }); // Once we've identified the backend version, it's safe to unsubscribe. if (typeof unlisten === 'function') { unlisten(); unlisten = null; } break; default: break; } switch (message.event) { case 'isBackendStorageAPISupported': case 'isNativeStyleEditorSupported': case 'operations': case 'overrideComponentFilters': // Any of these is sufficient to indicate a v4 backend. // Once we've identified the backend version, it's safe to unsubscribe. if (typeof unlisten === 'function') { unlisten(); unlisten = null; } break; default: break; } }); return () => { if (typeof unlisten === 'function') { unlisten(); unlisten = null; } }; }, [bridge, dispatch]); return null; } function InvalidBackendDetected(_: {}) { return ( <Fragment> <p>Either upgrade React or install React DevTools v3:</p> <code className={styles.Command}>npm install -d react-devtools@^3</code> </Fragment> ); }
28.476744
88
0.603394
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListItem = ListItem; exports.List = List; 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 ListItem({ item, removeItem, toggleItem }) { const handleDelete = (0, React.useCallback)(() => { removeItem(item); }, [item, removeItem]); const handleToggle = (0, React.useCallback)(() => { toggleItem(item); }, [item, toggleItem]); return /*#__PURE__*/React.createElement("li", { __source: { fileName: _jsxFileName, lineNumber: 23, columnNumber: 5 } }, /*#__PURE__*/React.createElement("button", { onClick: handleDelete, __source: { fileName: _jsxFileName, lineNumber: 24, columnNumber: 7 } }, "Delete"), /*#__PURE__*/React.createElement("label", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, /*#__PURE__*/React.createElement("input", { checked: item.isComplete, onChange: handleToggle, type: "checkbox", __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 9 } }), ' ', item.text)); } function List(props) { const [newItemText, setNewItemText] = (0, React.useState)(''); const [items, setItems] = (0, React.useState)([{ id: 1, isComplete: true, text: 'First' }, { id: 2, isComplete: true, text: 'Second' }, { id: 3, isComplete: false, text: 'Third' }]); const [uid, setUID] = (0, React.useState)(4); const handleClick = (0, React.useCallback)(() => { if (newItemText !== '') { setItems([...items, { id: uid, isComplete: false, text: newItemText }]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = (0, React.useCallback)(event => { if (event.key === 'Enter') { handleClick(); } }, [handleClick]); const handleChange = (0, React.useCallback)(event => { setNewItemText(event.currentTarget.value); }, [setNewItemText]); const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]); const toggleItem = (0, React.useCallback)(itemToToggle => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); setItems(items.slice(0, index).concat({ ...itemToToggle, isComplete: !itemToToggle.isComplete }).concat(items.slice(index + 1))); }, [items]); return /*#__PURE__*/React.createElement(React.Fragment, { __source: { fileName: _jsxFileName, lineNumber: 102, columnNumber: 5 } }, /*#__PURE__*/React.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 103, columnNumber: 7 } }, "List"), /*#__PURE__*/React.createElement("input", { type: "text", placeholder: "New list item...", value: newItemText, onChange: handleChange, onKeyPress: handleKeyPress, __source: { fileName: _jsxFileName, lineNumber: 104, columnNumber: 7 } }), /*#__PURE__*/React.createElement("button", { disabled: newItemText === '', onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 111, columnNumber: 7 } }, /*#__PURE__*/React.createElement("span", { role: "img", "aria-label": "Add item", __source: { fileName: _jsxFileName, lineNumber: 112, columnNumber: 9 } }, "Add")), /*#__PURE__*/React.createElement("ul", { __source: { fileName: _jsxFileName, lineNumber: 116, columnNumber: 7 } }, items.map(item => /*#__PURE__*/React.createElement(ListItem, { key: item.id, item: item, removeItem: removeItem, toggleItem: toggleItem, __source: { fileName: _jsxFileName, lineNumber: 118, columnNumber: 11 } })))); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlRvRG9MaXN0LmpzIl0sIm5hbWVzIjpbIkxpc3RJdGVtIiwiaXRlbSIsInJlbW92ZUl0ZW0iLCJ0b2dnbGVJdGVtIiwiaGFuZGxlRGVsZXRlIiwiaGFuZGxlVG9nZ2xlIiwiaXNDb21wbGV0ZSIsInRleHQiLCJMaXN0IiwicHJvcHMiLCJuZXdJdGVtVGV4dCIsInNldE5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJzZXRJdGVtcyIsImlkIiwidWlkIiwic2V0VUlEIiwiaGFuZGxlQ2xpY2siLCJoYW5kbGVLZXlQcmVzcyIsImV2ZW50Iiwia2V5IiwiaGFuZGxlQ2hhbmdlIiwiY3VycmVudFRhcmdldCIsInZhbHVlIiwiaXRlbVRvUmVtb3ZlIiwiZmlsdGVyIiwiaXRlbVRvVG9nZ2xlIiwiaW5kZXgiLCJmaW5kSW5kZXgiLCJzbGljZSIsImNvbmNhdCIsIm1hcCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFHTyxTQUFTQSxRQUFULENBQWtCO0FBQUNDLEVBQUFBLElBQUQ7QUFBT0MsRUFBQUEsVUFBUDtBQUFtQkMsRUFBQUE7QUFBbkIsQ0FBbEIsRUFBa0Q7QUFDdkQsUUFBTUMsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0QsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPQyxVQUFQLENBRmtCLENBQXJCO0FBSUEsUUFBTUcsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0YsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPRSxVQUFQLENBRmtCLENBQXJCO0FBSUEsc0JBQ0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0U7QUFBUSxJQUFBLE9BQU8sRUFBRUMsWUFBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQ0UsSUFBQSxPQUFPLEVBQUVILElBQUksQ0FBQ0ssVUFEaEI7QUFFRSxJQUFBLFFBQVEsRUFBRUQsWUFGWjtBQUdFLElBQUEsSUFBSSxFQUFDLFVBSFA7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFERixFQUtLLEdBTEwsRUFNR0osSUFBSSxDQUFDTSxJQU5SLENBRkYsQ0FERjtBQWFEOztBQUVNLFNBQVNDLElBQVQsQ0FBY0MsS0FBZCxFQUFxQjtBQUMxQixRQUFNLENBQUNDLFdBQUQsRUFBY0MsY0FBZCxJQUFnQyxvQkFBUyxFQUFULENBQXRDO0FBQ0EsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0Isb0JBQVMsQ0FDakM7QUFBQ0MsSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FEaUMsRUFFakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FGaUMsRUFHakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLEtBQXBCO0FBQTJCQyxJQUFBQSxJQUFJLEVBQUU7QUFBakMsR0FIaUMsQ0FBVCxDQUExQjtBQUtBLFFBQU0sQ0FBQ1EsR0FBRCxFQUFNQyxNQUFOLElBQWdCLG9CQUFTLENBQVQsQ0FBdEI7QUFFQSxRQUFNQyxXQUFXLEdBQUcsdUJBQVksTUFBTTtBQUNwQyxRQUFJUCxXQUFXLEtBQUssRUFBcEIsRUFBd0I7QUFDdEJHLE1BQUFBLFFBQVEsQ0FBQyxDQUNQLEdBQUdELEtBREksRUFFUDtBQUNFRSxRQUFBQSxFQUFFLEVBQUVDLEdBRE47QUFFRVQsUUFBQUEsVUFBVSxFQUFFLEtBRmQ7QUFHRUMsUUFBQUEsSUFBSSxFQUFFRztBQUhSLE9BRk8sQ0FBRCxDQUFSO0FBUUFNLE1BQUFBLE1BQU0sQ0FBQ0QsR0FBRyxHQUFHLENBQVAsQ0FBTjtBQUNBSixNQUFBQSxjQUFjLENBQUMsRUFBRCxDQUFkO0FBQ0Q7QUFDRixHQWJtQixFQWFqQixDQUFDRCxXQUFELEVBQWNFLEtBQWQsRUFBcUJHLEdBQXJCLENBYmlCLENBQXBCO0FBZUEsUUFBTUcsY0FBYyxHQUFHLHVCQUNyQkMsS0FBSyxJQUFJO0FBQ1AsUUFBSUEsS0FBSyxDQUFDQyxHQUFOLEtBQWMsT0FBbEIsRUFBMkI7QUFDekJILE1BQUFBLFdBQVc7QUFDWjtBQUNGLEdBTG9CLEVBTXJCLENBQUNBLFdBQUQsQ0FOcUIsQ0FBdkI7QUFTQSxRQUFNSSxZQUFZLEdBQUcsdUJBQ25CRixLQUFLLElBQUk7QUFDUFIsSUFBQUEsY0FBYyxDQUFDUSxLQUFLLENBQUNHLGFBQU4sQ0FBb0JDLEtBQXJCLENBQWQ7QUFDRCxHQUhrQixFQUluQixDQUFDWixjQUFELENBSm1CLENBQXJCO0FBT0EsUUFBTVQsVUFBVSxHQUFHLHVCQUNqQnNCLFlBQVksSUFBSVgsUUFBUSxDQUFDRCxLQUFLLENBQUNhLE1BQU4sQ0FBYXhCLElBQUksSUFBSUEsSUFBSSxLQUFLdUIsWUFBOUIsQ0FBRCxDQURQLEVBRWpCLENBQUNaLEtBQUQsQ0FGaUIsQ0FBbkI7QUFLQSxRQUFNVCxVQUFVLEdBQUcsdUJBQ2pCdUIsWUFBWSxJQUFJO0FBQ2Q7QUFDQTtBQUNBLFVBQU1DLEtBQUssR0FBR2YsS0FBSyxDQUFDZ0IsU0FBTixDQUFnQjNCLElBQUksSUFBSUEsSUFBSSxDQUFDYSxFQUFMLEtBQVlZLFlBQVksQ0FBQ1osRUFBakQsQ0FBZDtBQUVBRCxJQUFBQSxRQUFRLENBQ05ELEtBQUssQ0FDRmlCLEtBREgsQ0FDUyxDQURULEVBQ1lGLEtBRFosRUFFR0csTUFGSCxDQUVVLEVBQ04sR0FBR0osWUFERztBQUVOcEIsTUFBQUEsVUFBVSxFQUFFLENBQUNvQixZQUFZLENBQUNwQjtBQUZwQixLQUZWLEVBTUd3QixNQU5ILENBTVVsQixLQUFLLENBQUNpQixLQUFOLENBQVlGLEtBQUssR0FBRyxDQUFwQixDQU5WLENBRE0sQ0FBUjtBQVNELEdBZmdCLEVBZ0JqQixDQUFDZixLQUFELENBaEJpQixDQUFuQjtBQW1CQSxzQkFDRSxvQkFBQyxjQUFEO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLFlBREYsZUFFRTtBQUNFLElBQUEsSUFBSSxFQUFDLE1BRFA7QUFFRSxJQUFBLFdBQVcsRUFBQyxrQkFGZDtBQUdFLElBQUEsS0FBSyxFQUFFRixXQUhUO0FBSUUsSUFBQSxRQUFRLEVBQUVXLFlBSlo7QUFLRSxJQUFBLFVBQVUsRUFBRUgsY0FMZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQUZGLGVBU0U7QUFBUSxJQUFBLFFBQVEsRUFBRVIsV0FBVyxLQUFLLEVBQWxDO0FBQXNDLElBQUEsT0FBTyxFQUFFTyxXQUEvQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDRTtBQUFNLElBQUEsSUFBSSxFQUFDLEtBQVg7QUFBaUIsa0JBQVcsVUFBNUI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsV0FERixDQVRGLGVBY0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDR0wsS0FBSyxDQUFDbUIsR0FBTixDQUFVOUIsSUFBSSxpQkFDYixvQkFBQyxRQUFEO0FBQ0UsSUFBQSxHQUFHLEVBQUVBLElBQUksQ0FBQ2EsRUFEWjtBQUVFLElBQUEsSUFBSSxFQUFFYixJQUZSO0FBR0UsSUFBQSxVQUFVLEVBQUVDLFVBSGQ7QUFJRSxJQUFBLFVBQVUsRUFBRUMsVUFKZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQURELENBREgsQ0FkRixDQURGO0FBMkJEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0JztcbmltcG9ydCB7RnJhZ21lbnQsIHVzZUNhbGxiYWNrLCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gTGlzdEl0ZW0oe2l0ZW0sIHJlbW92ZUl0ZW0sIHRvZ2dsZUl0ZW19KSB7XG4gIGNvbnN0IGhhbmRsZURlbGV0ZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICByZW1vdmVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgcmVtb3ZlSXRlbV0pO1xuXG4gIGNvbnN0IGhhbmRsZVRvZ2dsZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICB0b2dnbGVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgdG9nZ2xlSXRlbV0pO1xuXG4gIHJldHVybiAoXG4gICAgPGxpPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXtoYW5kbGVEZWxldGV9PkRlbGV0ZTwvYnV0dG9uPlxuICAgICAgPGxhYmVsPlxuICAgICAgICA8aW5wdXRcbiAgICAgICAgICBjaGVja2VkPXtpdGVtLmlzQ29tcGxldGV9XG4gICAgICAgICAgb25DaGFuZ2U9e2hhbmRsZVRvZ2dsZX1cbiAgICAgICAgICB0eXBlPVwiY2hlY2tib3hcIlxuICAgICAgICAvPnsnICd9XG4gICAgICAgIHtpdGVtLnRleHR9XG4gICAgICA8L2xhYmVsPlxuICAgIDwvbGk+XG4gICk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBMaXN0KHByb3BzKSB7XG4gIGNvbnN0IFtuZXdJdGVtVGV4dCwgc2V0TmV3SXRlbVRleHRdID0gdXNlU3RhdGUoJycpO1xuICBjb25zdCBbaXRlbXMsIHNldEl0ZW1zXSA9IHVzZVN0YXRlKFtcbiAgICB7aWQ6IDEsIGlzQ29tcGxldGU6IHRydWUsIHRleHQ6ICdGaXJzdCd9LFxuICAgIHtpZDogMiwgaXNDb21wbGV0ZTogdHJ1ZSwgdGV4dDogJ1NlY29uZCd9LFxuICAgIHtpZDogMywgaXNDb21wbGV0ZTogZmFsc2UsIHRleHQ6ICdUaGlyZCd9LFxuICBdKTtcbiAgY29uc3QgW3VpZCwgc2V0VUlEXSA9IHVzZVN0YXRlKDQpO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gdXNlQ2FsbGJhY2soKCkgPT4ge1xuICAgIGlmIChuZXdJdGVtVGV4dCAhPT0gJycpIHtcbiAgICAgIHNldEl0ZW1zKFtcbiAgICAgICAgLi4uaXRlbXMsXG4gICAgICAgIHtcbiAgICAgICAgICBpZDogdWlkLFxuICAgICAgICAgIGlzQ29tcGxldGU6IGZhbHNlLFxuICAgICAgICAgIHRleHQ6IG5ld0l0ZW1UZXh0LFxuICAgICAgICB9LFxuICAgICAgXSk7XG4gICAgICBzZXRVSUQodWlkICsgMSk7XG4gICAgICBzZXROZXdJdGVtVGV4dCgnJyk7XG4gICAgfVxuICB9LCBbbmV3SXRlbVRleHQsIGl0ZW1zLCB1aWRdKTtcblxuICBjb25zdCBoYW5kbGVLZXlQcmVzcyA9IHVzZUNhbGxiYWNrKFxuICAgIGV2ZW50ID0+IHtcbiAgICAgIGlmIChldmVudC5rZXkgPT09ICdFbnRlcicpIHtcbiAgICAgICAgaGFuZGxlQ2xpY2soKTtcbiAgICAgIH1cbiAgICB9LFxuICAgIFtoYW5kbGVDbGlja10sXG4gICk7XG5cbiAgY29uc3QgaGFuZGxlQ2hhbmdlID0gdXNlQ2FsbGJhY2soXG4gICAgZXZlbnQgPT4ge1xuICAgICAgc2V0TmV3SXRlbVRleHQoZXZlbnQuY3VycmVudFRhcmdldC52YWx1ZSk7XG4gICAgfSxcbiAgICBbc2V0TmV3SXRlbVRleHRdLFxuICApO1xuXG4gIGNvbnN0IHJlbW92ZUl0ZW0gPSB1c2VDYWxsYmFjayhcbiAgICBpdGVtVG9SZW1vdmUgPT4gc2V0SXRlbXMoaXRlbXMuZmlsdGVyKGl0ZW0gPT4gaXRlbSAhPT0gaXRlbVRvUmVtb3ZlKSksXG4gICAgW2l0ZW1zXSxcbiAgKTtcblxuICBjb25zdCB0b2dnbGVJdGVtID0gdXNlQ2FsbGJhY2soXG4gICAgaXRlbVRvVG9nZ2xlID0+IHtcbiAgICAgIC8vIERvbnQgdXNlIGluZGV4T2YoKVxuICAgICAgLy8gYmVjYXVzZSBlZGl0aW5nIHByb3BzIGluIERldlRvb2xzIGNyZWF0ZXMgYSBuZXcgT2JqZWN0LlxuICAgICAgY29uc3QgaW5kZXggPSBpdGVtcy5maW5kSW5kZXgoaXRlbSA9PiBpdGVtLmlkID09PSBpdGVtVG9Ub2dnbGUuaWQpO1xuXG4gICAgICBzZXRJdGVtcyhcbiAgICAgICAgaXRlbXNcbiAgICAgICAgICAuc2xpY2UoMCwgaW5kZXgpXG4gICAgICAgICAgLmNvbmNhdCh7XG4gICAgICAgICAgICAuLi5pdGVtVG9Ub2dnbGUsXG4gICAgICAgICAgICBpc0NvbXBsZXRlOiAhaXRlbVRvVG9nZ2xlLmlzQ29tcGxldGUsXG4gICAgICAgICAgfSlcbiAgICAgICAgICAuY29uY2F0KGl0ZW1zLnNsaWNlKGluZGV4ICsgMSkpLFxuICAgICAgKTtcbiAgICB9LFxuICAgIFtpdGVtc10sXG4gICk7XG5cbiAgcmV0dXJuIChcbiAgICA8RnJhZ21lbnQ+XG4gICAgICA8aDE+TGlzdDwvaDE+XG4gICAgICA8aW5wdXRcbiAgICAgICAgdHlwZT1cInRleHRcIlxuICAgICAgICBwbGFjZWhvbGRlcj1cIk5ldyBsaXN0IGl0ZW0uLi5cIlxuICAgICAgICB2YWx1ZT17bmV3SXRlbVRleHR9XG4gICAgICAgIG9uQ2hhbmdlPXtoYW5kbGVDaGFuZ2V9XG4gICAgICAgIG9uS2V5UHJlc3M9e2hhbmRsZUtleVByZXNzfVxuICAgICAgLz5cbiAgICAgIDxidXR0b24gZGlzYWJsZWQ9e25ld0l0ZW1UZXh0ID09PSAnJ30gb25DbGljaz17aGFuZGxlQ2xpY2t9PlxuICAgICAgICA8c3BhbiByb2xlPVwiaW1nXCIgYXJpYS1sYWJlbD1cIkFkZCBpdGVtXCI+XG4gICAgICAgICAgQWRkXG4gICAgICAgIDwvc3Bhbj5cbiAgICAgIDwvYnV0dG9uPlxuICAgICAgPHVsPlxuICAgICAgICB7aXRlbXMubWFwKGl0ZW0gPT4gKFxuICAgICAgICAgIDxMaXN0SXRlbVxuICAgICAgICAgICAga2V5PXtpdGVtLmlkfVxuICAgICAgICAgICAgaXRlbT17aXRlbX1cbiAgICAgICAgICAgIHJlbW92ZUl0ZW09e3JlbW92ZUl0ZW19XG4gICAgICAgICAgICB0b2dnbGVJdGVtPXt0b2dnbGVJdGVtfVxuICAgICAgICAgIC8+XG4gICAgICAgICkpfVxuICAgICAgPC91bD5cbiAgICA8L0ZyYWdtZW50PlxuICApO1xufVxuIl19
84.94375
8,784
0.854473
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-local */ export opaque type PublicInstance = mixed; export opaque type PublicTextInstance = mixed; module.exports = { get BatchedBridge() { return require('./BatchedBridge.js'); }, get Platform() { return require('./Platform'); }, get RCTEventEmitter() { return require('./RCTEventEmitter'); }, get ReactFiberErrorDialog() { return require('./ReactFiberErrorDialog'); }, get ReactNativeViewConfigRegistry() { return require('./ReactNativeViewConfigRegistry'); }, get TextInputState() { return require('./TextInputState'); }, get UIManager() { return require('./UIManager'); }, get deepDiffer() { return require('./deepDiffer'); }, get deepFreezeAndThrowOnMutationInDev() { return require('./deepFreezeAndThrowOnMutationInDev'); }, get flattenStyle() { return require('./flattenStyle'); }, get legacySendAccessibilityEvent() { return require('./legacySendAccessibilityEvent'); }, get RawEventEmitter() { return require('./RawEventEmitter').default; }, get getNativeTagFromPublicInstance() { return require('./getNativeTagFromPublicInstance').default; }, get getNodeFromPublicInstance() { return require('./getNodeFromPublicInstance').default; }, get createPublicInstance() { return require('./createPublicInstance').default; }, get createPublicTextInstance() { return require('./createPublicTextInstance').default; }, };
25.31746
66
0.689801
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 url = require('url'); const Module = require('module'); let webpackModuleIdx = 0; const webpackServerModules = {}; const webpackClientModules = {}; const webpackErroredModules = {}; const webpackServerMap = {}; const webpackClientMap = {}; global.__webpack_require__ = function (id) { if (webpackErroredModules[id]) { throw webpackErroredModules[id]; } return webpackClientModules[id] || webpackServerModules[id]; }; const previousCompile = Module.prototype._compile; const register = require('react-server-dom-webpack/node-register'); // Register node compile register(); const nodeCompile = Module.prototype._compile; if (previousCompile === nodeCompile) { throw new Error( 'Expected the Node loader to register the _compile extension', ); } Module.prototype._compile = previousCompile; exports.webpackMap = webpackClientMap; exports.webpackModules = webpackClientModules; exports.webpackServerMap = webpackServerMap; exports.moduleLoading = { prefix: '/', }; exports.clientModuleError = function clientModuleError(moduleError) { const idx = '' + webpackModuleIdx++; webpackErroredModules[idx] = moduleError; const path = url.pathToFileURL(idx).href; webpackClientMap[path] = { id: idx, chunks: [], name: '*', }; const mod = {exports: {}}; nodeCompile.call(mod, '"use client"', idx); return mod.exports; }; exports.clientExports = function clientExports( moduleExports, chunkId, chunkFilename, ) { const chunks = []; if (chunkId) { chunks.push(chunkId, chunkFilename); } const idx = '' + webpackModuleIdx++; webpackClientModules[idx] = moduleExports; const path = url.pathToFileURL(idx).href; webpackClientMap[path] = { id: idx, chunks, name: '*', }; // We only add this if this test is testing ESM compat. if ('__esModule' in moduleExports) { webpackClientMap[path + '#'] = { id: idx, chunks, name: '', }; } if (typeof moduleExports.then === 'function') { moduleExports.then( asyncModuleExports => { for (const name in asyncModuleExports) { webpackClientMap[path + '#' + name] = { id: idx, chunks, name: name, }; } }, () => {}, ); } if ('split' in moduleExports) { // If we're testing module splitting, we encode this name in a separate module id. const splitIdx = '' + webpackModuleIdx++; webpackClientModules[splitIdx] = { s: moduleExports.split, }; webpackClientMap[path + '#split'] = { id: splitIdx, chunks, name: 's', }; } const mod = {exports: {}}; nodeCompile.call(mod, '"use client"', idx); return mod.exports; }; // This tests server to server references. There's another case of client to server references. exports.serverExports = function serverExports(moduleExports) { const idx = '' + webpackModuleIdx++; webpackServerModules[idx] = moduleExports; const path = url.pathToFileURL(idx).href; webpackServerMap[path] = { id: idx, chunks: [], name: '*', }; // We only add this if this test is testing ESM compat. if ('__esModule' in moduleExports) { webpackServerMap[path + '#'] = { id: idx, chunks: [], name: '', }; } if ('split' in moduleExports) { // If we're testing module splitting, we encode this name in a separate module id. const splitIdx = '' + webpackModuleIdx++; webpackServerModules[splitIdx] = { s: moduleExports.split, }; webpackServerMap[path + '#split'] = { id: splitIdx, chunks: [], name: 's', }; } const mod = {exports: moduleExports}; nodeCompile.call(mod, '"use server"', idx); return mod.exports; };
24.810458
95
0.641844
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('profiling utils', () => { let utils; beforeEach(() => { utils = require('react-devtools-shared/src/devtools/views/Profiler/utils'); }); it('should throw if importing older/unsupported data', () => { expect(() => utils.prepareProfilingDataFrontendFromExport( ({ version: 0, dataForRoots: [], }: any), ), ).toThrow('Unsupported profile export version'); }); });
22.107143
79
0.609907
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 {useContext, useEffect} from 'react'; import {RegistryContext} from './Contexts'; import type {OnChangeFn, RegistryContextType} from './Contexts'; import type {ElementRef} from 'react'; export default function useContextMenu({ data, id, onChange, ref, }: { data: Object, id: string, onChange?: OnChangeFn, ref: {current: ElementRef<any> | null}, }) { const {showMenu} = useContext<RegistryContextType>(RegistryContext); useEffect(() => { if (ref.current !== null) { const handleContextMenu = (event: MouseEvent | TouchEvent) => { event.preventDefault(); event.stopPropagation(); const pageX = (event: any).pageX || (event.touches && (event: any).touches[0].pageX); const pageY = (event: any).pageY || (event.touches && (event: any).touches[0].pageY); showMenu({data, id, onChange, pageX, pageY}); }; const trigger = ref.current; trigger.addEventListener('contextmenu', handleContextMenu); return () => { trigger.removeEventListener('contextmenu', handleContextMenu); }; } }, [data, id, showMenu]); }
24.425926
70
0.627551
cybersecurity-penetration-testing
// This is a generated file. The source files are in react-dom-bindings/src/server/fizz-instruction-set. // The build script is at scripts/rollup/generate-inline-fizz-runtime.js. // Run `yarn generate-inline-fizz-runtime` to generate. export const clientRenderBoundary = '$RX=function(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};'; export const completeBoundary = '$RC=function(b,c,e){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(e)b.data="$!",a.setAttribute("data-dgst",e);else{e=b.parentNode;a=b.nextSibling;var f=0;do{if(a&&8===a.nodeType){var d=a.data;if("/$"===d)if(0===f)break;else f--;else"$"!==d&&"$?"!==d&&"$!"!==d||f++}d=a.nextSibling;e.removeChild(a);a=d}while(a);for(;c.firstChild;)e.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}};'; export const completeBoundaryWithStyles = '$RM=new Map;\n$RR=function(r,t,w){for(var u=$RC,n=$RM,p=new Map,q=document,g,b,h=q.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=h[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&n.set(b.getAttribute("href"),b),p.set(b.dataset.precedence,g=b));b=0;h=[];var l,a;for(k=!0;;){if(k){var f=w[b++];if(!f){k=!1;b=0;continue}var c=!1,m=0;var d=f[m++];if(a=n.get(d)){var e=a._p;c=!0}else{a=q.createElement("link");a.href=d;a.rel="stylesheet";for(a.dataset.precedence=\nl=f[m++];e=f[m++];)a.setAttribute(e,f[m++]);e=a._p=new Promise(function(x,y){a.onload=x;a.onerror=y});n.set(d,a)}d=a.getAttribute("media");!e||"l"===e.s||d&&!matchMedia(d).matches||h.push(e);if(c)continue}else{a=v[b++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=p.get(l)||g;c===g&&(g=a);p.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=q.head,c.insertBefore(a,c.firstChild))}Promise.all(h).then(u.bind(null,r,t,""),u.bind(null,r,t,"Resource failed to load"))};'; export const completeSegment = '$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};'; export const formReplaying = 'addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error(\'A React form was unexpectedly submitted.\')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.getRootNode(),(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,\nd,b))}});';
200.214286
1,024
0.694602
null
#!/usr/bin/env node 'use strict'; const prompt = require('prompt-promise'); const theme = require('../theme'); const run = async () => { while (true) { const otp = await prompt('NPM 2-factor auth code: '); prompt.done(); if (otp) { return otp; } else { console.log(); console.log(theme.error`Two-factor auth is required to publish.`); // (Ask again.) } } }; module.exports = run;
17.083333
72
0.572748
PenetrationTestingScripts
#!/usr/bin/env node 'use strict'; const chalk = require('chalk'); const build = require('../build'); const main = async () => { await build('firefox'); console.log(chalk.green('\nThe Firefox extension has been built!')); console.log(chalk.green('You can test this build by running:')); console.log(chalk.gray('\n# From the react-devtools root directory:')); console.log('yarn run test:firefox'); console.log( chalk.gray('\n# You can also test against upcoming Firefox releases.') ); console.log( chalk.gray( '# First download a release from https://www.mozilla.org/en-US/firefox/channel/desktop/' ) ); console.log( chalk.gray( '# And then tell web-ext which release to use (eg firefoxdeveloperedition, nightly, beta):' ) ); console.log('WEB_EXT_FIREFOX=nightly yarn run test:firefox'); console.log(chalk.gray('\n# You can test against older versions too:')); console.log( 'WEB_EXT_FIREFOX=/Applications/Firefox Developer Edition.app/Contents/MacOS/firefox-bin yarn run test:firefox' ); }; main(); module.exports = {main};
27.815789
114
0.678245
PenetrationTestingScripts
function hasAbsoluteFileName(hook) { const fileName = hook.hookSource ? hook.hookSource.fileName : null; if (fileName == null) { return false; } else { return fileName.indexOf('/react-devtools-shared/') > 0; } } function serializeHook(hook) { if (!hook.hookSource) return hook; // Remove user-specific portions of this file path. let fileName = hook.hookSource.fileName; const index = fileName.lastIndexOf('/react-devtools-shared/'); fileName = fileName.slice(index + 1); let subHooks = hook.subHooks; if (subHooks) { subHooks = subHooks.map(serializeHook); } return { ...hook, hookSource: { ...hook.hookSource, fileName, // Otherwise changes in any test case or formatting might invalidate other tests. columnNumber: 'removed by Jest serializer', lineNumber: 'removed by Jest serializer', }, subHooks, }; } // test() is part of Jest's serializer API export function test(maybeHook) { if (maybeHook === null || typeof maybeHook !== 'object') { return false; } const hasOwnProperty = Object.prototype.hasOwnProperty.bind(maybeHook); return ( hasOwnProperty('id') && hasOwnProperty('isStateEditable') && hasOwnProperty('name') && hasOwnProperty('subHooks') && hasOwnProperty('value') && // Don't re-process an already printed hook. hasAbsoluteFileName(maybeHook) ); } // print() is part of Jest's serializer API export function print(hook, serialize, indent) { // Don't stringify this object; that would break nested serializers. return serialize(serializeHook(hook)); }
25.409836
87
0.678882
owtf
'use strict'; const fs = require('fs'); const path = require('path'); const paths = require('./paths'); // Make sure that including paths.js after env.js will read .env variables. delete require.cache[require.resolve('./paths')]; const NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV) { throw new Error( 'The NODE_ENV environment variable is required but was not specified.' ); } // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use const dotenvFiles = [ `${paths.dotenv}.${NODE_ENV}.local`, // Don't include `.env.local` for `test` environment // since normally you expect tests to produce the same // results for everyone NODE_ENV !== 'test' && `${paths.dotenv}.local`, `${paths.dotenv}.${NODE_ENV}`, paths.dotenv, ].filter(Boolean); // Load environment variables from .env* files. Suppress warnings using silent // if this file is missing. dotenv will never modify any environment variables // that have already been set. Variable expansion is supported in .env files. // https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv-expand dotenvFiles.forEach(dotenvFile => { if (fs.existsSync(dotenvFile)) { require('dotenv-expand')( require('dotenv').config({ path: dotenvFile, }) ); } }); // We support resolving modules according to `NODE_PATH`. // This lets you use absolute paths in imports inside large monorepos: // https://github.com/facebook/create-react-app/issues/253. // It works similar to `NODE_PATH` in Node itself: // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. // Otherwise, we risk importing Node.js core modules into an app instead of webpack shims. // https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 // We also resolve them to make sure all tools using them work consistently. const appDirectory = fs.realpathSync(process.cwd()); process.env.NODE_PATH = (process.env.NODE_PATH || '') .split(path.delimiter) .filter(folder => folder && !path.isAbsolute(folder)) .map(folder => path.resolve(appDirectory, folder)) .join(path.delimiter); // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be // injected into the application via DefinePlugin in webpack configuration. const REACT_APP = /^REACT_APP_/i; function getClientEnvironment(publicUrl) { const raw = Object.keys(process.env) .filter(key => REACT_APP.test(key)) .reduce( (env, key) => { env[key] = process.env[key]; return env; }, { // Useful for determining whether we’re running in production mode. // Most importantly, it switches React into the correct mode. NODE_ENV: process.env.NODE_ENV || 'development', // Useful for resolving the correct path to static assets in `public`. // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />. // This should only be used as an escape hatch. Normally you would put // images into the `src` and `import` them in code to get their paths. PUBLIC_URL: publicUrl, // We support configuring the sockjs pathname during development. // These settings let a developer run multiple simultaneous projects. // They are used as the connection `hostname`, `pathname` and `port` // in webpackHotDevClient. They are used as the `sockHost`, `sockPath` // and `sockPort` options in webpack-dev-server. WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST, WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH, WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT, // Whether or not react-refresh is enabled. // It is defined here so it is available in the webpackHotDevClient. FAST_REFRESH: process.env.FAST_REFRESH !== 'false', } ); // Stringify all values so we can feed into webpack DefinePlugin const stringified = { 'process.env': Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {}), }; return {raw, stringified}; } module.exports = getClientEnvironment;
39.038095
90
0.683084
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. */ 'use strict'; // Mock of the Native Hooks const roots = new Map(); const allocatedTags = new Set(); function dumpSubtree(info, indent) { let out = ''; out += ' '.repeat(indent) + info.viewName + ' ' + JSON.stringify(info.props); // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const child of info.children) { out += '\n' + dumpSubtree(child, indent + 2); } return out; } const RCTFabricUIManager = { __dumpChildSetForJestTestsOnly: function (childSet) { const result = []; // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const child of childSet) { result.push(dumpSubtree(child, 0)); } return result.join('\n'); }, __dumpHierarchyForJestTestsOnly: function () { const result = []; // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const [rootTag, childSet] of roots) { result.push(rootTag); // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const child of childSet) { result.push(dumpSubtree(child, 1)); } } return result.join('\n'); }, createNode: jest.fn( function createNode(reactTag, viewName, rootTag, props, eventTarget) { if (allocatedTags.has(reactTag)) { throw new Error(`Created two native views with tag ${reactTag}`); } allocatedTags.add(reactTag); return { reactTag: reactTag, viewName: viewName, props: props, children: [], }; }, ), cloneNode: jest.fn(function cloneNode(node) { return { reactTag: node.reactTag, viewName: node.viewName, props: node.props, children: node.children, }; }), cloneNodeWithNewChildren: jest.fn( function cloneNodeWithNewChildren(node, children) { return { reactTag: node.reactTag, viewName: node.viewName, props: node.props, children: children ?? [], }; }, ), cloneNodeWithNewProps: jest.fn( function cloneNodeWithNewProps(node, newPropsDiff) { return { reactTag: node.reactTag, viewName: node.viewName, props: {...node.props, ...newPropsDiff}, children: node.children, }; }, ), cloneNodeWithNewChildrenAndProps: jest.fn( function cloneNodeWithNewChildrenAndProps(node, newPropsDiff) { let children = []; if (arguments.length === 3) { children = newPropsDiff; newPropsDiff = arguments[2]; } return { reactTag: node.reactTag, viewName: node.viewName, props: {...node.props, ...newPropsDiff}, children, }; }, ), appendChild: jest.fn(function appendChild(parentNode, childNode) { parentNode.children.push(childNode); }), createChildSet: jest.fn(function createChildSet() { return []; }), appendChildToSet: jest.fn(function appendChildToSet(childSet, childNode) { childSet.push(childNode); }), completeRoot: jest.fn(function completeRoot(rootTag, newChildSet) { roots.set(rootTag, newChildSet); }), dispatchCommand: jest.fn(), setNativeProps: jest.fn(), sendAccessibilityEvent: jest.fn(), registerEventHandler: jest.fn(function registerEventHandler(callback) {}), measure: jest.fn(function measure(node, callback) { if (typeof node !== 'object') { throw new Error( `Expected node to be an object, was passed "${typeof node}"`, ); } if (typeof node.viewName !== 'string') { throw new Error('Expected node to be a host node.'); } callback(10, 10, 100, 100, 0, 0); }), measureInWindow: jest.fn(function measureInWindow(node, callback) { if (typeof node !== 'object') { throw new Error( `Expected node to be an object, was passed "${typeof node}"`, ); } if (typeof node.viewName !== 'string') { throw new Error('Expected node to be a host node.'); } callback(10, 10, 100, 100); }), getBoundingClientRect: jest.fn(function getBoundingClientRect(node) { if (typeof node !== 'object') { throw new Error( `Expected node to be an object, was passed "${typeof node}"`, ); } if (typeof node.viewName !== 'string') { throw new Error('Expected node to be a host node.'); } return [10, 10, 100, 100]; }), measureLayout: jest.fn( function measureLayout(node, relativeNode, fail, success) { if (typeof node !== 'object') { throw new Error( `Expected node to be an object, was passed "${typeof node}"`, ); } if (typeof node.viewName !== 'string') { throw new Error('Expected node to be a host node.'); } if (typeof relativeNode !== 'object') { throw new Error( `Expected relative node to be an object, was passed "${typeof relativeNode}"`, ); } if (typeof relativeNode.viewName !== 'string') { throw new Error('Expected relative node to be a host node.'); } success(1, 1, 100, 100); }, ), setIsJSResponder: jest.fn(), }; global.nativeFabricUIManager = RCTFabricUIManager; // DOMRect isn't provided by jsdom, but it's used by `ReactFabricHostComponent`. // This is a basic implementation for testing. global.DOMRect = class DOMRect { constructor(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } toJSON() { const {x, y, width, height} = this; return {x, y, width, height}; } };
25.779343
88
0.613361
owtf
import Fixture from '../../Fixture'; const React = window.React; class RangeKeyboardFixture extends React.Component { constructor(props, context) { super(props, context); this.state = { keydownCount: 0, changeCount: 0, }; } componentDidMount() { this.input.addEventListener('keydown', this.handleKeydown, false); } componentWillUnmount() { this.input.removeEventListener('keydown', this.handleKeydown, false); } handleChange = () => { this.setState(({changeCount}) => { return { changeCount: changeCount + 1, }; }); }; handleKeydown = e => { // only interesting in arrow key events if ([37, 38, 39, 40].indexOf(e.keyCode) < 0) { return; } this.setState(({keydownCount}) => { return { keydownCount: keydownCount + 1, }; }); }; handleReset = () => { this.setState({ keydownCount: 0, changeCount: 0, }); }; render() { const {keydownCount, changeCount} = this.state; const color = keydownCount === changeCount ? 'green' : 'red'; return ( <Fixture> <div> <input type="range" ref={r => (this.input = r)} onChange={this.handleChange} /> <button onClick={() => this.input.focus()}>Focus Knob</button> </div>{' '} <p style={{color}}> <code>onKeyDown</code> {' calls: '} <strong>{keydownCount}</strong> {' vs '} <code>onChange</code> {' calls: '} <strong>{changeCount}</strong> </p> <button onClick={this.handleReset}>Reset counts</button> </Fixture> ); } } export default RangeKeyboardFixture;
20.9375
73
0.537628
null
'use strict'; const http2Server = require('http2'); const httpServer = require('http-server'); const {existsSync, statSync, createReadStream} = require('fs'); const {join} = require('path'); const argv = require('minimist')(process.argv.slice(2)); const mime = require('mime'); function sendFile(filename, response) { response.setHeader('Content-Type', mime.lookup(filename)); response.writeHead(200); const fileStream = createReadStream(filename); fileStream.pipe(response); fileStream.on('finish', response.end); } function createHTTP2Server(benchmark) { const server = http2Server.createServer({}, (request, response) => { const filename = join( __dirname, 'benchmarks', benchmark, request.url ).replace(/\?.*/g, ''); if (existsSync(filename) && statSync(filename).isFile()) { sendFile(filename, response); } else { const indexHtmlPath = join(filename, 'index.html'); if (existsSync(indexHtmlPath)) { sendFile(indexHtmlPath, response); } else { response.writeHead(404); response.end(); } } }); server.listen(8080); return server; } function createHTTPServer() { const server = httpServer.createServer({ root: join(__dirname, 'benchmarks'), robots: true, cache: 'no-store', headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', }, }); server.listen(8080); return server; } function serveBenchmark(benchmark, http2) { if (http2) { return createHTTP2Server(benchmark); } else { return createHTTPServer(); } } // if run directly via CLI if (require.main === module) { const benchmarkInput = argv._[0]; if (benchmarkInput) { serveBenchmark(benchmarkInput); } else { console.error('Please specify a benchmark directory to serve!'); process.exit(1); } } module.exports = serveBenchmark;
23.316456
70
0.652604
null
'use strict'; // These flags can be in a @gate pragma to declare that a test depends on // certain conditions. They're like GKs. // // Examples: // // @gate enableSomeAPI // test('uses an unstable API', () => {/*...*/}) // // // @gate __DEV__ // test('only passes in development', () => {/*...*/}) // // Most flags are defined in ReactFeatureFlags. If it's defined there, you don't // have to do anything extra here. // // There are also flags based on the environment, like __DEV__. Feel free to // add new flags and aliases below. // // You can also combine flags using multiple gates: // // // @gate enableSomeAPI // // @gate __DEV__ // test('both conditions must pass', () => {/*...*/}) // // Or using logical operators // // @gate enableSomeAPI && __DEV__ // test('both conditions must pass', () => {/*...*/}) // // Negation also works: // // @gate !deprecateLegacyContext // test('uses a deprecated feature', () => {/*...*/}) // These flags are based on the environment and don't change for the entire // test run. const environmentFlags = { __DEV__, build: __DEV__ ? 'development' : 'production', // TODO: Should "experimental" also imply "modern"? Maybe we should // always compare to the channel? experimental: __EXPERIMENTAL__, // Similarly, should stable imply "classic"? stable: !__EXPERIMENTAL__, variant: __VARIANT__, persistent: global.__PERSISTENT__ === true, // Use this for tests that are known to be broken. FIXME: false, TODO: false, // Turn these flags back on (or delete) once the effect list is removed in // favor of a depth-first traversal using `subtreeTags`. dfsEffectsRefactor: true, enableUseJSStackToTrackPassiveDurations: false, }; function getTestFlags() { // These are required on demand because some of our tests mutate them. We try // not to but there are exceptions. const featureFlags = require('shared/ReactFeatureFlags'); const schedulerFeatureFlags = require('scheduler/src/SchedulerFeatureFlags'); const www = global.__WWW__ === true; const releaseChannel = www ? __EXPERIMENTAL__ ? 'modern' : 'classic' : __EXPERIMENTAL__ ? 'experimental' : 'stable'; // Return a proxy so we can throw if you attempt to access a flag that // doesn't exist. return new Proxy( { channel: releaseChannel, modern: releaseChannel === 'modern', classic: releaseChannel === 'classic', source: !process.env.IS_BUILD, www, // This isn't a flag, just a useful alias for tests. enableActivity: releaseChannel === 'experimental' || www, enableUseSyncExternalStoreShim: !__VARIANT__, enableSuspenseList: releaseChannel === 'experimental' || www, enableLegacyHidden: www, // If there's a naming conflict between scheduler and React feature flags, the // React ones take precedence. // TODO: Maybe we should error on conflicts? Or we could namespace // the flags ...schedulerFeatureFlags, ...featureFlags, ...environmentFlags, }, { get(flags, flagName) { const flagValue = flags[flagName]; if (flagValue === undefined && typeof flagName === 'string') { throw Error( `Feature flag "${flagName}" does not exist. See TestFlags.js ` + 'for more details.' ); } return flagValue; }, } ); } exports.getTestFlags = getTestFlags;
29.307018
84
0.629994