repo_name
stringlengths
4
68
text
stringlengths
21
269k
avg_line_length
float64
9.4
9.51k
max_line_length
int64
20
28.5k
alphnanum_fraction
float64
0.3
0.92
cybersecurity-penetration-testing
/** * 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('getEventKey', () => { let container; beforeEach(() => { React = require('react'); ReactDOM = require('react-dom'); // The container has to be attached for events to fire. container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); container = null; }); describe('when key is implemented in a browser', () => { describe('when key is not normalized', () => { it('returns a normalized value', () => { let key = null; class Comp extends React.Component { render() { return <input onKeyDown={e => (key = e.key)} />; } } ReactDOM.render(<Comp />, container); const nativeEvent = new KeyboardEvent('keydown', { key: 'Del', bubbles: true, cancelable: true, }); container.firstChild.dispatchEvent(nativeEvent); expect(key).toBe('Delete'); }); }); describe('when key is normalized', () => { it('returns a key', () => { let key = null; class Comp extends React.Component { render() { return <input onKeyDown={e => (key = e.key)} />; } } ReactDOM.render(<Comp />, container); const nativeEvent = new KeyboardEvent('keydown', { key: 'f', bubbles: true, cancelable: true, }); container.firstChild.dispatchEvent(nativeEvent); expect(key).toBe('f'); }); }); }); describe('when key is not implemented in a browser', () => { describe('when event type is keypress', () => { describe('when charCode is 13', () => { it('returns "Enter"', () => { let key = null; class Comp extends React.Component { render() { return <input onKeyPress={e => (key = e.key)} />; } } ReactDOM.render(<Comp />, container); const nativeEvent = new KeyboardEvent('keypress', { charCode: 13, bubbles: true, cancelable: true, }); container.firstChild.dispatchEvent(nativeEvent); expect(key).toBe('Enter'); }); }); describe('when charCode is not 13', () => { it('returns a string from a charCode', () => { let key = null; class Comp extends React.Component { render() { return <input onKeyPress={e => (key = e.key)} />; } } ReactDOM.render(<Comp />, container); const nativeEvent = new KeyboardEvent('keypress', { charCode: 65, bubbles: true, cancelable: true, }); container.firstChild.dispatchEvent(nativeEvent); expect(key).toBe('A'); }); }); }); describe('when event type is keydown or keyup', () => { describe('when keyCode is recognized', () => { it('returns a translated key', () => { let key = null; class Comp extends React.Component { render() { return <input onKeyDown={e => (key = e.key)} />; } } ReactDOM.render(<Comp />, container); const nativeEvent = new KeyboardEvent('keydown', { keyCode: 45, bubbles: true, cancelable: true, }); container.firstChild.dispatchEvent(nativeEvent); expect(key).toBe('Insert'); }); }); describe('when keyCode is not recognized', () => { it('returns Unidentified', () => { let key = null; class Comp extends React.Component { render() { return <input onKeyDown={e => (key = e.key)} />; } } ReactDOM.render(<Comp />, container); const nativeEvent = new KeyboardEvent('keydown', { keyCode: 1337, bubbles: true, cancelable: true, }); container.firstChild.dispatchEvent(nativeEvent); expect(key).toBe('Unidentified'); }); }); }); }); });
26.018072
66
0.507806
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. * * @jest-environment node */ let React; let Scheduler; let waitForAll; let assertLog; let ReactNoop; let useState; let act; let Suspense; let startTransition; let getCacheForType; let caches; // These tests are mostly concerned with concurrent roots. The legacy root // behavior is covered by other older test suites and is unchanged from // React 17. describe('act warnings', () => { beforeEach(() => { jest.resetModules(); React = require('react'); Scheduler = require('scheduler'); ReactNoop = require('react-noop-renderer'); act = React.unstable_act; useState = React.useState; Suspense = React.Suspense; startTransition = React.startTransition; getCacheForType = React.unstable_getCacheForType; caches = []; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; }); function createTextCache() { const data = new Map(); const version = caches.length + 1; const cache = { version, data, resolve(text) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } }, reject(text, error) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'rejected', value: error, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'rejected'; record.value = error; thenable.pings.forEach(t => t()); } }, }; caches.push(cache); return cache; } function readText(text) { const textCache = getCacheForType(createTextCache); const record = textCache.data.get(text); if (record !== undefined) { switch (record.status) { case 'pending': Scheduler.log(`Suspend! [${text}]`); throw record.value; case 'rejected': Scheduler.log(`Error! [${text}]`); throw record.value; case 'resolved': return textCache.version; } } else { Scheduler.log(`Suspend! [${text}]`); const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.data.set(text, newRecord); throw thenable; } } function Text({text}) { Scheduler.log(text); return text; } function AsyncText({text}) { readText(text); Scheduler.log(text); return text; } function resolveText(text) { if (caches.length === 0) { throw Error('Cache does not exist.'); } else { // Resolve the most recently created cache. An older cache can by // resolved with `caches[index].resolve(text)`. caches[caches.length - 1].resolve(text); } } async function withActEnvironment(value, scope) { const prevValue = global.IS_REACT_ACT_ENVIRONMENT; global.IS_REACT_ACT_ENVIRONMENT = value; try { return await scope(); } finally { global.IS_REACT_ACT_ENVIRONMENT = prevValue; } } test('warns about unwrapped updates only if environment flag is enabled', async () => { let setState; function App() { const [state, _setState] = useState(0); setState = _setState; return <Text text={state} />; } const root = ReactNoop.createRoot(); root.render(<App />); await waitForAll([0]); expect(root).toMatchRenderedOutput('0'); // Default behavior. Flag is undefined. No warning. expect(global.IS_REACT_ACT_ENVIRONMENT).toBe(undefined); setState(1); await waitForAll([1]); expect(root).toMatchRenderedOutput('1'); // Flag is true. Warn. await withActEnvironment(true, async () => { expect(() => setState(2)).toErrorDev( 'An update to App inside a test was not wrapped in act', ); await waitForAll([2]); expect(root).toMatchRenderedOutput('2'); }); // Flag is false. No warning. await withActEnvironment(false, async () => { setState(3); await waitForAll([3]); expect(root).toMatchRenderedOutput('3'); }); }); // @gate __DEV__ test('act warns if the environment flag is not enabled', async () => { let setState; function App() { const [state, _setState] = useState(0); setState = _setState; return <Text text={state} />; } const root = ReactNoop.createRoot(); root.render(<App />); await waitForAll([0]); expect(root).toMatchRenderedOutput('0'); // Default behavior. Flag is undefined. Warn. expect(global.IS_REACT_ACT_ENVIRONMENT).toBe(undefined); expect(() => { act(() => { setState(1); }); }).toErrorDev( 'The current testing environment is not configured to support act(...)', {withoutStack: true}, ); assertLog([1]); expect(root).toMatchRenderedOutput('1'); // Flag is true. Don't warn. await withActEnvironment(true, () => { act(() => { setState(2); }); assertLog([2]); expect(root).toMatchRenderedOutput('2'); }); // Flag is false. Warn. await withActEnvironment(false, () => { expect(() => { act(() => { setState(1); }); }).toErrorDev( 'The current testing environment is not configured to support act(...)', {withoutStack: true}, ); assertLog([1]); expect(root).toMatchRenderedOutput('1'); }); }); test('warns if root update is not wrapped', async () => { await withActEnvironment(true, () => { const root = ReactNoop.createRoot(); expect(() => root.render('Hi')).toErrorDev( // TODO: Better error message that doesn't make it look like "Root" is // the name of a custom component 'An update to Root inside a test was not wrapped in act(...)', {withoutStack: true}, ); }); }); // @gate __DEV__ test('warns if class update is not wrapped', async () => { let app; class App extends React.Component { state = {count: 0}; render() { app = this; return <Text text={this.state.count} />; } } await withActEnvironment(true, () => { const root = ReactNoop.createRoot(); act(() => { root.render(<App />); }); expect(() => app.setState({count: 1})).toErrorDev( 'An update to App inside a test was not wrapped in act(...)', ); }); }); // @gate __DEV__ test('warns even if update is synchronous', async () => { let setState; function App() { const [state, _setState] = useState(0); setState = _setState; return <Text text={state} />; } await withActEnvironment(true, () => { const root = ReactNoop.createRoot(); act(() => root.render(<App />)); assertLog([0]); expect(root).toMatchRenderedOutput('0'); // Even though this update is synchronous, we should still fire a warning, // because it could have spawned additional asynchronous work expect(() => ReactNoop.flushSync(() => setState(1))).toErrorDev( 'An update to App inside a test was not wrapped in act(...)', ); assertLog([1]); expect(root).toMatchRenderedOutput('1'); }); }); // @gate __DEV__ // @gate enableLegacyCache test('warns if Suspense retry is not wrapped', async () => { function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="Async" /> </Suspense> ); } await withActEnvironment(true, () => { const root = ReactNoop.createRoot(); act(() => { root.render(<App />); }); assertLog(['Suspend! [Async]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); // This is a retry, not a ping, because we already showed a fallback. expect(() => resolveText('Async')).toErrorDev( 'A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...)', {withoutStack: true}, ); }); }); // @gate __DEV__ // @gate enableLegacyCache test('warns if Suspense ping is not wrapped', async () => { function App({showMore}) { return ( <Suspense fallback={<Text text="Loading..." />}> {showMore ? <AsyncText text="Async" /> : <Text text="(empty)" />} </Suspense> ); } await withActEnvironment(true, () => { const root = ReactNoop.createRoot(); act(() => { root.render(<App showMore={false} />); }); assertLog(['(empty)']); expect(root).toMatchRenderedOutput('(empty)'); act(() => { startTransition(() => { root.render(<App showMore={true} />); }); }); assertLog(['Suspend! [Async]', 'Loading...']); expect(root).toMatchRenderedOutput('(empty)'); // This is a ping, not a retry, because no fallback is showing. expect(() => resolveText('Async')).toErrorDev( 'A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...)', {withoutStack: true}, ); }); }); });
26.711538
89
0.566825
owtf
var React = require('react'); var ReactDOM = require('react-dom'); ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') );
21.375
50
0.702247
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; // This is a new feature in Fiber so I put it in its own test file. It could // probably move to one of the other test files once it is official. describe('ReactTopLevelFragment', function () { beforeEach(function () { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; }); it('should render a simple fragment at the top of a component', async function () { function Fragment() { return [<div key="a">Hello</div>, <div key="b">World</div>]; } ReactNoop.render(<Fragment />); await waitForAll([]); }); it('should preserve state when switching from a single child', async function () { let instance = null; class Stateful extends React.Component { render() { instance = this; return <div>Hello</div>; } } function Fragment({condition}) { return condition ? ( <Stateful key="a" /> ) : ( [<Stateful key="a" />, <div key="b">World</div>] ); } ReactNoop.render(<Fragment />); await waitForAll([]); const instanceA = instance; expect(instanceA).not.toBe(null); ReactNoop.render(<Fragment condition={true} />); await waitForAll([]); const instanceB = instance; expect(instanceB).toBe(instanceA); }); it('should not preserve state when switching to a nested array', async function () { let instance = null; class Stateful extends React.Component { render() { instance = this; return <div>Hello</div>; } } function Fragment({condition}) { return condition ? ( <Stateful key="a" /> ) : ( [[<Stateful key="a" />, <div key="b">World</div>], <div key="c" />] ); } ReactNoop.render(<Fragment />); await waitForAll([]); const instanceA = instance; expect(instanceA).not.toBe(null); ReactNoop.render(<Fragment condition={true} />); await waitForAll([]); const instanceB = instance; expect(instanceB).not.toBe(instanceA); }); it('preserves state if an implicit key slot switches from/to null', async function () { let instance = null; class Stateful extends React.Component { render() { instance = this; return <div>World</div>; } } function Fragment({condition}) { return condition ? [null, <Stateful key="a" />] : [<div key="b">Hello</div>, <Stateful key="a" />]; } ReactNoop.render(<Fragment />); await waitForAll([]); const instanceA = instance; expect(instanceA).not.toBe(null); ReactNoop.render(<Fragment condition={true} />); await waitForAll([]); const instanceB = instance; expect(instanceB).toBe(instanceA); ReactNoop.render(<Fragment condition={false} />); await waitForAll([]); const instanceC = instance; expect(instanceC === instanceA).toBe(true); }); it('should preserve state in a reorder', async function () { let instance = null; class Stateful extends React.Component { render() { instance = this; return <div>Hello</div>; } } function Fragment({condition}) { return condition ? [[<div key="b">World</div>, <Stateful key="a" />]] : [[<Stateful key="a" />, <div key="b">World</div>], <div key="c" />]; } ReactNoop.render(<Fragment />); await waitForAll([]); const instanceA = instance; expect(instanceA).not.toBe(null); ReactNoop.render(<Fragment condition={true} />); await waitForAll([]); const instanceB = instance; expect(instanceB).toBe(instanceA); }); });
23.142857
89
0.605179
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 Agent from './agent'; import {attach} from './renderer'; import {attach as attachLegacy} from './legacy/renderer'; import {hasAssignedBackend} from './utils'; import type {DevToolsHook, ReactRenderer, RendererInterface} from './types'; // this is the backend that is compatible with all older React versions function isMatchingRender(version: string): boolean { return !hasAssignedBackend(version); } export type InitBackend = typeof initBackend; export function initBackend( hook: DevToolsHook, agent: Agent, global: Object, ): () => void { if (hook == null) { // DevTools didn't get injected into this page (maybe b'c of the contentType). return () => {}; } const subs = [ hook.sub( 'renderer-attached', ({ id, renderer, rendererInterface, }: { id: number, renderer: ReactRenderer, rendererInterface: RendererInterface, ... }) => { agent.setRendererInterface(id, rendererInterface); // Now that the Store and the renderer interface are connected, // it's time to flush the pending operation codes to the frontend. rendererInterface.flushInitialOperations(); }, ), hook.sub('unsupported-renderer-version', (id: number) => { agent.onUnsupportedRenderer(id); }), hook.sub('fastRefreshScheduled', agent.onFastRefreshScheduled), hook.sub('operations', agent.onHookOperations), hook.sub('traceUpdates', agent.onTraceUpdates), // TODO Add additional subscriptions required for profiling mode ]; const attachRenderer = (id: number, renderer: ReactRenderer) => { // only attach if the renderer is compatible with the current version of the backend if (!isMatchingRender(renderer.reconcilerVersion || renderer.version)) { return; } let rendererInterface = hook.rendererInterfaces.get(id); // Inject any not-yet-injected renderers (if we didn't reload-and-profile) if (rendererInterface == null) { if (typeof renderer.findFiberByHostInstance === 'function') { // react-reconciler v16+ rendererInterface = attach(hook, id, renderer, global); } else if (renderer.ComponentTree) { // react-dom v15 rendererInterface = attachLegacy(hook, id, renderer, global); } else { // Older react-dom or other unsupported renderer version } if (rendererInterface != null) { hook.rendererInterfaces.set(id, rendererInterface); } } // Notify the DevTools frontend about new renderers. // This includes any that were attached early (via __REACT_DEVTOOLS_ATTACH__). if (rendererInterface != null) { hook.emit('renderer-attached', { id, renderer, rendererInterface, }); } else { hook.emit('unsupported-renderer-version', id); } }; // Connect renderers that have already injected themselves. hook.renderers.forEach((renderer, id) => { attachRenderer(id, renderer); }); // Connect any new renderers that injected themselves. subs.push( hook.sub( 'renderer', ({id, renderer}: {id: number, renderer: ReactRenderer, ...}) => { attachRenderer(id, renderer); }, ), ); hook.emit('react-devtools', agent); hook.reactDevtoolsAgent = agent; const onAgentShutdown = () => { subs.forEach(fn => fn()); hook.rendererInterfaces.forEach(rendererInterface => { rendererInterface.cleanup(); }); hook.reactDevtoolsAgent = null; }; agent.addListener('shutdown', onAgentShutdown); subs.push(() => { agent.removeListener('shutdown', onAgentShutdown); }); return () => { subs.forEach(fn => fn()); }; }
27.759124
88
0.648134
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFlightDOMClientNode';
22
66
0.702381
owtf
let nextFiberID = 1; const fiberIDMap = new WeakMap(); function getFiberUniqueID(fiber) { if (!fiberIDMap.has(fiber)) { fiberIDMap.set(fiber, nextFiberID++); } return fiberIDMap.get(fiber); } function getFriendlyTag(tag) { switch (tag) { case 0: return '[indeterminate]'; case 1: return '[fn]'; case 2: return '[class]'; case 3: return '[root]'; case 4: return '[portal]'; case 5: return '[host]'; case 6: return '[text]'; case 7: return '[coroutine]'; case 8: return '[handler]'; case 9: return '[yield]'; case 10: return '[frag]'; default: throw new Error('Unknown tag.'); } } function getFriendlyEffect(flags) { const effects = { 1: 'Performed Work', 2: 'Placement', 4: 'Update', 8: 'Deletion', 16: 'Content reset', 32: 'Callback', 64: 'Err', 128: 'Ref', }; return Object.keys(effects) .filter(flag => flag & flags) .map(flag => effects[flag]) .join(' & '); } export default function describeFibers(rootFiber, workInProgress) { let descriptions = {}; function acknowledgeFiber(fiber) { if (!fiber) { return null; } if (!fiber.return && fiber.tag !== 3) { return null; } const id = getFiberUniqueID(fiber); if (descriptions[id]) { return id; } descriptions[id] = {}; Object.assign(descriptions[id], { ...fiber, id: id, tag: getFriendlyTag(fiber.tag), flags: getFriendlyEffect(fiber.flags), type: fiber.type && '<' + (fiber.type.name || fiber.type) + '>', stateNode: `[${typeof fiber.stateNode}]`, return: acknowledgeFiber(fiber.return), child: acknowledgeFiber(fiber.child), sibling: acknowledgeFiber(fiber.sibling), nextEffect: acknowledgeFiber(fiber.nextEffect), firstEffect: acknowledgeFiber(fiber.firstEffect), lastEffect: acknowledgeFiber(fiber.lastEffect), alternate: acknowledgeFiber(fiber.alternate), }); return id; } const rootID = acknowledgeFiber(rootFiber); const workInProgressID = acknowledgeFiber(workInProgress); let currentIDs = new Set(); function markAsCurrent(id) { currentIDs.add(id); const fiber = descriptions[id]; if (fiber.sibling) { markAsCurrent(fiber.sibling); } if (fiber.child) { markAsCurrent(fiber.child); } } markAsCurrent(rootID); return { descriptions, rootID, currentIDs: Array.from(currentIDs), workInProgressID, }; }
21.883929
70
0.603435
Broken-Droid-Factory
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; // Don't wait before processing work on the server. // TODO: we can replace this with FlightServer.act(). global.setImmediate = cb => cb(); let clientExports; let turbopackMap; let turbopackModules; let turbopackModuleLoading; let React; let ReactDOMServer; let ReactServerDOMServer; let ReactServerDOMClient; let Stream; let use; describe('ReactFlightDOMNode', () => { beforeEach(() => { jest.resetModules(); // Simulate the condition resolution jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-server-dom-turbopack/server', () => require('react-server-dom-turbopack/server.node'), ); ReactServerDOMServer = require('react-server-dom-turbopack/server'); const TurbopackMock = require('./utils/TurbopackMock'); clientExports = TurbopackMock.clientExports; turbopackMap = TurbopackMock.turbopackMap; turbopackModules = TurbopackMock.turbopackModules; turbopackModuleLoading = TurbopackMock.moduleLoading; jest.resetModules(); __unmockReact(); jest.unmock('react-server-dom-turbopack/server'); jest.mock('react-server-dom-turbopack/client', () => require('react-server-dom-turbopack/client.node'), ); React = require('react'); ReactDOMServer = require('react-dom/server.node'); ReactServerDOMClient = require('react-server-dom-turbopack/client'); Stream = require('stream'); use = React.use; }); function readResult(stream) { return new Promise((resolve, reject) => { let buffer = ''; const writable = new Stream.PassThrough(); writable.setEncoding('utf8'); writable.on('data', chunk => { buffer += chunk; }); writable.on('error', error => { reject(error); }); writable.on('end', () => { resolve(buffer); }); stream.pipe(writable); }); } it('should allow an alternative module mapping to be used for SSR', async () => { function ClientComponent() { return <span>Client Component</span>; } // The Client build may not have the same IDs as the Server bundles for the same // component. const ClientComponentOnTheClient = clientExports( ClientComponent, 'path/to/chunk.js', ); const ClientComponentOnTheServer = clientExports(ClientComponent); // In the SSR bundle this module won't exist. We simulate this by deleting it. const clientId = turbopackMap[ClientComponentOnTheClient.$$id].id; delete turbopackModules[clientId]; // Instead, we have to provide a translation from the client meta data to the SSR // meta data. const ssrMetadata = turbopackMap[ClientComponentOnTheServer.$$id]; const translationMap = { [clientId]: { '*': ssrMetadata, }, }; function App() { return <ClientComponentOnTheClient />; } const stream = ReactServerDOMServer.renderToPipeableStream( <App />, turbopackMap, ); const readable = new Stream.PassThrough(); stream.pipe(readable); let response; function ClientRoot() { if (!response) { response = ReactServerDOMClient.createFromNodeStream(readable, { moduleMap: translationMap, moduleLoading: turbopackModuleLoading, }); } return use(response); } const ssrStream = await ReactDOMServer.renderToPipeableStream( <ClientRoot />, ); const result = await readResult(ssrStream); expect(result).toEqual( '<script src="/prefix/path/to/chunk.js" async=""></script><span>Client Component</span>', ); }); });
27.879699
95
0.659375
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 5 } }, /*#__PURE__*/_react.default.createElement("p", { __source: { fileName: _jsxFileName, lineNumber: 17, columnNumber: 7 } }, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", { onClick: () => setCount(count + 1), __source: { fileName: _jsxFileName, lineNumber: 18, columnNumber: 7 } }, "Click me")); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkV4YW1wbGUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJzZXRDb3VudCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50LCBzZXRDb3VudF0gPSB1c2VTdGF0ZSgwKTtcblxuICByZXR1cm4gKFxuICAgIDxkaXY+XG4gICAgICA8cD5Zb3UgY2xpY2tlZCB7Y291bnR9IHRpbWVzPC9wPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXsoKSA9PiBzZXRDb3VudChjb3VudCArIDEpfT5DbGljayBtZTwvYnV0dG9uPlxuICAgIDwvZGl2PlxuICApO1xufVxuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiIsImNvdW50Il0sIm1hcHBpbmdzIjoiQ0FBRDthNEJDQSxBV0RBIn1dXV19fV19
81.846154
1,472
0.801858
owtf
import FixtureSet from '../../FixtureSet'; const React = window.React; class RangeInputs extends React.Component { state = {value: 0.5}; onChange = event => { this.setState({value: event.target.value}); }; render() { return ( <FixtureSet title="Range Inputs" description="Note: Range inputs are not supported in IE9."> <form> <fieldset> <legend>Controlled</legend> <input type="range" value={this.state.value} onChange={this.onChange} /> <span className="hint">Value: {this.state.value}</span> </fieldset> <fieldset> <legend>Uncontrolled</legend> <input type="range" defaultValue={0.5} /> </fieldset> </form> </FixtureSet> ); } } export default RangeInputs;
22.864865
67
0.534014
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 * as React from 'react'; import {useContext, useEffect, useLayoutEffect, useRef, useState} from 'react'; import {createPortal} from 'react-dom'; import {RegistryContext} from './Contexts'; import styles from './ContextMenu.css'; import type {RegistryContextType} from './Contexts'; function repositionToFit(element: HTMLElement, pageX: number, pageY: number) { const ownerWindow = element.ownerDocument.defaultView; if (element !== null) { if (pageY + element.offsetHeight >= ownerWindow.innerHeight) { if (pageY - element.offsetHeight > 0) { element.style.top = `${pageY - element.offsetHeight}px`; } else { element.style.top = '0px'; } } else { element.style.top = `${pageY}px`; } if (pageX + element.offsetWidth >= ownerWindow.innerWidth) { if (pageX - element.offsetWidth > 0) { element.style.left = `${pageX - element.offsetWidth}px`; } else { element.style.left = '0px'; } } else { element.style.left = `${pageX}px`; } } } const HIDDEN_STATE = { data: null, isVisible: false, pageX: 0, pageY: 0, }; type Props = { children: (data: Object) => React$Node, id: string, }; export default function ContextMenu({children, id}: Props): React.Node { const {hideMenu, registerMenu} = useContext<RegistryContextType>(RegistryContext); const [state, setState] = useState(HIDDEN_STATE); const bodyAccessorRef = useRef(null); const containerRef = useRef(null); const menuRef = useRef(null); useEffect(() => { const element = bodyAccessorRef.current; if (element !== null) { const ownerDocument = element.ownerDocument; containerRef.current = ownerDocument.querySelector( '[data-react-devtools-portal-root]', ); if (containerRef.current == null) { console.warn( 'DevTools tooltip root node not found; context menus will be disabled.', ); } } }, []); useEffect(() => { const showMenuFn = ({ data, pageX, pageY, }: { data: any, pageX: number, pageY: number, }) => { setState({data, isVisible: true, pageX, pageY}); }; const hideMenuFn = () => setState(HIDDEN_STATE); return registerMenu(id, showMenuFn, hideMenuFn); }, [id]); useLayoutEffect(() => { if (!state.isVisible) { return; } const menu = ((menuRef.current: any): HTMLElement); const container = containerRef.current; if (container !== null) { // $FlowFixMe[missing-local-annot] const hideUnlessContains = event => { if (!menu.contains(event.target)) { hideMenu(); } }; const ownerDocument = container.ownerDocument; ownerDocument.addEventListener('mousedown', hideUnlessContains); ownerDocument.addEventListener('touchstart', hideUnlessContains); ownerDocument.addEventListener('keydown', hideUnlessContains); const ownerWindow = ownerDocument.defaultView; ownerWindow.addEventListener('resize', hideMenu); repositionToFit(menu, state.pageX, state.pageY); return () => { ownerDocument.removeEventListener('mousedown', hideUnlessContains); ownerDocument.removeEventListener('touchstart', hideUnlessContains); ownerDocument.removeEventListener('keydown', hideUnlessContains); ownerWindow.removeEventListener('resize', hideMenu); }; } }, [state]); if (!state.isVisible) { return <div ref={bodyAccessorRef} />; } else { const container = containerRef.current; if (container !== null) { return createPortal( <div ref={menuRef} className={styles.ContextMenu}> {children(state.data)} </div>, container, ); } else { return null; } } }
26.087248
82
0.630235
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 { getDisplayName, getDisplayNameForReactElement, isPlainObject, } from 'react-devtools-shared/src/utils'; import {stackToComponentSources} from 'react-devtools-shared/src/devtools/utils'; import { format, formatWithStyles, gt, gte, } from 'react-devtools-shared/src/backend/utils'; import { REACT_SUSPENSE_LIST_TYPE as SuspenseList, REACT_STRICT_MODE_TYPE as StrictMode, } from 'shared/ReactSymbols'; import {createElement} from 'react/src/ReactElement'; describe('utils', () => { describe('getDisplayName', () => { // @reactVersion >= 16.0 it('should return a function name', () => { function FauxComponent() {} expect(getDisplayName(FauxComponent)).toEqual('FauxComponent'); }); // @reactVersion >= 16.0 it('should return a displayName name if specified', () => { function FauxComponent() {} FauxComponent.displayName = 'OverrideDisplayName'; expect(getDisplayName(FauxComponent)).toEqual('OverrideDisplayName'); }); // @reactVersion >= 16.0 it('should return the fallback for anonymous functions', () => { expect(getDisplayName(() => {}, 'Fallback')).toEqual('Fallback'); }); // @reactVersion >= 16.0 it('should return Anonymous for anonymous functions without a fallback', () => { expect(getDisplayName(() => {})).toEqual('Anonymous'); }); // Simulate a reported bug: // https://github.com/facebook/react/issues/16685 // @reactVersion >= 16.0 it('should return a fallback when the name prop is not a string', () => { const FauxComponent = {name: {}}; expect(getDisplayName(FauxComponent, 'Fallback')).toEqual('Fallback'); }); it('should parse a component stack trace', () => { expect( stackToComponentSources(` at Foobar (http://localhost:3000/static/js/bundle.js:103:74) at a at header at div at App`), ).toEqual([ ['Foobar', ['http://localhost:3000/static/js/bundle.js', 103, 74]], ['a', null], ['header', null], ['div', null], ['App', null], ]); }); }); describe('getDisplayNameForReactElement', () => { // @reactVersion >= 16.0 it('should return correct display name for an element with function type', () => { function FauxComponent() {} FauxComponent.displayName = 'OverrideDisplayName'; const element = createElement(FauxComponent); expect(getDisplayNameForReactElement(element)).toEqual( 'OverrideDisplayName', ); }); // @reactVersion >= 16.0 it('should return correct display name for an element with a type of StrictMode', () => { const element = createElement(StrictMode); expect(getDisplayNameForReactElement(element)).toEqual('StrictMode'); }); // @reactVersion >= 16.0 it('should return correct display name for an element with a type of SuspenseList', () => { const element = createElement(SuspenseList); expect(getDisplayNameForReactElement(element)).toEqual('SuspenseList'); }); // @reactVersion >= 16.0 it('should return NotImplementedInDevtools for an element with invalid symbol type', () => { const element = createElement(Symbol('foo')); expect(getDisplayNameForReactElement(element)).toEqual( 'NotImplementedInDevtools', ); }); // @reactVersion >= 16.0 it('should return NotImplementedInDevtools for an element with invalid type', () => { const element = createElement(true); expect(getDisplayNameForReactElement(element)).toEqual( 'NotImplementedInDevtools', ); }); // @reactVersion >= 16.0 it('should return Element for null type', () => { const element = createElement(); expect(getDisplayNameForReactElement(element)).toEqual('Element'); }); }); describe('format', () => { // @reactVersion >= 16.0 it('should format simple strings', () => { expect(format('a', 'b', 'c')).toEqual('a b c'); }); // @reactVersion >= 16.0 it('should format multiple argument types', () => { expect(format('abc', 123, true)).toEqual('abc 123 true'); }); // @reactVersion >= 16.0 it('should support string substitutions', () => { expect(format('a %s b %s c', 123, true)).toEqual('a 123 b true c'); }); // @reactVersion >= 16.0 it('should gracefully handle Symbol types', () => { expect(format(Symbol('a'), 'b', Symbol('c'))).toEqual( 'Symbol(a) b Symbol(c)', ); }); // @reactVersion >= 16.0 it('should gracefully handle Symbol type for the first argument', () => { expect(format(Symbol('abc'), 123)).toEqual('Symbol(abc) 123'); }); }); describe('formatWithStyles', () => { // @reactVersion >= 16.0 it('should format empty arrays', () => { expect(formatWithStyles([])).toEqual([]); expect(formatWithStyles([], 'gray')).toEqual([]); expect(formatWithStyles(undefined)).toEqual(undefined); }); // @reactVersion >= 16.0 it('should bail out of strings with styles', () => { expect( formatWithStyles(['%ca', 'color: green', 'b', 'c'], 'color: gray'), ).toEqual(['%ca', 'color: green', 'b', 'c']); }); // @reactVersion >= 16.0 it('should format simple strings', () => { expect(formatWithStyles(['a'])).toEqual(['a']); expect(formatWithStyles(['a', 'b', 'c'])).toEqual(['a', 'b', 'c']); expect(formatWithStyles(['a'], 'color: gray')).toEqual([ '%c%s', 'color: gray', 'a', ]); expect(formatWithStyles(['a', 'b', 'c'], 'color: gray')).toEqual([ '%c%s %s %s', 'color: gray', 'a', 'b', 'c', ]); }); // @reactVersion >= 16.0 it('should format string substituions', () => { expect( formatWithStyles(['%s %s %s', 'a', 'b', 'c'], 'color: gray'), ).toEqual(['%c%s %s %s', 'color: gray', 'a', 'b', 'c']); // The last letter isn't gray here but I think it's not a big // deal, since there is a string substituion but it's incorrect expect(formatWithStyles(['%s %s', 'a', 'b', 'c'], 'color: gray')).toEqual( ['%c%s %s', 'color: gray', 'a', 'b', 'c'], ); }); // @reactVersion >= 16.0 it('should support multiple argument types', () => { const symbol = Symbol('a'); expect( formatWithStyles( ['abc', 123, 12.3, true, {hello: 'world'}, symbol], 'color: gray', ), ).toEqual([ '%c%s %i %f %s %o %s', 'color: gray', 'abc', 123, 12.3, true, {hello: 'world'}, symbol, ]); }); // @reactVersion >= 16.0 it('should properly format escaped string substituions', () => { expect(formatWithStyles(['%%s'], 'color: gray')).toEqual([ '%c%s', 'color: gray', '%%s', ]); expect(formatWithStyles(['%%c'], 'color: gray')).toEqual([ '%c%s', 'color: gray', '%%c', ]); expect(formatWithStyles(['%%c%c'], 'color: gray')).toEqual(['%%c%c']); }); // @reactVersion >= 16.0 it('should format non string inputs as the first argument', () => { expect(formatWithStyles([{foo: 'bar'}])).toEqual([{foo: 'bar'}]); expect(formatWithStyles([[1, 2, 3]])).toEqual([[1, 2, 3]]); expect(formatWithStyles([{foo: 'bar'}], 'color: gray')).toEqual([ '%c%o', 'color: gray', {foo: 'bar'}, ]); expect(formatWithStyles([[1, 2, 3]], 'color: gray')).toEqual([ '%c%o', 'color: gray', [1, 2, 3], ]); expect(formatWithStyles([{foo: 'bar'}, 'hi'], 'color: gray')).toEqual([ '%c%o %s', 'color: gray', {foo: 'bar'}, 'hi', ]); }); }); describe('semver comparisons', () => { it('gte should compare versions correctly', () => { expect(gte('1.2.3', '1.2.1')).toBe(true); expect(gte('1.2.1', '1.2.1')).toBe(true); expect(gte('1.2.1', '1.2.2')).toBe(false); expect(gte('10.0.0', '9.0.0')).toBe(true); }); it('gt should compare versions correctly', () => { expect(gt('1.2.3', '1.2.1')).toBe(true); expect(gt('1.2.1', '1.2.1')).toBe(false); expect(gt('1.2.1', '1.2.2')).toBe(false); expect(gte('10.0.0', '9.0.0')).toBe(true); }); }); describe('isPlainObject', () => { it('should return true for plain objects', () => { expect(isPlainObject({})).toBe(true); expect(isPlainObject({a: 1})).toBe(true); expect(isPlainObject({a: {b: {c: 123}}})).toBe(true); }); it('should return false if object is a class instance', () => { expect(isPlainObject(new (class C {})())).toBe(false); }); it('should return false for objects, which have not only Object in its prototype chain', () => { expect(isPlainObject([])).toBe(false); expect(isPlainObject(Symbol())).toBe(false); }); it('should return false for primitives', () => { expect(isPlainObject(5)).toBe(false); expect(isPlainObject(true)).toBe(false); }); it('should return true for objects with no prototype', () => { expect(isPlainObject(Object.create(null))).toBe(true); }); }); });
30.614618
100
0.562901
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'; class EquivalenceReporter { onTestCaseResult(test, testCaseResult) { console.log( `EQUIVALENCE: ${testCaseResult.title}, ` + `status: ${testCaseResult.status}, ` + `numExpectations: ${testCaseResult.numPassingAsserts}` ); } } module.exports = EquivalenceReporter;
23.142857
66
0.685771
owtf
'use client'; import * as React from 'react'; import Container from './Container.js'; export default function ShowMore({children}) { const [show, setShow] = React.useState(false); if (!show) { return <button onClick={() => setShow(true)}>Show More</button>; } return <Container>{children}</Container>; }
21.857143
68
0.670846
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Scheduler; let act; let Suspense; let getCacheForType; let startTransition; let assertLog; let caches; let seededCache; describe('ReactConcurrentErrorRecovery', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; Suspense = React.Suspense; startTransition = React.startTransition; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; getCacheForType = React.unstable_getCacheForType; caches = []; seededCache = null; }); function createTextCache() { if (seededCache !== null) { // Trick to seed a cache before it exists. // TODO: Need a built-in API to seed data before the initial render (i.e. // not a refresh because nothing has mounted yet). const cache = seededCache; seededCache = null; return cache; } const data = new Map(); const version = caches.length + 1; const cache = { version, data, resolve(text) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } }, reject(text, error) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'rejected', value: error, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'rejected'; record.value = error; thenable.pings.forEach(t => t()); } }, }; caches.push(cache); return cache; } function readText(text) { const textCache = getCacheForType(createTextCache); const record = textCache.data.get(text); if (record !== undefined) { switch (record.status) { case 'pending': Scheduler.log(`Suspend! [${text}]`); throw record.value; case 'rejected': Scheduler.log(`Error! [${text}]`); throw record.value; case 'resolved': return textCache.version; } } else { Scheduler.log(`Suspend! [${text}]`); const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.data.set(text, newRecord); throw thenable; } } function Text({text}) { Scheduler.log(text); return text; } function AsyncText({text, showVersion}) { const version = readText(text); const fullText = showVersion ? `${text} [v${version}]` : text; Scheduler.log(fullText); return fullText; } function seedNextTextCache(text) { if (seededCache === null) { seededCache = createTextCache(); } seededCache.resolve(text); } function resolveMostRecentTextCache(text) { if (caches.length === 0) { throw Error('Cache does not exist.'); } else { // Resolve the most recently created cache. An older cache can by // resolved with `caches[index].resolve(text)`. caches[caches.length - 1].resolve(text); } } const resolveText = resolveMostRecentTextCache; function rejectMostRecentTextCache(text, error) { if (caches.length === 0) { throw Error('Cache does not exist.'); } else { // Resolve the most recently created cache. An older cache can by // resolved with `caches[index].reject(text, error)`. caches[caches.length - 1].reject(text, error); } } const rejectText = rejectMostRecentTextCache; // @gate enableLegacyCache test('errors during a refresh transition should not force fallbacks to display (suspend then error)', async () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error !== null) { return <Text text={this.state.error.message} />; } return this.props.children; } } function App({step}) { return ( <> <Suspense fallback={<Text text="Loading..." />}> <ErrorBoundary> <AsyncText text={'A' + step} /> </ErrorBoundary> </Suspense> <Suspense fallback={<Text text="Loading..." />}> <ErrorBoundary> <AsyncText text={'B' + step} /> </ErrorBoundary> </Suspense> </> ); } // Initial render const root = ReactNoop.createRoot(); seedNextTextCache('A1'); seedNextTextCache('B1'); await act(() => { root.render(<App step={1} />); }); assertLog(['A1', 'B1']); expect(root).toMatchRenderedOutput('A1B1'); // Start a refresh transition await act(() => { startTransition(() => { root.render(<App step={2} />); }); }); assertLog(['Suspend! [A2]', 'Loading...', 'Suspend! [B2]', 'Loading...']); // Because this is a refresh, we don't switch to a fallback expect(root).toMatchRenderedOutput('A1B1'); // B fails to load. await act(() => { rejectText('B2', new Error('Oops!')); }); // Because we're still suspended on A, we can't show an error boundary. We // should wait for A to resolve. if (gate(flags => flags.replayFailedUnitOfWorkWithInvokeGuardedCallback)) { assertLog([ 'Suspend! [A2]', 'Loading...', 'Error! [B2]', // This extra log happens when we replay the error // in invokeGuardedCallback 'Error! [B2]', 'Oops!', ]); } else { assertLog(['Suspend! [A2]', 'Loading...', 'Error! [B2]', 'Oops!']); } // Remain on previous screen. expect(root).toMatchRenderedOutput('A1B1'); // A finishes loading. await act(() => { resolveText('A2'); }); if (gate(flags => flags.replayFailedUnitOfWorkWithInvokeGuardedCallback)) { assertLog([ 'A2', 'Error! [B2]', // This extra log happens when we replay the error // in invokeGuardedCallback 'Error! [B2]', 'Oops!', 'A2', 'Error! [B2]', // This extra log happens when we replay the error // in invokeGuardedCallback 'Error! [B2]', 'Oops!', ]); } else { assertLog(['A2', 'Error! [B2]', 'Oops!', 'A2', 'Error! [B2]', 'Oops!']); } // Now we can show the error boundary that's wrapped around B. expect(root).toMatchRenderedOutput('A2Oops!'); }); // @gate enableLegacyCache test('errors during a refresh transition should not force fallbacks to display (error then suspend)', async () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error !== null) { return <Text text={this.state.error.message} />; } return this.props.children; } } function App({step}) { return ( <> <Suspense fallback={<Text text="Loading..." />}> <ErrorBoundary> <AsyncText text={'A' + step} /> </ErrorBoundary> </Suspense> <Suspense fallback={<Text text="Loading..." />}> <ErrorBoundary> <AsyncText text={'B' + step} /> </ErrorBoundary> </Suspense> </> ); } // Initial render const root = ReactNoop.createRoot(); seedNextTextCache('A1'); seedNextTextCache('B1'); await act(() => { root.render(<App step={1} />); }); assertLog(['A1', 'B1']); expect(root).toMatchRenderedOutput('A1B1'); // Start a refresh transition await act(() => { startTransition(() => { root.render(<App step={2} />); }); }); assertLog(['Suspend! [A2]', 'Loading...', 'Suspend! [B2]', 'Loading...']); // Because this is a refresh, we don't switch to a fallback expect(root).toMatchRenderedOutput('A1B1'); // A fails to load. await act(() => { rejectText('A2', new Error('Oops!')); }); // Because we're still suspended on B, we can't show an error boundary. We // should wait for B to resolve. if (gate(flags => flags.replayFailedUnitOfWorkWithInvokeGuardedCallback)) { assertLog([ 'Error! [A2]', // This extra log happens when we replay the error // in invokeGuardedCallback 'Error! [A2]', 'Oops!', 'Suspend! [B2]', 'Loading...', ]); } else { assertLog(['Error! [A2]', 'Oops!', 'Suspend! [B2]', 'Loading...']); } // Remain on previous screen. expect(root).toMatchRenderedOutput('A1B1'); // B finishes loading. await act(() => { resolveText('B2'); }); if (gate(flags => flags.replayFailedUnitOfWorkWithInvokeGuardedCallback)) { assertLog([ 'Error! [A2]', // This extra log happens when we replay the error // in invokeGuardedCallback 'Error! [A2]', 'Oops!', 'B2', 'Error! [A2]', // This extra log happens when we replay the error // in invokeGuardedCallback 'Error! [A2]', 'Oops!', 'B2', ]); } else { assertLog(['Error! [A2]', 'Oops!', 'B2', 'Error! [A2]', 'Oops!', 'B2']); } // Now we can show the error boundary that's wrapped around B. expect(root).toMatchRenderedOutput('Oops!B2'); }); // @gate enableLegacyCache test('suspending in the shell (outside a Suspense boundary) should not throw, warn, or log during a transition', async () => { class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error !== null) { return <Text text={this.state.error.message} />; } return this.props.children; } } // The initial render suspends without a Suspense boundary. Since it's // wrapped in startTransition, it suspends instead of erroring. const root = ReactNoop.createRoot(); await act(() => { startTransition(() => { root.render(<AsyncText text="Async" />); }); }); assertLog(['Suspend! [Async]']); expect(root).toMatchRenderedOutput(null); // This also works if the suspended component is wrapped with an error // boundary. (This is only interesting because when a component suspends // outside of a transition, we throw an error, which can be captured by // an error boundary. await act(() => { startTransition(() => { root.render( <ErrorBoundary> <AsyncText text="Async" /> </ErrorBoundary>, ); }); }); assertLog(['Suspend! [Async]']); expect(root).toMatchRenderedOutput(null); // Continues rendering once data resolves await act(() => { resolveText('Async'); }); assertLog(['Async']); expect(root).toMatchRenderedOutput('Async'); }); // @gate enableLegacyCache test( 'errors during a suspended transition at the shell should not force ' + 'fallbacks to display (error then suspend)', async () => { // This is similar to the earlier test for errors that occur during // a refresh transition. Suspending in the shell is conceptually the same // as a refresh, but they have slightly different implementation paths. class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error !== null) { return ( <Text text={'Caught an error: ' + this.state.error.message} /> ); } return this.props.children; } } function Throws() { throw new Error('Oops!'); } // Suspend and throw in the same transition const root = ReactNoop.createRoot(); await act(() => { startTransition(() => { root.render( <> <AsyncText text="Async" /> <ErrorBoundary> <Throws /> </ErrorBoundary> </>, ); }); }); assertLog(['Suspend! [Async]']); // The render suspended without committing or surfacing the error. expect(root).toMatchRenderedOutput(null); // Try the reverse order, too: throw then suspend await act(() => { startTransition(() => { root.render( <> <AsyncText text="Async" /> <ErrorBoundary> <Throws /> </ErrorBoundary> </>, ); }); }); assertLog(['Suspend! [Async]']); expect(root).toMatchRenderedOutput(null); await act(async () => { await resolveText('Async'); }); assertLog([ 'Async', 'Caught an error: Oops!', // Try recovering from the error by rendering again synchronously 'Async', 'Caught an error: Oops!', ]); expect(root).toMatchRenderedOutput('AsyncCaught an error: Oops!'); }, ); });
27.200401
128
0.551915
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('StoreStressConcurrent', () => { let React; let ReactDOMClient; let act; let actAsync; let bridge; let store; let print; beforeEach(() => { bridge = global.bridge; store = global.store; store.collapseNodesByDefault = false; React = require('react'); ReactDOMClient = require('react-dom/client'); act = require('./utils').act; // TODO: Figure out recommendation for concurrent mode tests, then replace // this helper with the real thing. actAsync = require('./utils').actAsync; print = require('./__serializers__/storeSerializer').print; }); // TODO: Remove this in favor of @gate pragma if (!__EXPERIMENTAL__) { it("empty test so Jest doesn't complain", () => {}); return; } // This is a stress test for the tree mount/update/unmount traversal. // It renders different trees that should produce the same output. // @reactVersion >= 18.0 it('should handle a stress test with different tree operations (Concurrent Mode)', () => { let setShowX; const A = () => 'a'; const B = () => 'b'; const C = () => { // We'll be manually flipping this component back and forth in the test. // We only do this for a single node in order to verify that DevTools // can handle a subtree switching alternates while other subtrees are memoized. const [showX, _setShowX] = React.useState(false); setShowX = _setShowX; return showX ? <X /> : 'c'; }; const D = () => 'd'; const E = () => 'e'; const X = () => 'x'; const a = <A key="a" />; const b = <B key="b" />; const c = <C key="c" />; const d = <D key="d" />; const e = <E key="e" />; function Parent({children}) { return children; } // 1. Render a normal version of [a, b, c, d, e]. let container = document.createElement('div'); let root = ReactDOMClient.createRoot(container); act(() => root.render(<Parent>{[a, b, c, d, e]}</Parent>)); expect(store).toMatchInlineSnapshot( ` [root] ▾ <Parent> <A key="a"> <B key="b"> <C key="c"> <D key="d"> <E key="e"> `, ); expect(container.textContent).toMatch('abcde'); const snapshotForABCDE = print(store); // 2. Render a version where <C /> renders an <X /> child instead of 'c'. // This is how we'll test an update to a single component. act(() => { setShowX(true); }); expect(store).toMatchInlineSnapshot( ` [root] ▾ <Parent> <A key="a"> <B key="b"> ▾ <C key="c"> <X> <D key="d"> <E key="e"> `, ); expect(container.textContent).toMatch('abxde'); const snapshotForABXDE = print(store); // 3. Verify flipping it back produces the original result. act(() => { setShowX(false); }); expect(container.textContent).toMatch('abcde'); expect(print(store)).toBe(snapshotForABCDE); // 4. Clean up. act(() => root.unmount()); expect(print(store)).toBe(''); // Now comes the interesting part. // All of these cases are equivalent to [a, b, c, d, e] in output. // We'll verify that DevTools produces the same snapshots for them. // These cases are picked so that rendering them sequentially in the same // container results in a combination of mounts, updates, unmounts, and reorders. // prettier-ignore const cases = [ [a, b, c, d, e], [[a], b, c, d, e], [[a, b], c, d, e], [[a, b], c, [d, e]], [[a, b], c, [d, '', e]], [[a], b, c, d, [e]], [a, b, [[c]], d, e], [[a, ''], [b], [c], [d], [e]], [a, b, [c, [d, ['', e]]]], [a, b, c, d, e], [<div key="0">{a}</div>, b, c, d, e], [<div key="0">{a}{b}</div>, c, d, e], [<div key="0">{a}{b}</div>, c, <div key="1">{d}{e}</div>], [<div key="1">{a}{b}</div>, c, <div key="0">{d}{e}</div>], [<div key="0">{a}{b}</div>, c, <div key="1">{d}{e}</div>], [<div key="2">{a}{b}</div>, c, <div key="3">{d}{e}</div>], [<span key="0">{a}</span>, b, c, d, [e]], [a, b, <span key="0"><span>{c}</span></span>, d, e], [<div key="0">{a}</div>, [b], <span key="1">{c}</span>, [d], <div key="2">{e}</div>], [a, b, [c, <div key="0">{d}<span>{e}</span></div>], ''], [a, [[]], b, c, [d, [[]], e]], [[[a, b, c, d], e]], [a, b, c, d, e], ]; // 5. Test fresh mount for each case. for (let i = 0; i < cases.length; i++) { // Ensure fresh mount. container = document.createElement('div'); root = ReactDOMClient.createRoot(container); // Verify mounting 'abcde'. act(() => root.render(<Parent>{cases[i]}</Parent>)); expect(container.textContent).toMatch('abcde'); expect(print(store)).toEqual(snapshotForABCDE); // Verify switching to 'abxde'. act(() => { setShowX(true); }); expect(container.textContent).toMatch('abxde'); expect(print(store)).toBe(snapshotForABXDE); // Verify switching back to 'abcde'. act(() => { setShowX(false); }); expect(container.textContent).toMatch('abcde'); expect(print(store)).toBe(snapshotForABCDE); // Clean up. act(() => root.unmount()); expect(print(store)).toBe(''); } // 6. Verify *updates* by reusing the container between iterations. // There'll be no unmounting until the very end. container = document.createElement('div'); root = ReactDOMClient.createRoot(container); for (let i = 0; i < cases.length; i++) { // Verify mounting 'abcde'. act(() => root.render(<Parent>{cases[i]}</Parent>)); expect(container.textContent).toMatch('abcde'); expect(print(store)).toEqual(snapshotForABCDE); // Verify switching to 'abxde'. act(() => { setShowX(true); }); expect(container.textContent).toMatch('abxde'); expect(print(store)).toBe(snapshotForABXDE); // Verify switching back to 'abcde'. act(() => { setShowX(false); }); expect(container.textContent).toMatch('abcde'); expect(print(store)).toBe(snapshotForABCDE); // Don't unmount. Reuse the container between iterations. } act(() => root.unmount()); expect(print(store)).toBe(''); }); // @reactVersion >= 18.0 it('should handle stress test with reordering (Concurrent Mode)', () => { const A = () => 'a'; const B = () => 'b'; const C = () => 'c'; const D = () => 'd'; const E = () => 'e'; const a = <A key="a" />; const b = <B key="b" />; const c = <C key="c" />; const d = <D key="d" />; const e = <E key="e" />; // prettier-ignore const steps = [ a, b, c, d, e, [a], [b], [c], [d], [e], [a, b], [b, a], [b, c], [c, b], [a, c], [c, a], ]; const Root = ({children}) => { return children; }; // 1. Capture the expected render result. const snapshots = []; let container = document.createElement('div'); for (let i = 0; i < steps.length; i++) { const root = ReactDOMClient.createRoot(container); act(() => root.render(<Root>{steps[i]}</Root>)); // We snapshot each step once so it doesn't regress. snapshots.push(print(store)); act(() => root.unmount()); expect(print(store)).toBe(''); } expect(snapshots).toMatchInlineSnapshot(` [ "[root] ▾ <Root> <A key="a">", "[root] ▾ <Root> <B key="b">", "[root] ▾ <Root> <C key="c">", "[root] ▾ <Root> <D key="d">", "[root] ▾ <Root> <E key="e">", "[root] ▾ <Root> <A key="a">", "[root] ▾ <Root> <B key="b">", "[root] ▾ <Root> <C key="c">", "[root] ▾ <Root> <D key="d">", "[root] ▾ <Root> <E key="e">", "[root] ▾ <Root> <A key="a"> <B key="b">", "[root] ▾ <Root> <B key="b"> <A key="a">", "[root] ▾ <Root> <B key="b"> <C key="c">", "[root] ▾ <Root> <C key="c"> <B key="b">", "[root] ▾ <Root> <A key="a"> <C key="c">", "[root] ▾ <Root> <C key="c"> <A key="a">", ] `); // 2. Verify that we can update from every step to every other step and back. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render(<Root>{steps[i]}</Root>)); expect(print(store)).toMatch(snapshots[i]); act(() => root.render(<Root>{steps[j]}</Root>)); expect(print(store)).toMatch(snapshots[j]); act(() => root.render(<Root>{steps[i]}</Root>)); expect(print(store)).toMatch(snapshots[i]); act(() => root.unmount()); expect(print(store)).toBe(''); } } // 3. Same test as above, but this time we wrap children in a host component. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <div>{steps[i]}</div> </Root>, ), ); expect(print(store)).toMatch(snapshots[i]); act(() => root.render( <Root> <div>{steps[j]}</div> </Root>, ), ); expect(print(store)).toMatch(snapshots[j]); act(() => root.render( <Root> <div>{steps[i]}</div> </Root>, ), ); expect(print(store)).toMatch(snapshots[i]); act(() => root.unmount()); expect(print(store)).toBe(''); } } }); // @reactVersion >= 18.0 it('should handle a stress test for Suspense (Concurrent Mode)', async () => { const A = () => 'a'; const B = () => 'b'; const C = () => 'c'; const X = () => 'x'; const Y = () => 'y'; const Z = () => 'z'; const a = <A key="a" />; const b = <B key="b" />; const c = <C key="c" />; const z = <Z key="z" />; // prettier-ignore const steps = [ a, [a], [a, b, c], [c, b, a], [c, null, a], <React.Fragment>{c}{a}</React.Fragment>, <div>{c}{a}</div>, <div><span>{a}</span>{b}</div>, [[a]], null, b, a, ]; const Never = () => { throw new Promise(() => {}); }; const Root = ({children}) => { return children; }; // 1. For each step, check Suspense can render them as initial primary content. // This is the only step where we use Jest snapshots. const snapshots = []; let container = document.createElement('div'); for (let i = 0; i < steps.length; i++) { const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={z}>{steps[i]}</React.Suspense> <Y /> </Root>, ), ); // We snapshot each step once so it doesn't regress.d snapshots.push(print(store)); act(() => root.unmount()); expect(print(store)).toBe(''); } expect(snapshots).toMatchInlineSnapshot(` [ "[root] ▾ <Root> <X> ▾ <Suspense> <A key="a"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <A key="a"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <A key="a"> <B key="b"> <C key="c"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <C key="c"> <B key="b"> <A key="a"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <C key="c"> <A key="a"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <C key="c"> <A key="a"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <C key="c"> <A key="a"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <A key="a"> <B key="b"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <A key="a"> <Y>", "[root] ▾ <Root> <X> <Suspense> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <B key="b"> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> <A key="a"> <Y>", ] `); // 2. Verify check Suspense can render same steps as initial fallback content. for (let i = 0; i < steps.length; i++) { const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); act(() => root.unmount()); expect(print(store)).toBe(''); } // 3. Verify we can update from each step to each step in primary mode. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={z}>{steps[i]}</React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={z}>{steps[j]}</React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(snapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={z}>{steps[i]}</React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 4. Verify we can update from each step to each step in fallback mode. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(snapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 5. Verify we can update from each step to each step when moving primary -> fallback. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={z}>{steps[i]}</React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(snapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={z}>{steps[i]}</React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 6. Verify we can update from each step to each step when moving fallback -> primary. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={z}>{steps[j]}</React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(snapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 7. Verify we can update from each step to each step when toggling Suspense. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}>{steps[i]}</React.Suspense> <Y /> </Root>, ), ); // We get ID from the index in the tree above: // Root, X, Suspense, ... // ^ (index is 2) const suspenseID = store.getElementIDAtIndex(2); // Force fallback. expect(print(store)).toEqual(snapshots[i]); await actAsync(async () => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: true, }); }); expect(print(store)).toEqual(snapshots[j]); // Stop forcing fallback. await actAsync(async () => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: false, }); }); expect(print(store)).toEqual(snapshots[i]); // Trigger actual fallback. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <Z /> <Never /> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[j]); // Force fallback while we're in fallback mode. act(() => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: true, }); }); // Keep seeing fallback content. expect(print(store)).toEqual(snapshots[j]); // Switch to primary mode. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}>{steps[i]}</React.Suspense> <Y /> </Root>, ), ); // Fallback is still forced though. expect(print(store)).toEqual(snapshots[j]); // Stop forcing fallback. This reverts to primary content. await actAsync(async () => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: false, }); }); // Now we see primary content. expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. await actAsync(async () => root.unmount()); expect(print(store)).toBe(''); } } }); // @reactVersion >= 18.0 it('should handle a stress test for Suspense without type change (Concurrent Mode)', async () => { const A = () => 'a'; const B = () => 'b'; const C = () => 'c'; const X = () => 'x'; const Y = () => 'y'; const Z = () => 'z'; const a = <A key="a" />; const b = <B key="b" />; const c = <C key="c" />; const z = <Z key="z" />; // prettier-ignore const steps = [ a, [a], [a, b, c], [c, b, a], [c, null, a], <React.Fragment>{c}{a}</React.Fragment>, <div>{c}{a}</div>, <div><span>{a}</span>{b}</div>, [[a]], null, b, a, ]; const Never = () => { throw new Promise(() => {}); }; const MaybeSuspend = ({children, suspend}) => { if (suspend) { return ( <div> {children} <Never /> <X /> </div> ); } return ( <div> {children} <Z /> </div> ); }; const Root = ({children}) => { return children; }; // 1. For each step, check Suspense can render them as initial primary content. // This is the only step where we use Jest snapshots. const snapshots = []; let container = document.createElement('div'); for (let i = 0; i < steps.length; i++) { const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={z}> <MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); // We snapshot each step once so it doesn't regress. snapshots.push(print(store)); act(() => root.unmount()); expect(print(store)).toBe(''); } // 2. Verify check Suspense can render same steps as initial fallback content. // We don't actually assert here because the tree includes <MaybeSuspend> // which is different from the snapshots above. So we take more snapshots. const fallbackSnapshots = []; for (let i = 0; i < steps.length; i++) { const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <MaybeSuspend suspend={true}>{steps[i]}</MaybeSuspend> <Z /> </React.Suspense> <Y /> </Root>, ), ); // We snapshot each step once so it doesn't regress. fallbackSnapshots.push(print(store)); act(() => root.unmount()); expect(print(store)).toBe(''); } expect(snapshots).toMatchInlineSnapshot(` [ "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <A key="a"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <A key="a"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <A key="a"> <B key="b"> <C key="c"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <C key="c"> <B key="b"> <A key="a"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <C key="c"> <A key="a"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <C key="c"> <A key="a"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <C key="c"> <A key="a"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <A key="a"> <B key="b"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <A key="a"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <B key="b"> <Z> <Y>", "[root] ▾ <Root> <X> ▾ <Suspense> ▾ <MaybeSuspend> <A key="a"> <Z> <Y>", ] `); // 3. Verify we can update from each step to each step in primary mode. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={z}> <MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={z}> <MaybeSuspend suspend={false}>{steps[j]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(snapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={z}> <MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 4. Verify we can update from each step to each step in fallback mode. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <MaybeSuspend suspend={true}> <X /> <Y /> </MaybeSuspend> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(fallbackSnapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <Z /> <MaybeSuspend suspend={true}> <Y /> <X /> </MaybeSuspend> <Z /> </React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(fallbackSnapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <Z /> <MaybeSuspend suspend={true}> <X /> <Y /> </MaybeSuspend> <Z /> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(fallbackSnapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 5. Verify we can update from each step to each step when moving primary -> fallback. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={z}> <MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <MaybeSuspend suspend={true}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(fallbackSnapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={z}> <MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 6. Verify we can update from each step to each step when moving fallback -> primary. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <MaybeSuspend suspend={true}>{steps[j]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(fallbackSnapshots[i]); // Re-render with steps[j]. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <MaybeSuspend suspend={false}>{steps[j]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); // Verify the successful transition to steps[j]. expect(print(store)).toEqual(snapshots[j]); // Check that we can transition back again. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[i]}> <MaybeSuspend suspend={true}>{steps[j]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(fallbackSnapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } // 7. Verify we can update from each step to each step when toggling Suspense. for (let i = 0; i < steps.length; i++) { for (let j = 0; j < steps.length; j++) { // Always start with a fresh container and steps[i]. container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); // We get ID from the index in the tree above: // Root, X, Suspense, ... // ^ (index is 2) const suspenseID = store.getElementIDAtIndex(2); // Force fallback. expect(print(store)).toEqual(snapshots[i]); await actAsync(async () => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: true, }); }); expect(print(store)).toEqual(fallbackSnapshots[j]); // Stop forcing fallback. await actAsync(async () => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: false, }); }); expect(print(store)).toEqual(snapshots[i]); // Trigger actual fallback. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <MaybeSuspend suspend={true}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); expect(print(store)).toEqual(fallbackSnapshots[j]); // Force fallback while we're in fallback mode. act(() => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: true, }); }); // Keep seeing fallback content. expect(print(store)).toEqual(fallbackSnapshots[j]); // Switch to primary mode. act(() => root.render( <Root> <X /> <React.Suspense fallback={steps[j]}> <MaybeSuspend suspend={false}>{steps[i]}</MaybeSuspend> </React.Suspense> <Y /> </Root>, ), ); // Fallback is still forced though. expect(print(store)).toEqual(fallbackSnapshots[j]); // Stop forcing fallback. This reverts to primary content. await actAsync(async () => { bridge.send('overrideSuspense', { id: suspenseID, rendererID: store.getRendererIDForElement(suspenseID), forceFallback: false, }); }); // Now we see primary content. expect(print(store)).toEqual(snapshots[i]); // Clean up after every iteration. act(() => root.unmount()); expect(print(store)).toBe(''); } } }); });
27.469253
100
0.442116
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 */ /** * This is a renderer of React that doesn't have a render target output. * It is useful to demonstrate the internals of the reconciler in isolation * and for testing semantics of reconciliation separate from the host * environment. */ import type { Fiber, TransitionTracingCallbacks, } from 'react-reconciler/src/ReactInternalTypes'; import type {UpdateQueue} from 'react-reconciler/src/ReactFiberClassUpdateQueue'; import type {ReactNodeList} from 'shared/ReactTypes'; import type {RootTag} from 'react-reconciler/src/ReactRootTags'; import * as Scheduler from 'scheduler/unstable_mock'; import {REACT_FRAGMENT_TYPE, REACT_ELEMENT_TYPE} from 'shared/ReactSymbols'; import isArray from 'shared/isArray'; import {checkPropStringCoercion} from 'shared/CheckStringCoercion'; import { DefaultEventPriority, IdleEventPriority, ConcurrentRoot, LegacyRoot, } from 'react-reconciler/constants'; type Container = { rootID: string, children: Array<Instance | TextInstance>, pendingChildren: Array<Instance | TextInstance>, ... }; type Props = { prop: any, hidden: boolean, children?: mixed, bottom?: null | number, left?: null | number, right?: null | number, top?: null | number, src?: string, ... }; type Instance = { type: string, id: number, parent: number, children: Array<Instance | TextInstance>, text: string | null, prop: any, hidden: boolean, context: HostContext, }; type TextInstance = { text: string, id: number, parent: number, hidden: boolean, context: HostContext, }; type HostContext = Object; type CreateRootOptions = { unstable_transitionCallbacks?: TransitionTracingCallbacks, ... }; type SuspenseyCommitSubscription = { pendingCount: number, commit: null | (() => void), }; export type TransitionStatus = mixed; const NO_CONTEXT = {}; const UPPERCASE_CONTEXT = {}; if (__DEV__) { Object.freeze(NO_CONTEXT); } function createReactNoop(reconciler: Function, useMutation: boolean) { let instanceCounter = 0; let hostUpdateCounter = 0; let hostCloneCounter = 0; function appendChildToContainerOrInstance( parentInstance: Container | Instance, child: Instance | TextInstance, ): void { const prevParent = child.parent; if (prevParent !== -1 && prevParent !== parentInstance.id) { throw new Error('Reparenting is not allowed'); } child.parent = parentInstance.id; const index = parentInstance.children.indexOf(child); if (index !== -1) { parentInstance.children.splice(index, 1); } parentInstance.children.push(child); } function appendChildToContainer( parentInstance: Container, child: Instance | TextInstance, ): void { if (typeof parentInstance.rootID !== 'string') { // Some calls to this aren't typesafe. // This helps surface mistakes in tests. throw new Error( 'appendChildToContainer() first argument is not a container.', ); } appendChildToContainerOrInstance(parentInstance, child); } function appendChild( parentInstance: Instance, child: Instance | TextInstance, ): void { if (typeof (parentInstance: any).rootID === 'string') { // Some calls to this aren't typesafe. // This helps surface mistakes in tests. throw new Error('appendChild() first argument is not an instance.'); } appendChildToContainerOrInstance(parentInstance, child); } function insertInContainerOrInstanceBefore( parentInstance: Container | Instance, child: Instance | TextInstance, beforeChild: Instance | TextInstance, ): void { const index = parentInstance.children.indexOf(child); if (index !== -1) { parentInstance.children.splice(index, 1); } const beforeIndex = parentInstance.children.indexOf(beforeChild); if (beforeIndex === -1) { throw new Error('This child does not exist.'); } parentInstance.children.splice(beforeIndex, 0, child); } function insertInContainerBefore( parentInstance: Container, child: Instance | TextInstance, beforeChild: Instance | TextInstance, ) { if (typeof parentInstance.rootID !== 'string') { // Some calls to this aren't typesafe. // This helps surface mistakes in tests. throw new Error( 'insertInContainerBefore() first argument is not a container.', ); } insertInContainerOrInstanceBefore(parentInstance, child, beforeChild); } function insertBefore( parentInstance: Instance, child: Instance | TextInstance, beforeChild: Instance | TextInstance, ) { if (typeof (parentInstance: any).rootID === 'string') { // Some calls to this aren't typesafe. // This helps surface mistakes in tests. throw new Error('insertBefore() first argument is not an instance.'); } insertInContainerOrInstanceBefore(parentInstance, child, beforeChild); } function clearContainer(container: Container): void { container.children.splice(0); } function removeChildFromContainerOrInstance( parentInstance: Container | Instance, child: Instance | TextInstance, ): void { const index = parentInstance.children.indexOf(child); if (index === -1) { throw new Error('This child does not exist.'); } parentInstance.children.splice(index, 1); } function removeChildFromContainer( parentInstance: Container, child: Instance | TextInstance, ): void { if (typeof parentInstance.rootID !== 'string') { // Some calls to this aren't typesafe. // This helps surface mistakes in tests. throw new Error( 'removeChildFromContainer() first argument is not a container.', ); } removeChildFromContainerOrInstance(parentInstance, child); } function removeChild( parentInstance: Instance, child: Instance | TextInstance, ): void { if (typeof (parentInstance: any).rootID === 'string') { // Some calls to this aren't typesafe. // This helps surface mistakes in tests. throw new Error('removeChild() first argument is not an instance.'); } removeChildFromContainerOrInstance(parentInstance, child); } function cloneInstance( instance: Instance, type: string, oldProps: Props, newProps: Props, keepChildren: boolean, children: ?$ReadOnlyArray<Instance>, ): Instance { if (__DEV__) { checkPropStringCoercion(newProps.children, 'children'); } const clone = { id: instance.id, type: type, parent: instance.parent, children: keepChildren ? instance.children : children ?? [], text: shouldSetTextContent(type, newProps) ? computeText((newProps.children: any) + '', instance.context) : null, prop: newProps.prop, hidden: !!newProps.hidden, context: instance.context, }; if (type === 'suspensey-thing' && typeof newProps.src === 'string') { clone.src = newProps.src; } Object.defineProperty(clone, 'id', { value: clone.id, enumerable: false, }); Object.defineProperty(clone, 'parent', { value: clone.parent, enumerable: false, }); Object.defineProperty(clone, 'text', { value: clone.text, enumerable: false, }); Object.defineProperty(clone, 'context', { value: clone.context, enumerable: false, }); hostCloneCounter++; return clone; } function shouldSetTextContent(type: string, props: Props): boolean { if (type === 'errorInBeginPhase') { throw new Error('Error in host config.'); } return ( typeof props.children === 'string' || typeof props.children === 'number' ); } function computeText(rawText, hostContext) { return hostContext === UPPERCASE_CONTEXT ? rawText.toUpperCase() : rawText; } type SuspenseyThingRecord = { status: 'pending' | 'fulfilled', subscriptions: Array<SuspenseyCommitSubscription> | null, }; let suspenseyThingCache: Map< SuspenseyThingRecord, 'pending' | 'fulfilled', > | null = null; // Represents a subscription for all the suspensey things that block a // particular commit. Once they've all loaded, the commit phase can proceed. let suspenseyCommitSubscription: SuspenseyCommitSubscription | null = null; function startSuspendingCommit(): void { // This is where we might suspend on things that aren't associated with a // particular node, like document.fonts.ready. suspenseyCommitSubscription = null; } function suspendInstance(type: string, props: Props): void { const src = props.src; if (type === 'suspensey-thing' && typeof src === 'string') { // Attach a listener to the suspensey thing and create a subscription // object that uses reference counting to track when all the suspensey // things have loaded. const record = suspenseyThingCache.get(src); if (record === undefined) { throw new Error('Could not find record for key.'); } if (record.status === 'fulfilled') { // Already loaded. } else if (record.status === 'pending') { if (suspenseyCommitSubscription === null) { suspenseyCommitSubscription = { pendingCount: 1, commit: null, }; } else { suspenseyCommitSubscription.pendingCount++; } // Stash the subscription on the record. In `resolveSuspenseyThing`, // we'll use this fire the commit once all the things have loaded. if (record.subscriptions === null) { record.subscriptions = []; } record.subscriptions.push(suspenseyCommitSubscription); } } else { throw new Error( 'Did not expect this host component to be visited when suspending ' + 'the commit. Did you check the SuspendCommit flag?', ); } } function waitForCommitToBeReady(): | ((commit: () => mixed) => () => void) | null { const subscription = suspenseyCommitSubscription; if (subscription !== null) { suspenseyCommitSubscription = null; return (commit: () => void) => { subscription.commit = commit; const cancelCommit = () => { subscription.commit = null; }; return cancelCommit; }; } return null; } const sharedHostConfig = { supportsSingletons: false, getRootHostContext() { return NO_CONTEXT; }, getChildHostContext(parentHostContext: HostContext, type: string) { if (type === 'offscreen') { return parentHostContext; } if (type === 'uppercase') { return UPPERCASE_CONTEXT; } return NO_CONTEXT; }, getPublicInstance(instance) { return instance; }, createInstance( type: string, props: Props, rootContainerInstance: Container, hostContext: HostContext, internalInstanceHandle: Object, ): Instance { if (type === 'errorInCompletePhase') { throw new Error('Error in host config.'); } if (__DEV__) { // The `if` statement here prevents auto-disabling of the safe coercion // ESLint rule, so we must manually disable it below. if (shouldSetTextContent(type, props)) { checkPropStringCoercion(props.children, 'children'); } } const inst = { id: instanceCounter++, type: type, children: [], parent: -1, text: shouldSetTextContent(type, props) ? // eslint-disable-next-line react-internal/safe-string-coercion computeText((props.children: any) + '', hostContext) : null, prop: props.prop, hidden: !!props.hidden, context: hostContext, }; if (type === 'suspensey-thing' && typeof props.src === 'string') { inst.src = props.src; } // Hide from unit tests Object.defineProperty(inst, 'id', {value: inst.id, enumerable: false}); Object.defineProperty(inst, 'parent', { value: inst.parent, enumerable: false, }); Object.defineProperty(inst, 'text', { value: inst.text, enumerable: false, }); Object.defineProperty(inst, 'context', { value: inst.context, enumerable: false, }); Object.defineProperty(inst, 'fiber', { value: internalInstanceHandle, enumerable: false, }); return inst; }, appendInitialChild( parentInstance: Instance, child: Instance | TextInstance, ): void { const prevParent = child.parent; if (prevParent !== -1 && prevParent !== parentInstance.id) { throw new Error('Reparenting is not allowed'); } child.parent = parentInstance.id; parentInstance.children.push(child); }, finalizeInitialChildren( domElement: Instance, type: string, props: Props, ): boolean { return false; }, shouldSetTextContent, createTextInstance( text: string, rootContainerInstance: Container, hostContext: Object, internalInstanceHandle: Object, ): TextInstance { if (hostContext === UPPERCASE_CONTEXT) { text = text.toUpperCase(); } const inst = { text: text, id: instanceCounter++, parent: -1, hidden: false, context: hostContext, }; // Hide from unit tests Object.defineProperty(inst, 'id', {value: inst.id, enumerable: false}); Object.defineProperty(inst, 'parent', { value: inst.parent, enumerable: false, }); Object.defineProperty(inst, 'context', { value: inst.context, enumerable: false, }); return inst; }, scheduleTimeout: setTimeout, cancelTimeout: clearTimeout, noTimeout: -1, supportsMicrotasks: true, scheduleMicrotask: typeof queueMicrotask === 'function' ? queueMicrotask : typeof Promise !== 'undefined' ? callback => Promise.resolve(null) .then(callback) .catch(error => { setTimeout(() => { throw error; }); }) : setTimeout, prepareForCommit(): null | Object { return null; }, resetAfterCommit(): void {}, getCurrentEventPriority() { return currentEventPriority; }, shouldAttemptEagerTransition(): boolean { return false; }, now: Scheduler.unstable_now, isPrimaryRenderer: true, warnsIfNotActing: true, supportsHydration: false, getInstanceFromNode() { throw new Error('Not yet implemented.'); }, beforeActiveInstanceBlur() { // NO-OP }, afterActiveInstanceBlur() { // NO-OP }, preparePortalMount() { // NO-OP }, prepareScopeUpdate() {}, getInstanceFromScope() { throw new Error('Not yet implemented.'); }, detachDeletedInstance() {}, logRecoverableError() { // no-op }, requestPostPaintCallback(callback) { const endTime = Scheduler.unstable_now(); callback(endTime); }, maySuspendCommit(type: string, props: Props): boolean { // Asks whether it's possible for this combination of type and props // to ever need to suspend. This is different from asking whether it's // currently ready because even if it's ready now, it might get purged // from the cache later. return type === 'suspensey-thing' && typeof props.src === 'string'; }, mayResourceSuspendCommit(resource: mixed): boolean { throw new Error( 'Resources are not implemented for React Noop yet. This method should not be called', ); }, preloadInstance(type: string, props: Props): boolean { if (type !== 'suspensey-thing' || typeof props.src !== 'string') { throw new Error('Attempted to preload unexpected instance: ' + type); } // In addition to preloading an instance, this method asks whether the // instance is ready to be committed. If it's not, React may yield to the // main thread and ask again. It's possible a load event will fire in // between, in which case we can avoid showing a fallback. if (suspenseyThingCache === null) { suspenseyThingCache = new Map(); } const record = suspenseyThingCache.get(props.src); if (record === undefined) { const newRecord: SuspenseyThingRecord = { status: 'pending', subscriptions: null, }; suspenseyThingCache.set(props.src, newRecord); const onLoadStart = props.onLoadStart; if (typeof onLoadStart === 'function') { onLoadStart(); } return false; } else { // If this is false, React will trigger a fallback, if needed. return record.status === 'fulfilled'; } }, preloadResource(resource: mixed): boolean { throw new Error( 'Resources are not implemented for React Noop yet. This method should not be called', ); }, startSuspendingCommit, suspendInstance, suspendResource(resource: mixed): void { throw new Error( 'Resources are not implemented for React Noop yet. This method should not be called', ); }, waitForCommitToBeReady, NotPendingTransition: (null: TransitionStatus), }; const hostConfig = useMutation ? { ...sharedHostConfig, supportsMutation: true, supportsPersistence: false, commitMount(instance: Instance, type: string, newProps: Props): void { // Noop }, commitUpdate( instance: Instance, updatePayload: Object, type: string, oldProps: Props, newProps: Props, ): void { if (oldProps === null) { throw new Error('Should have old props'); } hostUpdateCounter++; instance.prop = newProps.prop; instance.hidden = !!newProps.hidden; if (type === 'suspensey-thing' && typeof newProps.src === 'string') { instance.src = newProps.src; } if (shouldSetTextContent(type, newProps)) { if (__DEV__) { checkPropStringCoercion(newProps.children, 'children'); } instance.text = computeText( (newProps.children: any) + '', instance.context, ); } }, commitTextUpdate( textInstance: TextInstance, oldText: string, newText: string, ): void { hostUpdateCounter++; textInstance.text = computeText(newText, textInstance.context); }, appendChild, appendChildToContainer, insertBefore, insertInContainerBefore, removeChild, removeChildFromContainer, clearContainer, hideInstance(instance: Instance): void { instance.hidden = true; }, hideTextInstance(textInstance: TextInstance): void { textInstance.hidden = true; }, unhideInstance(instance: Instance, props: Props): void { if (!props.hidden) { instance.hidden = false; } }, unhideTextInstance(textInstance: TextInstance, text: string): void { textInstance.hidden = false; }, resetTextContent(instance: Instance): void { instance.text = null; }, } : { ...sharedHostConfig, supportsMutation: false, supportsPersistence: true, cloneInstance, clearContainer, createContainerChildSet(): Array<Instance | TextInstance> { return []; }, appendChildToContainerChildSet( childSet: Array<Instance | TextInstance>, child: Instance | TextInstance, ): void { childSet.push(child); }, finalizeContainerChildren( container: Container, newChildren: Array<Instance | TextInstance>, ): void { container.pendingChildren = newChildren; if ( newChildren.length === 1 && newChildren[0].text === 'Error when completing root' ) { // Trigger an error for testing purposes throw Error('Error when completing root'); } }, replaceContainerChildren( container: Container, newChildren: Array<Instance | TextInstance>, ): void { container.children = newChildren; }, cloneHiddenInstance( instance: Instance, type: string, props: Props, ): Instance { const clone = cloneInstance(instance, type, props, props, true, null); clone.hidden = true; return clone; }, cloneHiddenTextInstance( instance: TextInstance, text: string, ): TextInstance { const clone = { text: instance.text, id: instance.id, parent: instance.parent, hidden: true, context: instance.context, }; // Hide from unit tests Object.defineProperty(clone, 'id', { value: clone.id, enumerable: false, }); Object.defineProperty(clone, 'parent', { value: clone.parent, enumerable: false, }); Object.defineProperty(clone, 'context', { value: clone.context, enumerable: false, }); return clone; }, }; const NoopRenderer = reconciler(hostConfig); const rootContainers = new Map(); const roots = new Map(); const DEFAULT_ROOT_ID = '<default>'; let currentEventPriority = DefaultEventPriority; function childToJSX(child, text) { if (text !== null) { return text; } if (child === null) { return null; } if (typeof child === 'string') { return child; } if (isArray(child)) { if (child.length === 0) { return null; } if (child.length === 1) { return childToJSX(child[0], null); } const children = child.map(c => childToJSX(c, null)); if (children.every(c => typeof c === 'string' || typeof c === 'number')) { return children.join(''); } return children; } if (isArray(child.children)) { // This is an instance. const instance: Instance = (child: any); const children = childToJSX(instance.children, instance.text); const props = ({prop: instance.prop}: any); if (instance.hidden) { props.hidden = true; } if (instance.src) { props.src = instance.src; } if (children !== null) { props.children = children; } return { $$typeof: REACT_ELEMENT_TYPE, type: instance.type, key: null, ref: null, props: props, _owner: null, _store: __DEV__ ? {} : undefined, }; } // This is a text instance const textInstance: TextInstance = (child: any); if (textInstance.hidden) { return ''; } return textInstance.text; } function getChildren(root) { if (root) { return root.children; } else { return null; } } function getPendingChildren(root) { if (root) { return root.children; } else { return null; } } function getChildrenAsJSX(root) { const children = childToJSX(getChildren(root), null); if (children === null) { return null; } if (isArray(children)) { return { $$typeof: REACT_ELEMENT_TYPE, type: REACT_FRAGMENT_TYPE, key: null, ref: null, props: {children}, _owner: null, _store: __DEV__ ? {} : undefined, }; } return children; } function getPendingChildrenAsJSX(root) { const children = childToJSX(getChildren(root), null); if (children === null) { return null; } if (isArray(children)) { return { $$typeof: REACT_ELEMENT_TYPE, type: REACT_FRAGMENT_TYPE, key: null, ref: null, props: {children}, _owner: null, _store: __DEV__ ? {} : undefined, }; } return children; } function flushSync<R>(fn: () => R): R { if (__DEV__) { if (NoopRenderer.isAlreadyRendering()) { console.error( 'flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.', ); } } return NoopRenderer.flushSync(fn); } function onRecoverableError(error) { // TODO: Turn this on once tests are fixed // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args // console.error(error); } let idCounter = 0; const ReactNoop = { _Scheduler: Scheduler, getChildren(rootID: string = DEFAULT_ROOT_ID) { throw new Error( 'No longer supported due to bad performance when used with `expect()`. ' + 'Use `ReactNoop.getChildrenAsJSX()` instead or, if you really need to, `dangerouslyGetChildren` after you carefully considered the warning in its JSDOC.', ); }, getPendingChildren(rootID: string = DEFAULT_ROOT_ID) { throw new Error( 'No longer supported due to bad performance when used with `expect()`. ' + 'Use `ReactNoop.getPendingChildrenAsJSX()` instead or, if you really need to, `dangerouslyGetPendingChildren` after you carefully considered the warning in its JSDOC.', ); }, /** * Prefer using `getChildrenAsJSX`. * Using the returned children in `.toEqual` has very poor performance on mismatch due to deep equality checking of fiber structures. * Make sure you deeply remove enumerable properties before passing it to `.toEqual`, or, better, use `getChildrenAsJSX` or `toMatchRenderedOutput`. */ dangerouslyGetChildren(rootID: string = DEFAULT_ROOT_ID) { const container = rootContainers.get(rootID); return getChildren(container); }, /** * Prefer using `getPendingChildrenAsJSX`. * Using the returned children in `.toEqual` has very poor performance on mismatch due to deep equality checking of fiber structures. * Make sure you deeply remove enumerable properties before passing it to `.toEqual`, or, better, use `getChildrenAsJSX` or `toMatchRenderedOutput`. */ dangerouslyGetPendingChildren(rootID: string = DEFAULT_ROOT_ID) { const container = rootContainers.get(rootID); return getPendingChildren(container); }, getOrCreateRootContainer(rootID: string = DEFAULT_ROOT_ID, tag: RootTag) { let root = roots.get(rootID); if (!root) { const container = {rootID: rootID, pendingChildren: [], children: []}; rootContainers.set(rootID, container); root = NoopRenderer.createContainer( container, tag, null, null, false, '', onRecoverableError, null, ); roots.set(rootID, root); } return root.current.stateNode.containerInfo; }, // TODO: Replace ReactNoop.render with createRoot + root.render createRoot(options?: CreateRootOptions) { const container = { rootID: '' + idCounter++, pendingChildren: [], children: [], }; const fiberRoot = NoopRenderer.createContainer( container, ConcurrentRoot, null, null, false, '', onRecoverableError, options && options.unstable_transitionCallbacks ? options.unstable_transitionCallbacks : null, ); return { _Scheduler: Scheduler, render(children: ReactNodeList) { NoopRenderer.updateContainer(children, fiberRoot, null, null); }, getChildren() { return getChildren(container); }, getChildrenAsJSX() { return getChildrenAsJSX(container); }, }; }, createLegacyRoot() { const container = { rootID: '' + idCounter++, pendingChildren: [], children: [], }; const fiberRoot = NoopRenderer.createContainer( container, LegacyRoot, null, null, false, '', onRecoverableError, null, ); return { _Scheduler: Scheduler, render(children: ReactNodeList) { NoopRenderer.updateContainer(children, fiberRoot, null, null); }, getChildren() { return getChildren(container); }, getChildrenAsJSX() { return getChildrenAsJSX(container); }, }; }, getChildrenAsJSX(rootID: string = DEFAULT_ROOT_ID) { const container = rootContainers.get(rootID); return getChildrenAsJSX(container); }, getPendingChildrenAsJSX(rootID: string = DEFAULT_ROOT_ID) { const container = rootContainers.get(rootID); return getPendingChildrenAsJSX(container); }, getSuspenseyThingStatus(src): string | null { if (suspenseyThingCache === null) { return null; } else { const record = suspenseyThingCache.get(src); return record === undefined ? null : record.status; } }, resolveSuspenseyThing(key: string): void { if (suspenseyThingCache === null) { suspenseyThingCache = new Map(); } const record = suspenseyThingCache.get(key); if (record === undefined) { const newRecord: SuspenseyThingRecord = { status: 'fulfilled', subscriptions: null, }; suspenseyThingCache.set(key, newRecord); } else { if (record.status === 'pending') { record.status = 'fulfilled'; const subscriptions = record.subscriptions; if (subscriptions !== null) { record.subscriptions = null; for (let i = 0; i < subscriptions.length; i++) { const subscription = subscriptions[i]; subscription.pendingCount--; if (subscription.pendingCount === 0) { const commit = subscription.commit; subscription.commit = null; commit(); } } } } } }, resetSuspenseyThingCache() { suspenseyThingCache = null; }, createPortal( children: ReactNodeList, container: Container, key: ?string = null, ) { return NoopRenderer.createPortal(children, container, null, key); }, // Shortcut for testing a single root render(element: React$Element<any>, callback: ?Function) { ReactNoop.renderToRootWithID(element, DEFAULT_ROOT_ID, callback); }, renderLegacySyncRoot(element: React$Element<any>, callback: ?Function) { const rootID = DEFAULT_ROOT_ID; const container = ReactNoop.getOrCreateRootContainer(rootID, LegacyRoot); const root = roots.get(container.rootID); NoopRenderer.updateContainer(element, root, null, callback); }, renderToRootWithID( element: React$Element<any>, rootID: string, callback: ?Function, ) { const container = ReactNoop.getOrCreateRootContainer( rootID, ConcurrentRoot, ); const root = roots.get(container.rootID); NoopRenderer.updateContainer(element, root, null, callback); }, unmountRootWithID(rootID: string) { const root = roots.get(rootID); if (root) { NoopRenderer.updateContainer(null, root, null, () => { roots.delete(rootID); rootContainers.delete(rootID); }); } }, findInstance( componentOrElement: Element | ?React$Component<any, any>, ): null | Instance | TextInstance { if (componentOrElement == null) { return null; } // Unsound duck typing. const component = (componentOrElement: any); if (typeof component.id === 'number') { return component; } if (__DEV__) { return NoopRenderer.findHostInstanceWithWarning( component, 'findInstance', ); } return NoopRenderer.findHostInstance(component); }, flushNextYield(): Array<mixed> { Scheduler.unstable_flushNumberOfYields(1); return Scheduler.unstable_clearLog(); }, startTrackingHostCounters(): void { hostUpdateCounter = 0; hostCloneCounter = 0; }, stopTrackingHostCounters(): | { hostUpdateCounter: number, } | { hostCloneCounter: number, } { const result = useMutation ? { hostUpdateCounter, } : { hostCloneCounter, }; hostUpdateCounter = 0; hostCloneCounter = 0; return result; }, expire: Scheduler.unstable_advanceTime, flushExpired(): Array<mixed> { return Scheduler.unstable_flushExpired(); }, unstable_runWithPriority: NoopRenderer.runWithPriority, batchedUpdates: NoopRenderer.batchedUpdates, deferredUpdates: NoopRenderer.deferredUpdates, discreteUpdates: NoopRenderer.discreteUpdates, idleUpdates<T>(fn: () => T): T { const prevEventPriority = currentEventPriority; currentEventPriority = IdleEventPriority; try { fn(); } finally { currentEventPriority = prevEventPriority; } }, flushSync, flushPassiveEffects: NoopRenderer.flushPassiveEffects, // Logs the current state of the tree. dumpTree(rootID: string = DEFAULT_ROOT_ID) { const root = roots.get(rootID); const rootContainer = rootContainers.get(rootID); if (!root || !rootContainer) { // eslint-disable-next-line react-internal/no-production-logging console.log('Nothing rendered yet.'); return; } const bufferedLog = []; function log(...args) { bufferedLog.push(...args, '\n'); } function logHostInstances( children: Array<Instance | TextInstance>, depth, ) { for (let i = 0; i < children.length; i++) { const child = children[i]; const indent = ' '.repeat(depth); if (typeof child.text === 'string') { log(indent + '- ' + child.text); } else { log(indent + '- ' + child.type + '#' + child.id); logHostInstances(child.children, depth + 1); } } } function logContainer(container: Container, depth) { log(' '.repeat(depth) + '- [root#' + container.rootID + ']'); logHostInstances(container.children, depth + 1); } function logUpdateQueue(updateQueue: UpdateQueue<mixed>, depth) { log(' '.repeat(depth + 1) + 'QUEUED UPDATES'); const first = updateQueue.firstBaseUpdate; const update = first; if (update !== null) { do { log( ' '.repeat(depth + 1) + '~', '[' + update.expirationTime + ']', ); } while (update !== null); } const lastPending = updateQueue.shared.pending; if (lastPending !== null) { const firstPending = lastPending.next; const pendingUpdate = firstPending; if (pendingUpdate !== null) { do { log( ' '.repeat(depth + 1) + '~', '[' + pendingUpdate.expirationTime + ']', ); } while (pendingUpdate !== null && pendingUpdate !== firstPending); } } } function logFiber(fiber: Fiber, depth) { log( ' '.repeat(depth) + '- ' + // need to explicitly coerce Symbol to a string (fiber.type ? fiber.type.name || fiber.type.toString() : '[root]'), '[' + fiber.childExpirationTime + (fiber.pendingProps ? '*' : '') + ']', ); if (fiber.updateQueue) { logUpdateQueue(fiber.updateQueue, depth); } // const childInProgress = fiber.progressedChild; // if (childInProgress && childInProgress !== fiber.child) { // log( // ' '.repeat(depth + 1) + 'IN PROGRESS: ' + fiber.pendingWorkPriority, // ); // logFiber(childInProgress, depth + 1); // if (fiber.child) { // log(' '.repeat(depth + 1) + 'CURRENT'); // } // } else if (fiber.child && fiber.updateQueue) { // log(' '.repeat(depth + 1) + 'CHILDREN'); // } if (fiber.child) { logFiber(fiber.child, depth + 1); } if (fiber.sibling) { logFiber(fiber.sibling, depth); } } log('HOST INSTANCES:'); logContainer(rootContainer, 0); log('FIBERS:'); logFiber(root.current, 0); // eslint-disable-next-line react-internal/no-production-logging console.log(...bufferedLog); }, getRoot(rootID: string = DEFAULT_ROOT_ID) { return roots.get(rootID); }, }; return ReactNoop; } export default createReactNoop;
27.577475
178
0.593197
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-dom-test-utils.production.min.js'); } else { module.exports = require('./cjs/react-dom-test-utils.development.js'); }
26.625
75
0.681818
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 {evalStringConcat} = require('../evalToString'); const parser = require('@babel/parser'); const parse = source => parser.parse(`(${source});`).program.body[0].expression; // quick way to get an exp node const parseAndEval = source => evalStringConcat(parse(source)); describe('evalToString', () => { it('should support StringLiteral', () => { expect(parseAndEval(`'foobar'`)).toBe('foobar'); expect(parseAndEval(`'yowassup'`)).toBe('yowassup'); }); it('should support string concat (`+`)', () => { expect(parseAndEval(`'foo ' + 'bar'`)).toBe('foo bar'); }); it('should throw when it finds other types', () => { expect(() => parseAndEval(`'foo ' + true`)).toThrowError( /Unsupported type/ ); expect(() => parseAndEval(`'foo ' + 3`)).toThrowError(/Unsupported type/); expect(() => parseAndEval(`'foo ' + null`)).toThrowError( /Unsupported type/ ); expect(() => parseAndEval(`'foo ' + undefined`)).toThrowError( /Unsupported type/ ); }); });
30.461538
112
0.624796
owtf
'use client'; import * as React from 'react'; import {useFormStatus} from 'react-dom'; import ErrorBoundary from './ErrorBoundary.js'; const h = React.createElement; function Status() { const {pending} = useFormStatus(); return pending ? 'Saving...' : null; } export default function Form({action, children}) { const [isPending, setIsPending] = React.useState(false); return h( ErrorBoundary, null, h( 'form', { action: action, }, h( 'label', {}, 'Name: ', h('input', { name: 'name', }) ), h( 'label', {}, 'File: ', h('input', { type: 'file', name: 'file', }) ), h('button', {}, 'Say Hi'), h(Status, {}) ) ); }
16.695652
58
0.473555
owtf
var React = require('react'); var ReactDOM = require('react-dom'); ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') );
21.375
50
0.702247
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } // ?sourceMappingURL=([^\s'"]+)/gm function Component() { const [count, setCount] = (0, _react.useState)(0); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 18, columnNumber: 5 } }, /*#__PURE__*/_react.default.createElement("p", { __source: { fileName: _jsxFileName, lineNumber: 19, columnNumber: 7 } }, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", { onClick: () => setCount(count + 1), __source: { fileName: _jsxFileName, lineNumber: 20, columnNumber: 7 } }, "Click me")); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbnRhaW5pbmdTdHJpbmdTb3VyY2VNYXBwaW5nVVJMLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFFQTtBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuLy8gP3NvdXJjZU1hcHBpbmdVUkw9KFteXFxzJ1wiXSspL2dtXG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IFtjb3VudCwgc2V0Q291bnRdID0gdXNlU3RhdGUoMCk7XG5cbiAgcmV0dXJuIChcbiAgICA8ZGl2PlxuICAgICAgPHA+WW91IGNsaWNrZWQge2NvdW50fSB0aW1lczwvcD5cbiAgICAgIDxidXR0b24gb25DbGljaz17KCkgPT4gc2V0Q291bnQoY291bnQgKyAxKX0+Q2xpY2sgbWU8L2J1dHRvbj5cbiAgICA8L2Rpdj5cbiAgKTtcbn1cbiJdfX1dfQ==
79.95
1,444
0.796416
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 */ // TODO: direct imports like some-package/src/* are bad. Fix me. import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber'; import {getToStringValue, toString} from './ToStringValue'; import isArray from 'shared/isArray'; let didWarnValueDefaultValue; if (__DEV__) { didWarnValueDefaultValue = false; } function getDeclarationErrorAddendum() { const ownerName = getCurrentFiberOwnerNameInDevOrNull(); if (ownerName) { return '\n\nCheck the render method of `' + ownerName + '`.'; } return ''; } const valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. */ function checkSelectPropTypes(props: any) { if (__DEV__) { for (let i = 0; i < valuePropNames.length; i++) { const propName = valuePropNames[i]; if (props[propName] == null) { continue; } const propNameIsArray = isArray(props[propName]); if (props.multiple && !propNameIsArray) { console.error( 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(), ); } else if (!props.multiple && propNameIsArray) { console.error( 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(), ); } } } } function updateOptions( node: HTMLSelectElement, multiple: boolean, propValue: any, setDefaultSelected: boolean, ) { const options: HTMLOptionsCollection = node.options; if (multiple) { const selectedValues = (propValue: Array<string>); const selectedValue: {[string]: boolean} = {}; for (let i = 0; i < selectedValues.length; i++) { // Prefix to avoid chaos with special keys. selectedValue['$' + selectedValues[i]] = true; } for (let i = 0; i < options.length; i++) { const selected = selectedValue.hasOwnProperty('$' + options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } if (selected && setDefaultSelected) { options[i].defaultSelected = true; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. const selectedValue = toString(getToStringValue((propValue: any))); let defaultSelected = null; for (let i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; if (setDefaultSelected) { options[i].defaultSelected = true; } return; } if (defaultSelected === null && !options[i].disabled) { defaultSelected = options[i]; } } if (defaultSelected !== null) { defaultSelected.selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ export function validateSelectProps(element: Element, props: Object) { if (__DEV__) { checkSelectPropTypes(props); if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue ) { console.error( 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', ); didWarnValueDefaultValue = true; } } } export function initSelect( element: Element, value: ?string, defaultValue: ?string, multiple: ?boolean, ) { const node: HTMLSelectElement = (element: any); node.multiple = !!multiple; if (value != null) { updateOptions(node, !!multiple, value, false); } else if (defaultValue != null) { updateOptions(node, !!multiple, defaultValue, true); } } export function updateSelect( element: Element, value: ?string, defaultValue: ?string, multiple: ?boolean, wasMultiple: ?boolean, ) { const node: HTMLSelectElement = (element: any); if (value != null) { updateOptions(node, !!multiple, value, false); } else if (!!wasMultiple !== !!multiple) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (defaultValue != null) { updateOptions(node, !!multiple, defaultValue, true); } else { // Revert the select back to its default unselected state. updateOptions(node, !!multiple, multiple ? [] : '', false); } } } export function restoreControlledSelectState(element: Element, props: Object) { const node: HTMLSelectElement = (element: any); const value = props.value; if (value != null) { updateOptions(node, !!props.multiple, value, false); } }
29.336842
91
0.643415
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 {ThrownError, TimelineData} from '../types'; import type { Interaction, MouseMoveInteraction, Rect, Size, ViewRefs, } from '../view-base'; import { positioningScaleFactor, timestampToPosition, positionToTimestamp, widthToDuration, } from './utils/positioning'; import { View, Surface, rectContainsPoint, rectIntersectsRect, intersectionOfRects, } from '../view-base'; import { COLORS, TOP_ROW_PADDING, REACT_EVENT_DIAMETER, BORDER_SIZE, } from './constants'; const EVENT_ROW_HEIGHT_FIXED = TOP_ROW_PADDING + REACT_EVENT_DIAMETER + TOP_ROW_PADDING; export class ThrownErrorsView extends View { _profilerData: TimelineData; _intrinsicSize: Size; _hoveredEvent: ThrownError | null = null; onHover: ((event: ThrownError | null) => void) | null = null; constructor(surface: Surface, frame: Rect, profilerData: TimelineData) { super(surface, frame); this._profilerData = profilerData; this._intrinsicSize = { width: this._profilerData.duration, height: EVENT_ROW_HEIGHT_FIXED, }; } desiredSize(): Size { return this._intrinsicSize; } setHoveredEvent(hoveredEvent: ThrownError | null) { if (this._hoveredEvent === hoveredEvent) { return; } this._hoveredEvent = hoveredEvent; this.setNeedsDisplay(); } /** * Draw a single `ThrownError` as a circle in the canvas. */ _drawSingleThrownError( context: CanvasRenderingContext2D, rect: Rect, thrownError: ThrownError, baseY: number, scaleFactor: number, showHoverHighlight: boolean, ) { const {frame} = this; const {timestamp} = thrownError; const x = timestampToPosition(timestamp, scaleFactor, frame); const radius = REACT_EVENT_DIAMETER / 2; const eventRect: Rect = { origin: { x: x - radius, y: baseY, }, size: {width: REACT_EVENT_DIAMETER, height: REACT_EVENT_DIAMETER}, }; if (!rectIntersectsRect(eventRect, rect)) { return; // Not in view } const fillStyle = showHoverHighlight ? COLORS.REACT_THROWN_ERROR_HOVER : COLORS.REACT_THROWN_ERROR; const y = eventRect.origin.y + radius; context.beginPath(); context.fillStyle = fillStyle; context.arc(x, y, radius, 0, 2 * Math.PI); context.fill(); } draw(context: CanvasRenderingContext2D) { const { frame, _profilerData: {thrownErrors}, _hoveredEvent, visibleArea, } = this; context.fillStyle = COLORS.BACKGROUND; context.fillRect( visibleArea.origin.x, visibleArea.origin.y, visibleArea.size.width, visibleArea.size.height, ); // Draw events const baseY = frame.origin.y + TOP_ROW_PADDING; const scaleFactor = positioningScaleFactor( this._intrinsicSize.width, frame, ); const highlightedEvents: ThrownError[] = []; thrownErrors.forEach(thrownError => { if (thrownError === _hoveredEvent) { highlightedEvents.push(thrownError); return; } this._drawSingleThrownError( context, visibleArea, thrownError, baseY, scaleFactor, false, ); }); // Draw the highlighted items on top so they stand out. // This is helpful if there are multiple (overlapping) items close to each other. highlightedEvents.forEach(thrownError => { this._drawSingleThrownError( context, visibleArea, thrownError, baseY, scaleFactor, true, ); }); // Render bottom borders. // Propose border rect, check if intersects with `rect`, draw intersection. const borderFrame: Rect = { origin: { x: frame.origin.x, y: frame.origin.y + EVENT_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.REACT_WORK_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 { _profilerData: {thrownErrors}, } = this; const scaleFactor = positioningScaleFactor( this._intrinsicSize.width, frame, ); const hoverTimestamp = positionToTimestamp(location.x, scaleFactor, frame); const eventTimestampAllowance = widthToDuration( REACT_EVENT_DIAMETER / 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 = thrownErrors.length - 1; index >= 0; index--) { const event = thrownErrors[index]; const {timestamp} = event; if ( timestamp - eventTimestampAllowance <= hoverTimestamp && hoverTimestamp <= timestamp + eventTimestampAllowance ) { this.currentCursor = 'context-menu'; viewRefs.hoveredView = this; onHover(event); return; } } onHover(null); } handleInteraction(interaction: Interaction, viewRefs: ViewRefs) { switch (interaction.type) { case 'mousemove': this._handleMouseMove(interaction, viewRefs); break; } } }
23.863636
85
0.635805
owtf
// Compile this with Babel. // babel --config-file ./babel.config.json BabelClasses.js --out-file BabelClasses-compiled.js --source-maps class BabelClass extends React.Component { render() { return this.props.children; } } class BabelClassWithFields extends React.Component { // These compile to defineProperty which can break some interception techniques. props; state = {}; render() { return this.props.children; } }
23.666667
108
0.722348
owtf
import Fixture from '../../Fixture'; const React = window.React; class NumberInputExtraZeroes extends React.Component { state = {value: '3.0000'}; changeValue = () => { this.setState({ value: '3.0000', }); }; onChange = event => { this.setState({value: event.target.value}); }; render() { const {value} = this.state; return ( <Fixture> <div>{this.props.children}</div> <div className="control-box"> <input type="number" value={value} onChange={this.onChange} /> <button onClick={this.changeValue}>Reset to "3.0000"</button> </div> </Fixture> ); } } export default NumberInputExtraZeroes;
21.354839
72
0.586705
null
'use strict'; const {resolve} = require('path'); const {readFileSync} = require('fs'); const {signFile, getSigningToken} = require('signedsource'); const {bundleTypes, moduleTypes} = require('./bundles'); const { NODE_ES2015, ESM_DEV, ESM_PROD, UMD_DEV, UMD_PROD, UMD_PROFILING, NODE_DEV, NODE_PROD, NODE_PROFILING, BUN_DEV, BUN_PROD, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, BROWSER_SCRIPT, } = bundleTypes; const {RECONCILER} = moduleTypes; const USE_STRICT_HEADER_REGEX = /'use strict';\n+/; function registerInternalModuleStart(globalName) { const path = resolve(__dirname, 'wrappers', 'registerInternalModuleBegin.js'); const file = readFileSync(path); return String(file).trim(); } function registerInternalModuleStop(globalName) { const path = resolve(__dirname, 'wrappers', 'registerInternalModuleEnd.js'); const file = readFileSync(path); // Remove the 'use strict' directive from the footer. // This directive is only meaningful when it is the first statement in a file or function. return String(file).replace(USE_STRICT_HEADER_REGEX, '').trim(); } const license = ` * 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 topLevelDefinitionWrappers = { /***************** NODE_ES2015 *****************/ [NODE_ES2015](source, globalName, filename, moduleType) { return `'use strict'; ${source}`; }, /***************** ESM_DEV *****************/ [ESM_DEV](source, globalName, filename, moduleType) { return source; }, /***************** ESM_PROD *****************/ [ESM_PROD](source, globalName, filename, moduleType) { return source; }, /***************** BUN_DEV *****************/ [BUN_DEV](source, globalName, filename, moduleType) { return source; }, /***************** BUN_PROD *****************/ [BUN_PROD](source, globalName, filename, moduleType) { return source; }, /***************** UMD_DEV *****************/ [UMD_DEV](source, globalName, filename, moduleType) { return source; }, /***************** UMD_PROD *****************/ [UMD_PROD](source, globalName, filename, moduleType) { return `(function(){${source}})();`; }, /***************** UMD_PROFILING *****************/ [UMD_PROFILING](source, globalName, filename, moduleType) { return `(function(){${source}})();`; }, /***************** NODE_DEV *****************/ [NODE_DEV](source, globalName, filename, moduleType) { return `'use strict'; if (process.env.NODE_ENV !== "production") { (function() { ${source} })(); }`; }, /***************** NODE_PROD *****************/ [NODE_PROD](source, globalName, filename, moduleType) { return source; }, /***************** NODE_PROFILING *****************/ [NODE_PROFILING](source, globalName, filename, moduleType) { return source; }, /****************** FB_WWW_DEV ******************/ [FB_WWW_DEV](source, globalName, filename, moduleType) { return `'use strict'; if (__DEV__) { (function() { ${source} })(); }`; }, /****************** FB_WWW_PROD ******************/ [FB_WWW_PROD](source, globalName, filename, moduleType) { return source; }, /****************** FB_WWW_PROFILING ******************/ [FB_WWW_PROFILING](source, globalName, filename, moduleType) { return source; }, /****************** RN_OSS_DEV ******************/ [RN_OSS_DEV](source, globalName, filename, moduleType) { return `'use strict'; if (__DEV__) { (function() { ${source} })(); }`; }, /****************** RN_OSS_PROD ******************/ [RN_OSS_PROD](source, globalName, filename, moduleType) { return source; }, /****************** RN_OSS_PROFILING ******************/ [RN_OSS_PROFILING](source, globalName, filename, moduleType) { return source; }, /****************** RN_FB_DEV ******************/ [RN_FB_DEV](source, globalName, filename, moduleType) { return `'use strict'; if (__DEV__) { (function() { ${source} })(); }`; }, /****************** RN_FB_PROD ******************/ [RN_FB_PROD](source, globalName, filename, moduleType) { return source; }, /****************** RN_FB_PROFILING ******************/ [RN_FB_PROFILING](source, globalName, filename, moduleType) { return source; }, }; const reconcilerWrappers = { /***************** NODE_DEV (reconciler only) *****************/ [NODE_DEV](source, globalName, filename, moduleType) { return `'use strict'; if (process.env.NODE_ENV !== "production") { module.exports = function $$$reconciler($$$config) { var exports = {}; ${source} return exports; }; module.exports.default = module.exports; Object.defineProperty(module.exports, "__esModule", { value: true }); } `; }, /***************** NODE_PROD (reconciler only) *****************/ [NODE_PROD](source, globalName, filename, moduleType) { return `module.exports = function $$$reconciler($$$config) { var exports = {}; ${source} return exports; }; module.exports.default = module.exports; Object.defineProperty(module.exports, "__esModule", { value: true }); `; }, /***************** NODE_PROFILING (reconciler only) *****************/ [NODE_PROFILING](source, globalName, filename, moduleType) { return `module.exports = function $$$reconciler($$$config) { var exports = {}; ${source} return exports; }; module.exports.default = module.exports; Object.defineProperty(module.exports, "__esModule", { value: true }); `; }, }; const licenseHeaderWrappers = { /***************** NODE_ES2015 *****************/ [NODE_ES2015](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** ESM_DEV *****************/ [ESM_DEV](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** ESM_PROD *****************/ [ESM_PROD](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** BUN_DEV *****************/ [BUN_DEV](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** BUN_PROD *****************/ [BUN_PROD](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** UMD_DEV *****************/ [UMD_DEV](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** UMD_PROD *****************/ [UMD_PROD](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** UMD_PROFILING *****************/ [UMD_PROFILING](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** NODE_DEV *****************/ [NODE_DEV](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** NODE_PROD *****************/ [NODE_PROD](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /***************** NODE_PROFILING *****************/ [NODE_PROFILING](source, globalName, filename, moduleType) { return `/** * @license React * ${filename} * ${license} */ ${source}`; }, /****************** FB_WWW_DEV ******************/ [FB_WWW_DEV](source, globalName, filename, moduleType) { return `/** ${license} * * @noflow * @nolint * @preventMunge * @preserve-invariant-messages */ ${source}`; }, /****************** FB_WWW_PROD ******************/ [FB_WWW_PROD](source, globalName, filename, moduleType) { return `/** ${license} * * @noflow * @nolint * @preventMunge * @preserve-invariant-messages */ ${source}`; }, /****************** FB_WWW_PROFILING ******************/ [FB_WWW_PROFILING](source, globalName, filename, moduleType) { return `/** ${license} * * @noflow * @nolint * @preventMunge * @preserve-invariant-messages */ ${source}`; }, /****************** RN_OSS_DEV ******************/ [RN_OSS_DEV](source, globalName, filename, moduleType) { return signFile(`/** ${license} * * @noflow * @nolint * @providesModule ${globalName}-dev * @preventMunge * ${getSigningToken()} */ ${source}`); }, /****************** RN_OSS_PROD ******************/ [RN_OSS_PROD](source, globalName, filename, moduleType) { return signFile(`/** ${license} * * @noflow * @nolint * @providesModule ${globalName}-prod * @preventMunge * ${getSigningToken()} */ ${source}`); }, /****************** RN_OSS_PROFILING ******************/ [RN_OSS_PROFILING](source, globalName, filename, moduleType) { return signFile(`/** ${license} * * @noflow * @nolint * @providesModule ${globalName}-profiling * @preventMunge * ${getSigningToken()} */ ${source}`); }, /****************** RN_FB_DEV ******************/ [RN_FB_DEV](source, globalName, filename, moduleType) { return signFile(`/** ${license} * * @noflow * @nolint * @preventMunge * ${getSigningToken()} */ ${source}`); }, /****************** RN_FB_PROD ******************/ [RN_FB_PROD](source, globalName, filename, moduleType) { return signFile(`/** ${license} * * @noflow * @nolint * @preventMunge * ${getSigningToken()} */ ${source}`); }, /****************** RN_FB_PROFILING ******************/ [RN_FB_PROFILING](source, globalName, filename, moduleType) { return signFile(`/** ${license} * * @noflow * @nolint * @preventMunge * ${getSigningToken()} */ ${source}`); }, }; function wrapWithTopLevelDefinitions( source, bundleType, globalName, filename, moduleType, wrapWithModuleBoundaries ) { if (wrapWithModuleBoundaries) { switch (bundleType) { case NODE_DEV: case NODE_PROFILING: case FB_WWW_DEV: case FB_WWW_PROFILING: case RN_OSS_DEV: case RN_OSS_PROFILING: case RN_FB_DEV: case RN_FB_PROFILING: // Remove the 'use strict' directive from source. // The module start wrapper will add its own. // This directive is only meaningful when it is the first statement in a file or function. source = source.replace(USE_STRICT_HEADER_REGEX, ''); // Certain DEV and Profiling bundles should self-register their own module boundaries with DevTools. // This allows the Timeline to de-emphasize (dim) internal stack frames. source = ` ${registerInternalModuleStart(globalName)} ${source} ${registerInternalModuleStop(globalName)} `; break; } } if (bundleType === BROWSER_SCRIPT) { // Bundles of type BROWSER_SCRIPT get sent straight to the browser without // additional processing. So we should exclude any extra wrapper comments. return source; } if (moduleType === RECONCILER) { // Standalone reconciler is only used by third-party renderers. // It is handled separately. const wrapper = reconcilerWrappers[bundleType]; if (typeof wrapper !== 'function') { throw new Error( `Unsupported build type for the reconciler package: ${bundleType}.` ); } return wrapper(source, globalName, filename, moduleType); } // All the other packages. const wrapper = topLevelDefinitionWrappers[bundleType]; if (typeof wrapper !== 'function') { throw new Error(`Unsupported build type: ${bundleType}.`); } return wrapper(source, globalName, filename, moduleType); } function wrapWithLicenseHeader( source, bundleType, globalName, filename, moduleType ) { if (bundleType === BROWSER_SCRIPT) { // Bundles of type BROWSER_SCRIPT get sent straight to the browser without // additional processing. So we should exclude any extra wrapper comments. return source; } // All the other packages. const wrapper = licenseHeaderWrappers[bundleType]; if (typeof wrapper !== 'function') { throw new Error(`Unsupported build type: ${bundleType}.`); } return wrapper(source, globalName, filename, moduleType); } module.exports = { wrapWithTopLevelDefinitions, wrapWithLicenseHeader, };
21.098616
108
0.555512
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 {Dispatcher} from 'react-reconciler/src/ReactInternalTypes'; import type {Awaited} from 'shared/ReactTypes'; import {enableAsyncActions, enableFormActions} from 'shared/ReactFeatureFlags'; import ReactSharedInternals from 'shared/ReactSharedInternals'; const ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; type FormStatusNotPending = {| pending: false, data: null, method: null, action: null, |}; type FormStatusPending = {| pending: true, data: FormData, method: string, action: string | (FormData => void | Promise<void>), |}; export type FormStatus = FormStatusPending | FormStatusNotPending; // Since the "not pending" value is always the same, we can reuse the // same object across all transitions. const sharedNotPendingObject = { pending: false, data: null, method: null, action: null, }; export const NotPending: FormStatus = __DEV__ ? Object.freeze(sharedNotPendingObject) : sharedNotPendingObject; function resolveDispatcher() { // Copied from react/src/ReactHooks.js. It's the same thing but in a // different package. const dispatcher = ReactCurrentDispatcher.current; if (__DEV__) { if (dispatcher === null) { console.error( '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.', ); } } // Will result in a null access error if accessed outside render phase. We // intentionally don't throw our own error because this is in a hot path. // Also helps ensure this is inlined. return ((dispatcher: any): Dispatcher); } export function useFormStatus(): FormStatus { if (!(enableFormActions && enableAsyncActions)) { throw new Error('Not implemented.'); } else { const dispatcher = resolveDispatcher(); // $FlowFixMe[not-a-function] We know this exists because of the feature check above. return dispatcher.useHostTransitionStatus(); } } export function useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { if (!(enableFormActions && enableAsyncActions)) { throw new Error('Not implemented.'); } else { const dispatcher = resolveDispatcher(); // $FlowFixMe[not-a-function] This is unstable, thus optional return dispatcher.useFormState(action, initialState, permalink); } }
31.456522
121
0.702178
owtf
/** * Babel works across all browsers, however it requires many polyfills. */ import 'core-js/es6/weak-map'; import 'core-js/es6/weak-set'; import 'core-js/es6/number'; import 'core-js/es6/string'; import 'core-js/es6/array'; import 'core-js/modules/es6.object.set-prototype-of'; import {transform} from '@babel/standalone'; const presets = ['es2015', 'stage-3', 'react']; export function compile(raw) { return transform(raw, {presets}).code; }
22.894737
71
0.708609
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 */ 'use strict'; throw new Error('Use react-server-dom-esm/client instead.');
20.615385
66
0.696429
Mastering-Machine-Learning-for-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {copy} from 'clipboard-js'; import * as React from 'react'; import {Fragment, useCallback, useContext} from 'react'; import {TreeDispatcherContext} from './TreeContext'; import {BridgeContext, ContextMenuContext, StoreContext} from '../context'; import ContextMenu from '../../ContextMenu/ContextMenu'; import ContextMenuItem from '../../ContextMenu/ContextMenuItem'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import Icon from '../Icon'; import InspectedElementBadges from './InspectedElementBadges'; import InspectedElementContextTree from './InspectedElementContextTree'; import InspectedElementErrorsAndWarningsTree from './InspectedElementErrorsAndWarningsTree'; import InspectedElementHooksTree from './InspectedElementHooksTree'; import InspectedElementPropsTree from './InspectedElementPropsTree'; import InspectedElementStateTree from './InspectedElementStateTree'; import InspectedElementStyleXPlugin from './InspectedElementStyleXPlugin'; import InspectedElementSuspenseToggle from './InspectedElementSuspenseToggle'; import NativeStyleEditor from './NativeStyleEditor'; import ElementBadges from './ElementBadges'; import {useHighlightNativeElement} from '../hooks'; import { copyInspectedElementPath as copyInspectedElementPathAPI, storeAsGlobal as storeAsGlobalAPI, } from 'react-devtools-shared/src/backendAPI'; import {enableStyleXFeatures} from 'react-devtools-feature-flags'; import {logEvent} from 'react-devtools-shared/src/Logger'; import styles from './InspectedElementView.css'; import type {ContextMenuContextType} from '../context'; import type { Element, InspectedElement, } from 'react-devtools-shared/src/frontend/types'; import type {HookNames} from 'react-devtools-shared/src/frontend/types'; import type {ToggleParseHookNames} from './InspectedElementContext'; export type CopyPath = (path: Array<string | number>) => void; export type InspectPath = (path: Array<string | number>) => void; type Props = { element: Element, hookNames: HookNames | null, inspectedElement: InspectedElement, parseHookNames: boolean, toggleParseHookNames: ToggleParseHookNames, }; export default function InspectedElementView({ element, hookNames, inspectedElement, parseHookNames, toggleParseHookNames, }: Props): React.Node { const {id} = element; const {owners, rendererPackageName, rendererVersion, rootType, source} = inspectedElement; const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const { isEnabledForInspectedElement: isContextMenuEnabledForInspectedElement, viewAttributeSourceFunction, } = useContext<ContextMenuContextType>(ContextMenuContext); const rendererLabel = rendererPackageName !== null && rendererVersion !== null ? `${rendererPackageName}@${rendererVersion}` : null; const showOwnersList = owners !== null && owners.length > 0; const showRenderedBy = showOwnersList || rendererLabel !== null || rootType !== null; return ( <Fragment> <div className={styles.InspectedElement}> <InspectedElementBadges element={element} /> <InspectedElementPropsTree bridge={bridge} element={element} inspectedElement={inspectedElement} store={store} /> <InspectedElementSuspenseToggle bridge={bridge} inspectedElement={inspectedElement} store={store} /> <InspectedElementStateTree bridge={bridge} element={element} inspectedElement={inspectedElement} store={store} /> <InspectedElementHooksTree bridge={bridge} element={element} hookNames={hookNames} inspectedElement={inspectedElement} parseHookNames={parseHookNames} store={store} toggleParseHookNames={toggleParseHookNames} /> <InspectedElementContextTree bridge={bridge} element={element} inspectedElement={inspectedElement} store={store} /> {enableStyleXFeatures && ( <InspectedElementStyleXPlugin bridge={bridge} element={element} inspectedElement={inspectedElement} store={store} /> )} <InspectedElementErrorsAndWarningsTree bridge={bridge} element={element} inspectedElement={inspectedElement} store={store} /> <NativeStyleEditor /> {showRenderedBy && ( <div className={styles.Owners} data-testname="InspectedElementView-Owners"> <div className={styles.OwnersHeader}>rendered by</div> {showOwnersList && owners?.map(owner => ( <OwnerView key={owner.id} displayName={owner.displayName || 'Anonymous'} hocDisplayNames={owner.hocDisplayNames} compiledWithForget={owner.compiledWithForget} id={owner.id} isInStore={store.containsElement(owner.id)} type={owner.type} /> ))} {rootType !== null && ( <div className={styles.OwnersMetaField}>{rootType}</div> )} {rendererLabel !== null && ( <div className={styles.OwnersMetaField}>{rendererLabel}</div> )} </div> )} {source !== null && ( <Source fileName={source.fileName} lineNumber={source.lineNumber} /> )} </div> {isContextMenuEnabledForInspectedElement && ( <ContextMenu id="InspectedElement"> {({path, type: pathType}) => { const copyInspectedElementPath = () => { const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { copyInspectedElementPathAPI({ bridge, id, path, rendererID, }); } }; const storeAsGlobal = () => { const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { storeAsGlobalAPI({ bridge, id, path, rendererID, }); } }; return ( <Fragment> <ContextMenuItem onClick={copyInspectedElementPath} title="Copy value to clipboard"> <Icon className={styles.ContextMenuIcon} type="copy" /> Copy value to clipboard </ContextMenuItem> <ContextMenuItem onClick={storeAsGlobal} title="Store as global variable"> <Icon className={styles.ContextMenuIcon} type="store-as-global-variable" />{' '} Store as global variable </ContextMenuItem> {viewAttributeSourceFunction !== null && pathType === 'function' && ( <ContextMenuItem onClick={() => viewAttributeSourceFunction(id, path)} title="Go to definition"> <Icon className={styles.ContextMenuIcon} type="code" /> Go to definition </ContextMenuItem> )} </Fragment> ); }} </ContextMenu> )} </Fragment> ); } // This function is based on describeComponentFrame() in packages/shared/ReactComponentStackFrame function formatSourceForDisplay(fileName: string, lineNumber: string) { const BEFORE_SLASH_RE = /^(.*)[\\\/]/; let nameOnly = fileName.replace(BEFORE_SLASH_RE, ''); // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(nameOnly)) { const match = fileName.match(BEFORE_SLASH_RE); if (match) { const pathBeforeSlash = match[1]; if (pathBeforeSlash) { const folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); nameOnly = folderName + '/' + nameOnly; } } } return `${nameOnly}:${lineNumber}`; } type SourceProps = { fileName: string, lineNumber: string, }; function Source({fileName, lineNumber}: SourceProps) { const handleCopy = () => copy(`${fileName}:${lineNumber}`); return ( <div className={styles.Source} data-testname="InspectedElementView-Source"> <div className={styles.SourceHeaderRow}> <div className={styles.SourceHeader}>source</div> <Button onClick={handleCopy} title="Copy to clipboard"> <ButtonIcon type="copy" /> </Button> </div> <div className={styles.SourceOneLiner}> {formatSourceForDisplay(fileName, lineNumber)} </div> </div> ); } type OwnerViewProps = { displayName: string, hocDisplayNames: Array<string> | null, compiledWithForget: boolean, id: number, isInStore: boolean, }; function OwnerView({ displayName, hocDisplayNames, compiledWithForget, id, isInStore, }: OwnerViewProps) { const dispatch = useContext(TreeDispatcherContext); const {highlightNativeElement, clearHighlightNativeElement} = useHighlightNativeElement(); const handleClick = useCallback(() => { logEvent({ event_name: 'select-element', metadata: {source: 'owner-view'}, }); dispatch({ type: 'SELECT_ELEMENT_BY_ID', payload: id, }); }, [dispatch, id]); return ( <Button key={id} className={styles.OwnerButton} disabled={!isInStore} onClick={handleClick} onMouseEnter={() => highlightNativeElement(id)} onMouseLeave={clearHighlightNativeElement}> <span className={styles.OwnerContent}> <span className={`${styles.Owner} ${isInStore ? '' : styles.NotInStore}`} title={displayName}> {displayName} </span> <ElementBadges hocDisplayNames={hocDisplayNames} compiledWithForget={compiledWithForget} /> </span> </Button> ); }
30.343195
97
0.60927
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 { Thenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig'; export type SSRModuleMap = string; // Module root path export type ServerManifest = string; // Module root path export type ServerReferenceId = string; import {prepareDestinationForModuleImpl} from 'react-client/src/ReactFlightClientConfig'; export opaque type ClientReferenceMetadata = [ string, // module path string, // export name ]; // eslint-disable-next-line no-unused-vars export opaque type ClientReference<T> = { specifier: string, name: string, }; // The reason this function needs to defined here in this file instead of just // being exported directly from the WebpackDestination... file is because the // ClientReferenceMetadata is opaque and we can't unwrap it there. // This should get inlined and we could also just implement an unwrapping function // though that risks it getting used in places it shouldn't be. This is unfortunate // but currently it seems to be the best option we have. export function prepareDestinationForModule( moduleLoading: ModuleLoading, nonce: ?string, metadata: ClientReferenceMetadata, ) { prepareDestinationForModuleImpl(moduleLoading, metadata[0], nonce); } export function resolveClientReference<T>( bundlerConfig: SSRModuleMap, metadata: ClientReferenceMetadata, ): ClientReference<T> { const baseURL = bundlerConfig; return { specifier: baseURL + metadata[0], name: metadata[1], }; } export function resolveServerReference<T>( config: ServerManifest, id: ServerReferenceId, ): ClientReference<T> { const baseURL: string = config; const idx = id.lastIndexOf('#'); const exportName = id.slice(idx + 1); const fullURL = id.slice(0, idx); if (!fullURL.startsWith(baseURL)) { throw new Error( 'Attempted to load a Server Reference outside the hosted root.', ); } return {specifier: fullURL, name: exportName}; } const asyncModuleCache: Map<string, Thenable<any>> = new Map(); export function preloadModule<T>( metadata: ClientReference<T>, ): null | Thenable<any> { const existingPromise = asyncModuleCache.get(metadata.specifier); if (existingPromise) { if (existingPromise.status === 'fulfilled') { return null; } return existingPromise; } else { // $FlowFixMe[unsupported-syntax] const modulePromise: Thenable<T> = import(metadata.specifier); modulePromise.then( value => { const fulfilledThenable: FulfilledThenable<mixed> = (modulePromise: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; }, reason => { const rejectedThenable: RejectedThenable<mixed> = (modulePromise: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = reason; }, ); asyncModuleCache.set(metadata.specifier, modulePromise); return modulePromise; } } export function requireModule<T>(metadata: ClientReference<T>): T { let moduleExports; // We assume that preloadModule has been called before, which // should have added something to the module cache. const promise: any = asyncModuleCache.get(metadata.specifier); if (promise.status === 'fulfilled') { moduleExports = promise.value; } else { throw promise.reason; } return moduleExports[metadata.name]; }
29.057851
89
0.718647
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'; function emptyFunction() {} describe('ReactDOMTextarea', () => { let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; let renderTextarea; const ReactFeatureFlags = require('shared/ReactFeatureFlags'); beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); renderTextarea = function (component, container) { if (!container) { container = document.createElement('div'); } const node = ReactDOM.render(component, container); // Fixing jsdom's quirky behavior -- in reality, the parser should strip // off the leading newline but we need to do it by hand here. node.defaultValue = node.innerHTML.replace(/^\n/, ''); return node; }; }); afterEach(() => { jest.restoreAllMocks(); }); it('should allow setting `defaultValue`', () => { const container = document.createElement('div'); const node = renderTextarea(<textarea defaultValue="giraffe" />, container); expect(node.value).toBe('giraffe'); // Changing `defaultValue` should do nothing. renderTextarea(<textarea defaultValue="gorilla" />, container); expect(node.value).toEqual('giraffe'); node.value = 'cat'; renderTextarea(<textarea defaultValue="monkey" />, container); expect(node.value).toEqual('cat'); }); it('should display `defaultValue` of number 0', () => { const stub = <textarea defaultValue={0} />; const node = renderTextarea(stub); expect(node.value).toBe('0'); }); it('should display "false" for `defaultValue` of `false`', () => { const stub = <textarea defaultValue={false} />; const node = renderTextarea(stub); expect(node.value).toBe('false'); }); it('should display "foobar" for `defaultValue` of `objToString`', () => { const objToString = { toString: function () { return 'foobar'; }, }; const stub = <textarea defaultValue={objToString} />; const node = renderTextarea(stub); expect(node.value).toBe('foobar'); }); it('should set defaultValue', () => { const container = document.createElement('div'); ReactDOM.render(<textarea defaultValue="foo" />, container); ReactDOM.render(<textarea defaultValue="bar" />, container); ReactDOM.render(<textarea defaultValue="noise" />, container); expect(container.firstChild.defaultValue).toBe('noise'); }); it('should not render value as an attribute', () => { const stub = <textarea value="giraffe" onChange={emptyFunction} />; const node = renderTextarea(stub); expect(node.getAttribute('value')).toBe(null); }); it('should display `value` of number 0', () => { const stub = <textarea value={0} onChange={emptyFunction} />; const node = renderTextarea(stub); expect(node.value).toBe('0'); }); it('should update defaultValue to empty string', () => { const container = document.createElement('div'); ReactDOM.render(<textarea defaultValue={'foo'} />, container); ReactDOM.render(<textarea defaultValue={''} />, container); expect(container.firstChild.defaultValue).toBe(''); }); it('should allow setting `value` to `giraffe`', () => { const container = document.createElement('div'); let stub = <textarea value="giraffe" onChange={emptyFunction} />; const node = renderTextarea(stub, container); expect(node.value).toBe('giraffe'); stub = ReactDOM.render( <textarea value="gorilla" onChange={emptyFunction} />, container, ); expect(node.value).toEqual('gorilla'); }); it('will not initially assign an empty value (covers case where firefox throws a validation error when required attribute is set)', () => { const container = document.createElement('div'); let counter = 0; const originalCreateElement = document.createElement; spyOnDevAndProd(document, 'createElement').mockImplementation( function (type) { const el = originalCreateElement.apply(this, arguments); let value = ''; if (type === 'textarea') { Object.defineProperty(el, 'value', { get: function () { return value; }, set: function (val) { value = String(val); counter++; }, }); } return el; }, ); ReactDOM.render(<textarea value="" readOnly={true} />, container); expect(counter).toEqual(0); }); it('should render defaultValue for SSR', () => { const markup = ReactDOMServer.renderToString(<textarea defaultValue="1" />); const div = document.createElement('div'); div.innerHTML = markup; expect(div.firstChild.innerHTML).toBe('1'); expect(div.firstChild.getAttribute('defaultValue')).toBe(null); }); it('should render value for SSR', () => { const element = <textarea value="1" onChange={function () {}} />; const markup = ReactDOMServer.renderToString(element); const div = document.createElement('div'); div.innerHTML = markup; expect(div.firstChild.innerHTML).toBe('1'); expect(div.firstChild.getAttribute('defaultValue')).toBe(null); }); it('should allow setting `value` to `true`', () => { const container = document.createElement('div'); let stub = <textarea value="giraffe" onChange={emptyFunction} />; const node = renderTextarea(stub, container); expect(node.value).toBe('giraffe'); stub = ReactDOM.render( <textarea value={true} onChange={emptyFunction} />, container, ); expect(node.value).toEqual('true'); }); it('should allow setting `value` to `false`', () => { const container = document.createElement('div'); let stub = <textarea value="giraffe" onChange={emptyFunction} />; const node = renderTextarea(stub, container); expect(node.value).toBe('giraffe'); stub = ReactDOM.render( <textarea value={false} onChange={emptyFunction} />, container, ); expect(node.value).toEqual('false'); }); it('should allow setting `value` to `objToString`', () => { const container = document.createElement('div'); let stub = <textarea value="giraffe" onChange={emptyFunction} />; const node = renderTextarea(stub, container); expect(node.value).toBe('giraffe'); const objToString = { toString: function () { return 'foo'; }, }; stub = ReactDOM.render( <textarea value={objToString} onChange={emptyFunction} />, container, ); expect(node.value).toEqual('foo'); }); it('should throw when value is set to a Temporal-like object', () => { 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'; } } const container = document.createElement('div'); const stub = <textarea value="giraffe" onChange={emptyFunction} />; const node = renderTextarea(stub, container); expect(node.value).toBe('giraffe'); const test = () => ReactDOM.render( <textarea value={new TemporalLike()} onChange={emptyFunction} />, container, ); expect(() => expect(test).toThrowError(new TypeError('prod message')), ).toErrorDev( 'Form field values (value, checked, defaultValue, or defaultChecked props) must be ' + 'strings, not TemporalLike. This value must be coerced to a string before using it here.', ); }); it('should take updates to `defaultValue` for uncontrolled textarea', () => { const container = document.createElement('div'); const node = ReactDOM.render(<textarea defaultValue="0" />, container); expect(node.value).toBe('0'); ReactDOM.render(<textarea defaultValue="1" />, container); expect(node.value).toBe('0'); }); it('should take updates to children in lieu of `defaultValue` for uncontrolled textarea', () => { const container = document.createElement('div'); const node = ReactDOM.render(<textarea defaultValue="0" />, container); expect(node.value).toBe('0'); ReactDOM.render(<textarea>1</textarea>, container); expect(node.value).toBe('0'); }); it('should not incur unnecessary DOM mutations', () => { const container = document.createElement('div'); ReactDOM.render(<textarea value="a" onChange={emptyFunction} />, container); const node = container.firstChild; let nodeValue = 'a'; const nodeValueSetter = jest.fn(); Object.defineProperty(node, 'value', { get: function () { return nodeValue; }, set: nodeValueSetter.mockImplementation(function (newValue) { nodeValue = newValue; }), }); ReactDOM.render(<textarea value="a" onChange={emptyFunction} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(0); ReactDOM.render(<textarea value="b" onChange={emptyFunction} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); }); it('should properly control a value of number `0`', () => { const stub = <textarea value={0} onChange={emptyFunction} />; const setUntrackedValue = Object.getOwnPropertyDescriptor( HTMLTextAreaElement.prototype, 'value', ).set; const container = document.createElement('div'); document.body.appendChild(container); try { const node = renderTextarea(stub, container); setUntrackedValue.call(node, 'giraffe'); node.dispatchEvent( new Event('input', {bubbles: true, cancelable: false}), ); expect(node.value).toBe('0'); } finally { document.body.removeChild(container); } }); if (ReactFeatureFlags.disableTextareaChildren) { it('should ignore children content', () => { const container = document.createElement('div'); let stub = <textarea>giraffe</textarea>; let node; expect(() => { node = renderTextarea(stub, container); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe(''); // Changing children should do nothing, it functions like `defaultValue`. stub = ReactDOM.render(<textarea>gorilla</textarea>, container); expect(node.value).toEqual(''); }); } if (ReactFeatureFlags.disableTextareaChildren) { it('should receive defaultValue and still ignore children content', () => { let node; expect(() => { node = renderTextarea( <textarea defaultValue="dragon">monkey</textarea>, ); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe('dragon'); }); } if (!ReactFeatureFlags.disableTextareaChildren) { it('should treat children like `defaultValue`', () => { const container = document.createElement('div'); let stub = <textarea>giraffe</textarea>; let node; expect(() => { node = renderTextarea(stub, container); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe('giraffe'); // Changing children should do nothing, it functions like `defaultValue`. stub = ReactDOM.render(<textarea>gorilla</textarea>, container); expect(node.value).toEqual('giraffe'); }); } it('should keep value when switching to uncontrolled element if not changed', () => { const container = document.createElement('div'); const node = renderTextarea( <textarea value="kitten" onChange={emptyFunction} />, container, ); expect(node.value).toBe('kitten'); ReactDOM.render(<textarea defaultValue="gorilla" />, container); expect(node.value).toEqual('kitten'); }); it('should keep value when switching to uncontrolled element if changed', () => { const container = document.createElement('div'); const node = renderTextarea( <textarea value="kitten" onChange={emptyFunction} />, container, ); expect(node.value).toBe('kitten'); ReactDOM.render( <textarea value="puppies" onChange={emptyFunction} />, container, ); expect(node.value).toBe('puppies'); ReactDOM.render(<textarea defaultValue="gorilla" />, container); expect(node.value).toEqual('puppies'); }); if (ReactFeatureFlags.disableTextareaChildren) { it('should ignore numbers as children', () => { let node; expect(() => { node = renderTextarea(<textarea>{17}</textarea>); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe(''); }); } if (!ReactFeatureFlags.disableTextareaChildren) { it('should allow numbers as children', () => { let node; expect(() => { node = renderTextarea(<textarea>{17}</textarea>); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe('17'); }); } if (ReactFeatureFlags.disableTextareaChildren) { it('should ignore booleans as children', () => { let node; expect(() => { node = renderTextarea(<textarea>{false}</textarea>); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe(''); }); } if (!ReactFeatureFlags.disableTextareaChildren) { it('should allow booleans as children', () => { let node; expect(() => { node = renderTextarea(<textarea>{false}</textarea>); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe('false'); }); } if (ReactFeatureFlags.disableTextareaChildren) { it('should ignore objects as children', () => { const obj = { toString: function () { return 'sharkswithlasers'; }, }; let node; expect(() => { node = renderTextarea(<textarea>{obj}</textarea>); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe(''); }); } if (!ReactFeatureFlags.disableTextareaChildren) { it('should allow objects as children', () => { const obj = { toString: function () { return 'sharkswithlasers'; }, }; let node; expect(() => { node = renderTextarea(<textarea>{obj}</textarea>); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe('sharkswithlasers'); }); } if (!ReactFeatureFlags.disableTextareaChildren) { it('should throw with multiple or invalid children', () => { expect(() => { expect(() => ReactTestUtils.renderIntoDocument( <textarea> {'hello'} {'there'} </textarea>, ), ).toThrow('<textarea> can only have at most one child'); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); let node; expect(() => { expect( () => (node = renderTextarea( <textarea> <strong /> </textarea>, )), ).not.toThrow(); }).toErrorDev( 'Use the `defaultValue` or `value` props instead of setting children on <textarea>.', ); expect(node.value).toBe('[object Object]'); }); } it('should unmount', () => { const container = document.createElement('div'); renderTextarea(<textarea />, container); ReactDOM.unmountComponentAtNode(container); }); it('should warn if value is null', () => { expect(() => ReactTestUtils.renderIntoDocument(<textarea value={null} />), ).toErrorDev( '`value` prop on `textarea` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', ); // No additional warnings are expected ReactTestUtils.renderIntoDocument(<textarea value={null} />); }); it('should warn if value and defaultValue are specified', () => { const InvalidComponent = () => ( <textarea value="foo" defaultValue="bar" readOnly={true} /> ); expect(() => ReactTestUtils.renderIntoDocument(<InvalidComponent />), ).toErrorDev( 'InvalidComponent contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', ); // No additional warnings are expected ReactTestUtils.renderIntoDocument(<InvalidComponent />); }); it('should not warn about missing onChange in uncontrolled textareas', () => { const container = document.createElement('div'); ReactDOM.render(<textarea />, container); ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<textarea value={undefined} />, container); }); it('does not set textContent if value is unchanged', () => { const container = document.createElement('div'); let node; let instance; // Setting defaultValue on a textarea is equivalent to setting textContent, // and is the method we currently use, so we can observe if defaultValue is // is set to determine if textContent is being recreated. // https://html.spec.whatwg.org/#the-textarea-element let defaultValue; const set = jest.fn(value => { defaultValue = value; }); const get = jest.fn(value => { return defaultValue; }); class App extends React.Component { state = {count: 0, text: 'foo'}; componentDidMount() { instance = this; } render() { return ( <div> <span>{this.state.count}</span> <textarea ref={n => (node = n)} value="foo" onChange={emptyFunction} data-count={this.state.count} /> </div> ); } } ReactDOM.render(<App />, container); defaultValue = node.defaultValue; Object.defineProperty(node, 'defaultValue', {get, set}); instance.setState({count: 1}); expect(set.mock.calls.length).toBe(0); }); describe('When given a Symbol value', () => { it('treats initial Symbol value as an empty string', () => { const container = document.createElement('div'); expect(() => ReactDOM.render( <textarea value={Symbol('foobar')} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); }); it('treats initial Symbol children as an empty string', () => { const container = document.createElement('div'); expect(() => ReactDOM.render( <textarea onChange={() => {}}>{Symbol('foo')}</textarea>, container, ), ).toErrorDev('Use the `defaultValue` or `value` props'); const node = container.firstChild; expect(node.value).toBe(''); }); it('treats updated Symbol value as an empty string', () => { const container = document.createElement('div'); ReactDOM.render(<textarea value="foo" onChange={() => {}} />, container); expect(() => ReactDOM.render( <textarea value={Symbol('foo')} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); }); it('treats initial Symbol defaultValue as an empty string', () => { const container = document.createElement('div'); ReactDOM.render(<textarea defaultValue={Symbol('foobar')} />, container); const node = container.firstChild; // TODO: defaultValue is a reserved prop and is not validated. Check warnings when they are. expect(node.value).toBe(''); }); it('treats updated Symbol defaultValue as an empty string', () => { const container = document.createElement('div'); ReactDOM.render(<textarea defaultValue="foo" />, container); ReactDOM.render(<textarea defaultValue={Symbol('foobar')} />, container); const node = container.firstChild; // TODO: defaultValue is a reserved prop and is not validated. Check warnings when they are. expect(node.value).toBe('foo'); }); }); describe('When given a function value', () => { it('treats initial function value as an empty string', () => { const container = document.createElement('div'); expect(() => ReactDOM.render( <textarea value={() => {}} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); }); it('treats initial function children as an empty string', () => { const container = document.createElement('div'); expect(() => ReactDOM.render( <textarea onChange={() => {}}>{() => {}}</textarea>, container, ), ).toErrorDev('Use the `defaultValue` or `value` props'); const node = container.firstChild; expect(node.value).toBe(''); }); it('treats updated function value as an empty string', () => { const container = document.createElement('div'); ReactDOM.render(<textarea value="foo" onChange={() => {}} />, container); expect(() => ReactDOM.render( <textarea value={() => {}} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); }); it('treats initial function defaultValue as an empty string', () => { const container = document.createElement('div'); ReactDOM.render(<textarea defaultValue={() => {}} />, container); const node = container.firstChild; // TODO: defaultValue is a reserved prop and is not validated. Check warnings when they are. expect(node.value).toBe(''); }); it('treats updated function defaultValue as an empty string', () => { const container = document.createElement('div'); ReactDOM.render(<textarea defaultValue="foo" />, container); ReactDOM.render(<textarea defaultValue={() => {}} />, container); const node = container.firstChild; // TODO: defaultValue is a reserved prop and is not validated. Check warnings when they are. expect(node.value).toBe('foo'); }); }); it('should remove previous `defaultValue`', () => { const container = document.createElement('div'); const node = ReactDOM.render(<textarea defaultValue="0" />, container); expect(node.value).toBe('0'); expect(node.defaultValue).toBe('0'); ReactDOM.render(<textarea />, container); expect(node.defaultValue).toBe(''); }); it('should treat `defaultValue={null}` as missing', () => { const container = document.createElement('div'); const node = ReactDOM.render(<textarea defaultValue="0" />, container); expect(node.value).toBe('0'); expect(node.defaultValue).toBe('0'); ReactDOM.render(<textarea defaultValue={null} />, container); expect(node.defaultValue).toBe(''); }); it('should not warn about missing onChange if value is not set', () => { expect(() => { ReactTestUtils.renderIntoDocument(<textarea />); }).not.toThrow(); }); it('should not warn about missing onChange if value is undefined', () => { expect(() => { ReactTestUtils.renderIntoDocument(<textarea value={undefined} />); }).not.toThrow(); }); it('should not warn about missing onChange if onChange is set', () => { expect(() => { const change = jest.fn(); ReactTestUtils.renderIntoDocument( <textarea value="something" onChange={change} />, ); }).not.toThrow(); }); it('should not warn about missing onChange if disabled is true', () => { expect(() => { ReactTestUtils.renderIntoDocument( <textarea value="something" disabled={true} />, ); }).not.toThrow(); }); it('should not warn about missing onChange if value is not set', () => { expect(() => { ReactTestUtils.renderIntoDocument( <textarea value="something" readOnly={true} />, ); }).not.toThrow(); }); it('should warn about missing onChange if value is false', () => { expect(() => ReactTestUtils.renderIntoDocument(<textarea value={false} />), ).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); it('should warn about missing onChange if value is 0', () => { expect(() => ReactTestUtils.renderIntoDocument(<textarea value={0} />), ).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); it('should warn about missing onChange if value is "0"', () => { expect(() => ReactTestUtils.renderIntoDocument(<textarea value="0" />), ).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); it('should warn about missing onChange if value is ""', () => { expect(() => ReactTestUtils.renderIntoDocument(<textarea value="" />), ).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); });
31.425355
141
0.612658
owtf
'use strict'; // This is mostly copypasta from toWarnDev.js matchers // that we use in the main repo Jest configuration. const expect = global.expect; const {diff: jestDiff} = require('jest-diff'); const util = require('util'); function shouldIgnoreConsoleError(format, args) { if (process.env.NODE_ENV !== 'production') { if (typeof format === 'string') { if (format.indexOf('Error: Uncaught [') === 0) { // This looks like an uncaught error from invokeGuardedCallback() wrapper // in development that is reported by jsdom. Ignore because it's noisy. return true; } if (format.indexOf('The above error occurred') === 0) { // This looks like an error addendum from ReactFiberErrorLogger. // Ignore it too. return true; } } } else { if ( format != null && typeof format.message === 'string' && typeof format.stack === 'string' && args.length === 0 ) { // In production, ReactFiberErrorLogger logs error objects directly. // They are noisy too so we'll try to ignore them. return true; } } // Looks legit return false; } function normalizeCodeLocInfo(str) { if (typeof str !== 'string') { return str; } // This special case exists only for the special source location in // ReactElementValidator. That will go away if we remove source locations. str = str.replace(/Check your code at .+?:\d+/g, 'Check your code at **'); // V8 format: // at Component (/path/filename.js:123:45) // React format: // in Component (at filename.js:123) return str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) { return '\n in ' + name + ' (at **)'; }); } const createMatcherFor = (consoleMethod, matcherName) => function matcher(callback, expectedMessages, options = {}) { if (process.env.NODE_ENV !== 'production') { // Warn about incorrect usage of matcher. if (typeof expectedMessages === 'string') { expectedMessages = [expectedMessages]; } else if (!Array.isArray(expectedMessages)) { throw Error( `${matcherName}() requires a parameter of type string or an array of strings ` + `but was given ${typeof expectedMessages}.` ); } if ( options != null && (typeof options !== 'object' || Array.isArray(options)) ) { throw new Error( `${matcherName}() second argument, when present, should be an object. ` + 'Did you forget to wrap the messages into an array?' ); } if (arguments.length > 3) { // `matcher` comes from Jest, so it's more than 2 in practice throw new Error( `${matcherName}() received more than two arguments. ` + 'Did you forget to wrap the messages into an array?' ); } const withoutStack = options.withoutStack; const logAllErrors = options.logAllErrors; const warningsWithoutComponentStack = []; const warningsWithComponentStack = []; const unexpectedWarnings = []; let lastWarningWithMismatchingFormat = null; let lastWarningWithExtraComponentStack = null; // Catch errors thrown by the callback, // But only rethrow them if all test expectations have been satisfied. // Otherwise an Error in the callback can mask a failed expectation, // and result in a test that passes when it shouldn't. let caughtError; const isLikelyAComponentStack = message => typeof message === 'string' && (message.includes('\n in ') || message.includes('\n at ')); const consoleSpy = (format, ...args) => { // Ignore uncaught errors reported by jsdom // and React addendums because they're too noisy. if ( !logAllErrors && consoleMethod === 'error' && shouldIgnoreConsoleError(format, args) ) { return; } const message = util.format(format, ...args); const normalizedMessage = normalizeCodeLocInfo(message); // Remember if the number of %s interpolations // doesn't match the number of arguments. // We'll fail the test if it happens. let argIndex = 0; format.replace(/%s/g, () => argIndex++); if (argIndex !== args.length) { lastWarningWithMismatchingFormat = { format, args, expectedArgCount: argIndex, }; } // Protect against accidentally passing a component stack // to warning() which already injects the component stack. if ( args.length >= 2 && isLikelyAComponentStack(args[args.length - 1]) && isLikelyAComponentStack(args[args.length - 2]) ) { lastWarningWithExtraComponentStack = { format, }; } for (let index = 0; index < expectedMessages.length; index++) { const expectedMessage = expectedMessages[index]; if ( normalizedMessage === expectedMessage || normalizedMessage.includes(expectedMessage) ) { if (isLikelyAComponentStack(normalizedMessage)) { warningsWithComponentStack.push(normalizedMessage); } else { warningsWithoutComponentStack.push(normalizedMessage); } expectedMessages.splice(index, 1); return; } } let errorMessage; if (expectedMessages.length === 0) { errorMessage = 'Unexpected warning recorded: ' + this.utils.printReceived(normalizedMessage); } else if (expectedMessages.length === 1) { errorMessage = 'Unexpected warning recorded: ' + jestDiff(expectedMessages[0], normalizedMessage); } else { errorMessage = 'Unexpected warning recorded: ' + jestDiff(expectedMessages, [normalizedMessage]); } // Record the call stack for unexpected warnings. // We don't throw an Error here though, // Because it might be suppressed by ReactFiberScheduler. unexpectedWarnings.push(new Error(errorMessage)); }; // TODO Decide whether we need to support nested toWarn* expectations. // If we don't need it, add a check here to see if this is already our spy, // And throw an error. const originalMethod = console[consoleMethod]; // Avoid using Jest's built-in spy since it can't be removed. console[consoleMethod] = consoleSpy; try { callback(); } catch (error) { caughtError = error; } finally { // Restore the unspied method so that unexpected errors fail tests. console[consoleMethod] = originalMethod; // Any unexpected Errors thrown by the callback should fail the test. // This should take precedence since unexpected errors could block warnings. if (caughtError) { throw caughtError; } // Any unexpected warnings should be treated as a failure. if (unexpectedWarnings.length > 0) { return { message: () => unexpectedWarnings[0].stack, pass: false, }; } // Any remaining messages indicate a failed expectations. if (expectedMessages.length > 0) { return { message: () => `Expected warning was not recorded:\n ${this.utils.printReceived( expectedMessages[0] )}`, pass: false, }; } if (typeof withoutStack === 'number') { // We're expecting a particular number of warnings without stacks. if (withoutStack !== warningsWithoutComponentStack.length) { return { message: () => `Expected ${withoutStack} warnings without a component stack but received ${warningsWithoutComponentStack.length}:\n` + warningsWithoutComponentStack.map(warning => this.utils.printReceived(warning) ), pass: false, }; } } else if (withoutStack === true) { // We're expecting that all warnings won't have the stack. // If some warnings have it, it's an error. if (warningsWithComponentStack.length > 0) { return { message: () => `Received warning unexpectedly includes a component stack:\n ${this.utils.printReceived( warningsWithComponentStack[0] )}\nIf this warning intentionally includes the component stack, remove ` + `{withoutStack: true} from the ${matcherName}() call. If you have a mix of ` + `warnings with and without stack in one ${matcherName}() call, pass ` + `{withoutStack: N} where N is the number of warnings without stacks.`, pass: false, }; } } else if (withoutStack === false || withoutStack === undefined) { // We're expecting that all warnings *do* have the stack (default). // If some warnings don't have it, it's an error. if (warningsWithoutComponentStack.length > 0) { return { message: () => `Received warning unexpectedly does not include a component stack:\n ${this.utils.printReceived( warningsWithoutComponentStack[0] )}\nIf this warning intentionally omits the component stack, add ` + `{withoutStack: true} to the ${matcherName} call.`, pass: false, }; } } else { throw Error( `The second argument for ${matcherName}(), when specified, must be an object. It may have a ` + `property called "withoutStack" whose value may be undefined, boolean, or a number. ` + `Instead received ${typeof withoutStack}.` ); } if (lastWarningWithMismatchingFormat !== null) { return { message: () => `Received ${ lastWarningWithMismatchingFormat.args.length } arguments for a message with ${ lastWarningWithMismatchingFormat.expectedArgCount } placeholders:\n ${this.utils.printReceived( lastWarningWithMismatchingFormat.format )}`, pass: false, }; } if (lastWarningWithExtraComponentStack !== null) { return { message: () => `Received more than one component stack for a warning:\n ${this.utils.printReceived( lastWarningWithExtraComponentStack.format )}\nDid you accidentally pass a stack to warning() as the last argument? ` + `Don't forget warning() already injects the component stack automatically.`, pass: false, }; } return {pass: true}; } } else { // Any uncaught errors or warnings should fail tests in production mode. callback(); return {pass: true}; } }; expect.extend({ toWarnDev: createMatcherFor('warn', 'toWarnDev'), toErrorDev: createMatcherFor('error', 'toErrorDev'), });
35.915858
135
0.57952
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 all exports so that they're available in tests. // We can't use export * from in Flow for some reason. export {default as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED} from './src/ReactDOMSharedInternals'; export { createPortal, createRoot, hydrateRoot, findDOMNode, flushSync, hydrate, render, unmountComponentAtNode, unstable_batchedUpdates, unstable_createEventHandle, unstable_renderSubtreeIntoContainer, unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority. useFormStatus, useFormState, prefetchDNS, preconnect, preload, preloadModule, preinit, preinitModule, version, } from './src/client/ReactDOM';
24.583333
108
0.741304
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 */ /** * HTML nodeType values that represent the type of the node */ export const ELEMENT_NODE = 1; export const TEXT_NODE = 3; export const COMMENT_NODE = 8; export const DOCUMENT_NODE = 9; export const DOCUMENT_TYPE_NODE = 10; export const DOCUMENT_FRAGMENT_NODE = 11;
22.8
66
0.713684
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'; function isEmptyLiteral(node) { return ( node.type === 'Literal' && typeof node.value === 'string' && node.value === '' ); } function isStringLiteral(node) { return ( // TaggedTemplateExpressions can return non-strings (node.type === 'TemplateLiteral' && node.parent.type !== 'TaggedTemplateExpression') || (node.type === 'Literal' && typeof node.value === 'string') ); } // Symbols and Temporal.* objects will throw when using `'' + value`, but that // pattern can be faster than `String(value)` because JS engines can optimize // `+` better in some cases. Therefore, in perf-sensitive production codepaths // we require using `'' + value` for string coercion. The only exception is prod // error handling code, because it's bad to crash while assembling an error // message or call stack! Also, error-handling code isn't usually perf-critical. // // Non-production codepaths (tests, devtools extension, build tools, etc.) // should use `String(value)` because it will never crash and the (small) perf // difference doesn't matter enough for non-prod use cases. // // This rule assists enforcing these guidelines: // * `'' + value` is flagged with a message to remind developers to add a DEV // check from shared/CheckStringCoercion.js to make sure that the user gets a // clear error message in DEV is the coercion will throw. These checks are not // needed if throwing is not possible, e.g. if the value is already known to // be a string or number. // * `String(value)` is flagged only if the `isProductionUserAppCode` option // is set. Set this option for prod code files, and don't set it for non-prod // files. const ignoreKeys = [ 'range', 'raw', 'parent', 'loc', 'start', 'end', '_babelType', 'leadingComments', 'trailingComments', ]; function astReplacer(key, value) { return ignoreKeys.includes(key) ? undefined : value; } /** * Simplistic comparison between AST node. Only the following patterns are * supported because that's almost all (all?) usage in React: * - Identifiers, e.g. `foo` * - Member access, e.g. `foo.bar` * - Array access with numeric literal, e.g. `foo[0]` */ function isEquivalentCode(node1, node2) { return ( JSON.stringify(node1, astReplacer) === JSON.stringify(node2, astReplacer) ); } function isDescendant(node, maybeParentNode) { let parent = node.parent; while (parent) { if (!parent) { return false; } if (parent === maybeParentNode) { return true; } parent = parent.parent; } return false; } function isSafeTypeofExpression(originalValueNode, node) { if (node.type === 'BinaryExpression') { // Example: typeof foo === 'string' if (node.operator !== '===') { return false; } const {left, right} = node; // left must be `typeof original` if (left.type !== 'UnaryExpression' || left.operator !== 'typeof') { return false; } if (!isEquivalentCode(left.argument, originalValueNode)) { return false; } // right must be a literal value of a safe type const safeTypes = ['string', 'number', 'boolean', 'undefined', 'bigint']; if (right.type !== 'Literal' || !safeTypes.includes(right.value)) { return false; } return true; } else if (node.type === 'LogicalExpression') { // Examples: // * typeof foo === 'string' && typeof foo === 'number // * typeof foo === 'string' && someOtherTest if (node.operator === '&&') { return ( isSafeTypeofExpression(originalValueNode, node.left) || isSafeTypeofExpression(originalValueNode, node.right) ); } else if (node.operator === '||') { return ( isSafeTypeofExpression(originalValueNode, node.left) && isSafeTypeofExpression(originalValueNode, node.right) ); } } return false; } /** Returns true if the code is inside an `if` block that validates the value excludes symbols and objects. Examples: * if (typeof value === 'string') { } * if (typeof value === 'string' || typeof value === 'number') { } * if (typeof value === 'string' || someOtherTest) { } @param - originalValueNode Top-level expression to test. Kept unchanged during recursion. @param - node Expression to test at current recursion level. Will be undefined on non-recursive call. */ function isInSafeTypeofBlock(originalValueNode, node) { if (!node) { node = originalValueNode; } let parent = node.parent; while (parent) { if (!parent) { return false; } // Normally, if the parent block is inside a type-safe `if` statement, // then all child code is also type-safe. But there's a quirky case we // need to defend against: // if (typeof obj === 'string') { } else if (typeof obj === 'object') {'' + obj} // if (typeof obj === 'string') { } else {'' + obj} // In that code above, the `if` block is safe, but the `else` block is // unsafe and should report. But the AST parent of the `else` clause is the // `if` statement. This is the one case where the parent doesn't confer // safety onto the child. The code below identifies that case and keeps // moving up the tree until we get out of the `else`'s parent `if` block. // This ensures that we don't use any of these "parents" (really siblings) // to confer safety onto the current node. if ( parent.type === 'IfStatement' && !isDescendant(originalValueNode, parent.alternate) ) { const test = parent.test; if (isSafeTypeofExpression(originalValueNode, test)) { return true; } } parent = parent.parent; } } const missingDevCheckMessage = 'Missing DEV check before this string coercion.' + ' Check should be in this format:\n' + ' if (__DEV__) {\n' + ' checkXxxxxStringCoercion(value);\n' + ' }'; const prevStatementNotDevCheckMessage = 'The statement before this coercion must be a DEV check in this format:\n' + ' if (__DEV__) {\n' + ' checkXxxxxStringCoercion(value);\n' + ' }'; /** * Does this node have an "is coercion safe?" DEV check * in the same block? */ function hasCoercionCheck(node) { // find the containing statement let topOfExpression = node; while (!topOfExpression.parent.body) { topOfExpression = topOfExpression.parent; if (!topOfExpression) { return 'Cannot find top of expression.'; } } const containingBlock = topOfExpression.parent.body; const index = containingBlock.indexOf(topOfExpression); if (index <= 0) { return missingDevCheckMessage; } const prev = containingBlock[index - 1]; // The previous statement is expected to be like this: // if (__DEV__) { // checkFormFieldValueStringCoercion(foo); // } // where `foo` must be equivalent to `node` (which is the // mixed value being coerced to a string). if ( prev.type !== 'IfStatement' || prev.test.type !== 'Identifier' || prev.test.name !== '__DEV__' ) { return prevStatementNotDevCheckMessage; } let maybeCheckNode = prev.consequent; if (maybeCheckNode.type === 'BlockStatement') { const body = maybeCheckNode.body; if (body.length === 0) { return prevStatementNotDevCheckMessage; } if (body.length !== 1) { return ( 'Too many statements in DEV block before this coercion.' + ' Expected only one (the check function call). ' + prevStatementNotDevCheckMessage ); } maybeCheckNode = body[0]; } if (maybeCheckNode.type !== 'ExpressionStatement') { return ( 'The DEV block before this coercion must only contain an expression. ' + prevStatementNotDevCheckMessage ); } const call = maybeCheckNode.expression; if ( call.type !== 'CallExpression' || call.callee.type !== 'Identifier' || !/^check(\w+?)StringCoercion$/.test(call.callee.name) || !call.arguments.length ) { // `maybeCheckNode` should be a call of a function named checkXXXStringCoercion return ( 'Missing or invalid check function call before this coercion.' + ' Expected: call of a function like checkXXXStringCoercion. ' + prevStatementNotDevCheckMessage ); } const same = isEquivalentCode(call.arguments[0], node); if (!same) { return ( 'Value passed to the check function before this coercion' + ' must match the value being coerced.' ); } } function isOnlyAddingStrings(node) { if (node.operator !== '+') { return; } if (isStringLiteral(node.left) && isStringLiteral(node.right)) { // It's always safe to add string literals return true; } if (node.left.type === 'BinaryExpression' && isStringLiteral(node.right)) { return isOnlyAddingStrings(node.left); } } function checkBinaryExpression(context, node) { if (isOnlyAddingStrings(node)) { return; } if ( node.operator === '+' && (isEmptyLiteral(node.left) || isEmptyLiteral(node.right)) ) { let valueToTest = isEmptyLiteral(node.left) ? node.right : node.left; if ( (valueToTest.type === 'TypeCastExpression' || valueToTest.type === 'AsExpression') && valueToTest.expression ) { valueToTest = valueToTest.expression; } if ( valueToTest.type === 'Identifier' && ['i', 'idx', 'lineNumber'].includes(valueToTest.name) ) { // Common non-object variable names are assumed to be safe return; } if ( valueToTest.type === 'UnaryExpression' || valueToTest.type === 'UpdateExpression' ) { // Any unary expression will return a non-object, non-symbol type. return; } if (isInSafeTypeofBlock(valueToTest)) { // The value is inside an if (typeof...) block that ensures it's safe return; } const coercionCheckMessage = hasCoercionCheck(valueToTest); if (!coercionCheckMessage) { // The previous statement is a correct check function call, so no report. return; } context.report({ node, message: coercionCheckMessage + '\n' + "Using `'' + value` or `value + ''` is fast to coerce strings, but may throw." + ' For prod code, add a DEV check from shared/CheckStringCoercion immediately' + ' before this coercion.' + ' For non-prod code and prod error handling, use `String(value)` instead.', }); } } function coerceWithStringConstructor(context, node) { const isProductionUserAppCode = context.options[0] && context.options[0].isProductionUserAppCode; if (isProductionUserAppCode && node.callee.name === 'String') { context.report( node, "For perf-sensitive coercion, avoid `String(value)`. Instead, use `'' + value`." + ' Precede it with a DEV check from shared/CheckStringCoercion' + ' unless Symbol and Temporal.* values are impossible.' + ' For non-prod code and prod error handling, use `String(value)` and disable this rule.' ); } } module.exports = { meta: { schema: [ { type: 'object', properties: { isProductionUserAppCode: { type: 'boolean', default: false, }, }, additionalProperties: false, }, ], }, create(context) { return { BinaryExpression: node => checkBinaryExpression(context, node), CallExpression: node => coerceWithStringConstructor(context, node), }; }, };
30.168
96
0.641311
Nojle
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; global.TextDecoder = require('util').TextDecoder; // let serverExports; let turbopackServerMap; let ReactServerDOMServer; let ReactServerDOMClient; describe('ReactFlightDOMReply', () => { beforeEach(() => { jest.resetModules(); // Simulate the condition resolution jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-server-dom-turbopack/server', () => require('react-server-dom-turbopack/server.edge'), ); const TurbopackMock = require('./utils/TurbopackMock'); // serverExports = TurbopackMock.serverExports; turbopackServerMap = TurbopackMock.turbopackServerMap; ReactServerDOMServer = require('react-server-dom-turbopack/server.edge'); jest.resetModules(); ReactServerDOMClient = require('react-server-dom-turbopack/client.edge'); }); it('can encode a reply', async () => { const body = await ReactServerDOMClient.encodeReply({some: 'object'}); const decoded = await ReactServerDOMServer.decodeReply( body, turbopackServerMap, ); expect(decoded).toEqual({some: 'object'}); }); });
29.77551
77
0.706038
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 type {ReactContext} from 'shared/ReactTypes'; import {createContext} from 'react'; const TreeFocusedContext: ReactContext<boolean> = createContext<boolean>(false); export default TreeFocusedContext;
23.352941
80
0.745763
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'; module.exports = { meta: { fixable: 'code', schema: [], }, create: function (context) { function isInDEVBlock(node) { let done = false; while (!done) { let parent = node.parent; if (!parent) { return false; } if ( parent.type === 'IfStatement' && node === parent.consequent && parent.test.type === 'Identifier' && // This is intentionally strict so we can // see blocks of DEV-only code at once. parent.test.name === '__DEV__' ) { return true; } node = parent; } } function reportWrapInDEV(node) { context.report({ node: node, message: `Wrap console.{{identifier}}() in an "if (__DEV__) {}" check`, data: { identifier: node.property.name, }, fix: function (fixer) { return [ fixer.insertTextBefore(node.parent, `if (__DEV__) {`), fixer.insertTextAfter(node.parent, '}'), ]; }, }); } function reportUnexpectedConsole(node) { context.report({ node: node, message: `Unexpected use of console`, }); } return { MemberExpression: function (node) { if ( node.object.type === 'Identifier' && node.object.name === 'console' && node.property.type === 'Identifier' ) { switch (node.property.name) { case 'error': case 'warn': { if (!isInDEVBlock(node)) { reportWrapInDEV(node); } break; } default: { reportUnexpectedConsole(node); break; } } } }, }; }, };
22.643678
79
0.477626
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } // ?sourceMappingURL=([^\s'"]+)/gm function Component() { const [count, setCount] = (0, _react.useState)(0); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 18, columnNumber: 5 } }, /*#__PURE__*/_react.default.createElement("p", { __source: { fileName: _jsxFileName, lineNumber: 19, columnNumber: 7 } }, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", { onClick: () => setCount(count + 1), __source: { fileName: _jsxFileName, lineNumber: 20, columnNumber: 7 } }, "Click me")); } //# sourceMappingURL=ContainingStringSourceMappingURL.js.map?foo=bar&param=some_value
45.975
743
0.651225
owtf
/** @license React v16.14.0 * react-jsx-dev-runtime.development.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'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var React = require('react'); // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; exports.Fragment = 0xeacb; var REACT_STRICT_MODE_TYPE = 0xeacc; var REACT_PROFILER_TYPE = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; var REACT_SUSPENSE_TYPE = 0xead1; var REACT_SUSPENSE_LIST_TYPE = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_BLOCK_TYPE = 0xead9; var REACT_SERVER_BLOCK_TYPE = 0xeada; var REACT_FUNDAMENTAL_TYPE = 0xead5; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); exports.Fragment = symbolFor('react.fragment'); REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); REACT_PROFILER_TYPE = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_BLOCK_TYPE = symbolFor('react.block'); REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); } var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function error(format) { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ''; if (currentlyValidatingElement) { var name = getComponentName(currentlyValidatingElement.type); var owner = currentlyValidatingElement._owner; stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type)); } stack += ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableScopeAPI = false; // Experimental Create Event Handle API. function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { return true; } } return false; } var BEFORE_SLASH_RE = /^(.*)[\\\/]/; function describeComponentFrame (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; } var Resolved = 1; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case exports.Fragment: 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'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_BLOCK_TYPE: return getComponentName(type.render); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } break; } } } return null; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var currentlyValidatingElement = null; function setCurrentlyValidatingElement(element) { currentlyValidatingElement = element; } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(Object.prototype.hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown; var specialPropRefWarningShown; var didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function warnIfStringRefCannotBeAutoConverted(config, self) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { var componentName = getComponentName(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref); didWarnAboutStringRefs[componentName] = true; } } } } function defineKeyPropWarningGetter(props, displayName) { { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } } function defineRefPropWarningGetter(props, displayName) { { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ function jsxDEV(type, config, maybeKey, source, self) { { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { key = '' + maybeKey; } if (hasValidKey(config)) { key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; warnIfStringRefCannotBeAutoConverted(config, self); } // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } } var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement$1(element) { currentlyValidatingElement = element; } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } } function getDeclarationErrorAddendum() { { if (ReactCurrentOwner$1.current) { var name = getComponentName(ReactCurrentOwner$1.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } } function getSourceInfoErrorAddendum(source) { { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; } setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentName(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentName(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function jsxWithValidation(type, props, key, isStaticChildren, source, self) { { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(source); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { var children = props.children; if (children !== undefined) { if (isStaticChildren) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { validateChildKeys(children[i], type); } if (Object.freeze) { Object.freeze(children); } } else { error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); } } else { validateChildKeys(children, type); } } } if (type === exports.Fragment) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } } // These two functions exist to still get child warnings in dev var jsxDEV$1 = jsxWithValidation ; exports.jsxDEV = jsxDEV$1; })(); }
31.257303
450
0.652849
Python-Penetration-Testing-Cookbook
"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+XG4gICAgICAgICkpfVxuICAgICAgPC91bD5cbiAgICA8L0ZyYWdtZW50PlxuICApO1xufVxuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiIsImhhbmRsZURlbGV0ZSIsImhhbmRsZVRvZ2dsZSIsIm5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJ1aWQiLCJoYW5kbGVDbGljayIsImhhbmRsZUtleVByZXNzIiwiaGFuZGxlQ2hhbmdlIiwicmVtb3ZlSXRlbSIsInRvZ2dsZUl0ZW0iXSwibWFwcGluZ3MiOiJDQUFEO2N1QkNBO2dCQ0RBO2tCREVBO29CQ0ZBO3NDZ0JHQSxBWUhBO3VDeEJJQTsyQ3hCSkE7NENvQktBLEFXTEE7OENiTUE7MkRTTkE7NkROT0E7b0V0QlBBO3NFb0JRQTsyRXBCUkE7NkVrQlNBO2dGbEJUQTtrRmtCVUE7bUdsQlZBIn1dXX0=
87.64375
9,216
0.858835
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 */ let React; let ReactNoop; let Scheduler; let act; let Suspense; let getCacheForType; let caches; let seededCache; let ErrorBoundary; let waitForAll; let waitFor; let assertLog; // TODO: These tests don't pass in persistent mode yet. Need to implement. describe('ReactSuspenseEffectsSemantics', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; Suspense = React.Suspense; getCacheForType = React.unstable_getCacheForType; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; assertLog = InternalTestUtils.assertLog; caches = []; seededCache = null; ErrorBoundary = class extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { if (this.state.error) { Scheduler.log('ErrorBoundary render: catch'); return this.props.fallback; } Scheduler.log('ErrorBoundary render: try'); return this.props.children; } }; }); function createTextCache() { if (seededCache !== null) { // Trick to seed a cache before it exists. // TODO: Need a built-in API to seed data before the initial render (i.e. // not a refresh because nothing has mounted yet). const cache = seededCache; seededCache = null; return cache; } const data = new Map(); const version = caches.length + 1; const cache = { version, data, resolve(text) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } }, reject(text, error) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'rejected', value: error, }; data.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'rejected'; record.value = error; thenable.pings.forEach(t => t()); } }, }; caches.push(cache); return cache; } function readText(text) { const textCache = getCacheForType(createTextCache); const record = textCache.data.get(text); if (record !== undefined) { switch (record.status) { case 'pending': Scheduler.log(`Suspend:${text}`); throw record.value; case 'rejected': Scheduler.log(`Error:${text}`); throw record.value; case 'resolved': return textCache.version; } } else { Scheduler.log(`Suspend:${text}`); const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.data.set(text, newRecord); throw thenable; } } function Text({children = null, text}) { Scheduler.log(`Text:${text} render`); React.useLayoutEffect(() => { Scheduler.log(`Text:${text} create layout`); return () => { Scheduler.log(`Text:${text} destroy layout`); }; }, []); React.useEffect(() => { Scheduler.log(`Text:${text} create passive`); return () => { Scheduler.log(`Text:${text} destroy passive`); }; }, []); return <span prop={text}>{children}</span>; } function AsyncText({children = null, text}) { readText(text); Scheduler.log(`AsyncText:${text} render`); React.useLayoutEffect(() => { Scheduler.log(`AsyncText:${text} create layout`); return () => { Scheduler.log(`AsyncText:${text} destroy layout`); }; }, []); React.useEffect(() => { Scheduler.log(`AsyncText:${text} create passive`); return () => { Scheduler.log(`AsyncText:${text} destroy passive`); }; }, []); return <span prop={text}>{children}</span>; } function resolveMostRecentTextCache(text) { if (caches.length === 0) { throw Error('Cache does not exist.'); } else { // Resolve the most recently created cache. An older cache can by // resolved with `caches[index].resolve(text)`. caches[caches.length - 1].resolve(text); } } const resolveText = resolveMostRecentTextCache; function advanceTimers(ms) { // Note: This advances Jest's virtual time but not React's. Use // ReactNoop.expire for that. if (typeof ms !== 'number') { throw new Error('Must specify ms'); } jest.advanceTimersByTime(ms); // Wait until the end of the current tick // We cannot use a timer since we're faking them return Promise.resolve().then(() => {}); } describe('when a component suspends during initial mount', () => { // @gate enableLegacyCache it('should not change behavior in concurrent mode', async () => { class ClassText extends React.Component { componentDidMount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidMount`); } componentDidUpdate() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidUpdate`); } componentWillUnmount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentWillUnmount`); } render() { const {children, text} = this.props; Scheduler.log(`ClassText:${text} render`); return <span prop={text}>{children}</span>; } } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); React.useEffect(() => { Scheduler.log('App create passive'); return () => { Scheduler.log('App destroy passive'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> <Text text="Inside:Before" /> {children} <ClassText text="Inside:After" /> </Suspense> <Text text="Outside" /> </> ); } // Mount and suspend. await act(() => { ReactNoop.render( <App> <AsyncText text="Async" ms={1000} /> </App>, ); }); assertLog([ 'App render', 'Text:Inside:Before render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outside render', 'Text:Fallback create layout', 'Text:Outside create layout', 'App create layout', 'Text:Fallback create passive', 'Text:Outside create passive', 'App create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Fallback" /> <span prop="Outside" /> </>, ); // Resolving the suspended resource should await act(async () => { await resolveText('Async'); }); assertLog([ 'Text:Inside:Before render', 'AsyncText:Async render', 'ClassText:Inside:After render', 'Text:Fallback destroy layout', 'Text:Inside:Before create layout', 'AsyncText:Async create layout', 'ClassText:Inside:After componentDidMount', 'Text:Fallback destroy passive', 'Text:Inside:Before create passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Async" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'App destroy layout', 'Text:Inside:Before destroy layout', 'AsyncText:Async destroy layout', 'ClassText:Inside:After componentWillUnmount', 'Text:Outside destroy layout', 'App destroy passive', 'Text:Inside:Before destroy passive', 'AsyncText:Async destroy passive', 'Text:Outside destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('should not change behavior in sync', async () => { class ClassText extends React.Component { componentDidMount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidMount`); } componentDidUpdate() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidUpdate`); } componentWillUnmount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentWillUnmount`); } render() { const {children, text} = this.props; Scheduler.log(`ClassText:${text} render`); return <span prop={text}>{children}</span>; } } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); React.useEffect(() => { Scheduler.log('App create passive'); return () => { Scheduler.log('App destroy passive'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> <Text text="Inside:Before" /> {children} <ClassText text="Inside:After" /> </Suspense> <Text text="Outside" /> </> ); } // Mount and suspend. await act(() => { ReactNoop.renderLegacySyncRoot( <App> <AsyncText text="Async" ms={1000} /> </App>, ); }); assertLog([ 'App render', 'Text:Inside:Before render', 'Suspend:Async', 'ClassText:Inside:After render', 'Text:Fallback render', 'Text:Outside render', 'Text:Inside:Before create layout', 'ClassText:Inside:After componentDidMount', 'Text:Fallback create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside:Before create passive', 'Text:Fallback create passive', 'Text:Outside create passive', 'App create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" hidden={true} /> <span prop="Inside:After" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); // Resolving the suspended resource should await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Async" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); await act(() => { ReactNoop.renderLegacySyncRoot(null); }); assertLog([ 'App destroy layout', 'Text:Inside:Before destroy layout', 'AsyncText:Async destroy layout', 'ClassText:Inside:After componentWillUnmount', 'Text:Outside destroy layout', 'App destroy passive', 'Text:Inside:Before destroy passive', 'AsyncText:Async destroy passive', 'Text:Outside destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput(null); }); }); describe('layout effects within a tree that re-suspends in an update', () => { // @gate enableLegacyCache it('should not be destroyed or recreated in legacy roots', async () => { function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); React.useEffect(() => { Scheduler.log('App create passive'); return () => { Scheduler.log('App destroy passive'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> <Text text="Inside:Before" /> {children} <Text text="Inside:After" /> </Suspense> <Text text="Outside" /> </> ); } // Mount await act(() => { ReactNoop.renderLegacySyncRoot(<App />); }); assertLog([ 'App render', 'Text:Inside:Before render', 'Text:Inside:After render', 'Text:Outside render', 'Text:Inside:Before create layout', 'Text:Inside:After create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside:Before create passive', 'Text:Inside:After create passive', 'Text:Outside create passive', 'App create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); // Schedule an update that causes React to suspend. await act(() => { ReactNoop.renderLegacySyncRoot( <App> <AsyncText text="Async" ms={1000} /> </App>, ); }); assertLog([ 'App render', 'Text:Inside:Before render', 'Suspend:Async', 'Text:Inside:After render', 'Text:Fallback render', 'Text:Outside render', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" hidden={true} /> <span prop="Inside:After" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); await advanceTimers(1000); // Noop since sync root has already committed assertLog([]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" hidden={true} /> <span prop="Inside:After" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Async" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); await act(() => { ReactNoop.renderLegacySyncRoot(null); }); assertLog([ 'App destroy layout', 'Text:Inside:Before destroy layout', 'AsyncText:Async destroy layout', 'Text:Inside:After destroy layout', 'Text:Outside destroy layout', 'App destroy passive', 'Text:Inside:Before destroy passive', 'AsyncText:Async destroy passive', 'Text:Inside:After destroy passive', 'Text:Outside destroy passive', ]); }); // @gate enableLegacyCache it('should be destroyed and recreated for function components', async () => { function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); React.useEffect(() => { Scheduler.log('App create passive'); return () => { Scheduler.log('App destroy passive'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> <Text text="Inside:Before" /> {children} <Text text="Inside:After" /> </Suspense> <Text text="Outside" /> </> ); } await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'Text:Inside:Before render', 'Text:Inside:After render', 'Text:Outside render', 'Text:Inside:Before create layout', 'Text:Inside:After create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside:Before create passive', 'Text:Inside:After create passive', 'Text:Outside create passive', 'App create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); // Schedule an update that causes React to suspend. await act(async () => { ReactNoop.render( <App> <AsyncText text="Async" ms={1000} /> </App>, ); await waitFor([ 'App render', 'Text:Inside:Before render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outside render', 'Text:Inside:Before destroy layout', 'Text:Inside:After destroy layout', 'Text:Fallback create layout', ]); await waitForAll(['Text:Fallback create passive']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" hidden={true} /> <span prop="Inside:After" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); }); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'Text:Inside:Before render', 'AsyncText:Async render', 'Text:Inside:After render', 'Text:Fallback destroy layout', 'Text:Inside:Before create layout', 'AsyncText:Async create layout', 'Text:Inside:After create layout', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Async" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'App destroy layout', 'Text:Inside:Before destroy layout', 'AsyncText:Async destroy layout', 'Text:Inside:After destroy layout', 'Text:Outside destroy layout', 'App destroy passive', 'Text:Inside:Before destroy passive', 'AsyncText:Async destroy passive', 'Text:Inside:After destroy passive', 'Text:Outside destroy passive', ]); }); // @gate enableLegacyCache it('should be destroyed and recreated for class components', async () => { class ClassText extends React.Component { componentDidMount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidMount`); } componentDidUpdate() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidUpdate`); } componentWillUnmount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentWillUnmount`); } render() { const {children, text} = this.props; Scheduler.log(`ClassText:${text} render`); return <span prop={text}>{children}</span>; } } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); React.useEffect(() => { Scheduler.log('App create passive'); return () => { Scheduler.log('App destroy passive'); }; }, []); return ( <> <Suspense fallback={<ClassText text="Fallback" />}> <ClassText text="Inside:Before" /> {children} <ClassText text="Inside:After" /> </Suspense> <ClassText text="Outside" /> </> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'ClassText:Inside:Before render', 'ClassText:Inside:After render', 'ClassText:Outside render', 'ClassText:Inside:Before componentDidMount', 'ClassText:Inside:After componentDidMount', 'ClassText:Outside componentDidMount', 'App create layout', 'App create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); // Schedule an update that causes React to suspend. await act(async () => { ReactNoop.render( <App> <AsyncText text="Async" ms={1000} /> </App>, ); await waitFor([ 'App render', 'ClassText:Inside:Before render', 'Suspend:Async', 'ClassText:Fallback render', 'ClassText:Outside render', 'ClassText:Inside:Before componentWillUnmount', 'ClassText:Inside:After componentWillUnmount', 'ClassText:Fallback componentDidMount', 'ClassText:Outside componentDidUpdate', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" hidden={true} /> <span prop="Inside:After" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); }); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'ClassText:Inside:Before render', 'AsyncText:Async render', 'ClassText:Inside:After render', 'ClassText:Fallback componentWillUnmount', 'ClassText:Inside:Before componentDidMount', 'AsyncText:Async create layout', 'ClassText:Inside:After componentDidMount', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside:Before" /> <span prop="Async" /> <span prop="Inside:After" /> <span prop="Outside" /> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'App destroy layout', 'ClassText:Inside:Before componentWillUnmount', 'AsyncText:Async destroy layout', 'ClassText:Inside:After componentWillUnmount', 'ClassText:Outside componentWillUnmount', 'App destroy passive', 'AsyncText:Async destroy passive', ]); }); // @gate enableLegacyCache it('should be destroyed and recreated when nested below host components', async () => { function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); React.useEffect(() => { Scheduler.log('App create passive'); return () => { Scheduler.log('App destroy passive'); }; }, []); return ( <Suspense fallback={<Text text="Fallback" />}> {children} <Text text="Outer"> <Text text="Inner" /> </Text> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'Text:Outer render', 'Text:Inner render', 'Text:Inner create layout', 'Text:Outer create layout', 'App create layout', 'Text:Inner create passive', 'Text:Outer create passive', 'App create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <span prop="Outer"> <span prop="Inner" /> </span>, ); // Schedule an update that causes React to suspend. await act(async () => { ReactNoop.render( <App> <AsyncText text="Async" ms={1000} /> </App>, ); await waitFor([ 'App render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outer destroy layout', 'Text:Inner destroy layout', 'Text:Fallback create layout', ]); await waitForAll(['Text:Fallback create passive']); expect(ReactNoop).toMatchRenderedOutput( <> <span hidden={true} prop="Outer"> <span prop="Inner" /> </span> <span prop="Fallback" /> </>, ); }); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'Text:Outer render', 'Text:Inner render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'Text:Inner create layout', 'Text:Outer create layout', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Async" /> <span prop="Outer"> <span prop="Inner" /> </span> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'App destroy layout', 'AsyncText:Async destroy layout', 'Text:Outer destroy layout', 'Text:Inner destroy layout', 'App destroy passive', 'AsyncText:Async destroy passive', 'Text:Outer destroy passive', 'Text:Inner destroy passive', ]); }); // @gate enableLegacyCache it('should be destroyed and recreated even if there is a bailout because of memoization', async () => { const MemoizedText = React.memo(Text, () => true); function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); React.useEffect(() => { Scheduler.log('App create passive'); return () => { Scheduler.log('App destroy passive'); }; }, []); return ( <Suspense fallback={<Text text="Fallback" />}> {children} <Text text="Outer"> <MemoizedText text="MemoizedInner" /> </Text> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'Text:Outer render', 'Text:MemoizedInner render', 'Text:MemoizedInner create layout', 'Text:Outer create layout', 'App create layout', 'Text:MemoizedInner create passive', 'Text:Outer create passive', 'App create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <span prop="Outer"> <span prop="MemoizedInner" /> </span>, ); // Schedule an update that causes React to suspend. await act(async () => { ReactNoop.render( <App> <AsyncText text="Async" ms={1000} /> </App>, ); await waitFor([ 'App render', 'Suspend:Async', // Text:MemoizedInner is memoized 'Text:Fallback render', 'Text:Outer destroy layout', 'Text:MemoizedInner destroy layout', 'Text:Fallback create layout', ]); await waitForAll(['Text:Fallback create passive']); expect(ReactNoop).toMatchRenderedOutput( <> <span hidden={true} prop="Outer"> <span prop="MemoizedInner" /> </span> <span prop="Fallback" /> </>, ); }); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'Text:Outer render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'Text:MemoizedInner create layout', 'Text:Outer create layout', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Async" /> <span prop="Outer"> <span prop="MemoizedInner" /> </span> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'App destroy layout', 'AsyncText:Async destroy layout', 'Text:Outer destroy layout', 'Text:MemoizedInner destroy layout', 'App destroy passive', 'AsyncText:Async destroy passive', 'Text:Outer destroy passive', 'Text:MemoizedInner destroy passive', ]); }); // @gate enableLegacyCache it('should respect nested suspense boundaries', async () => { function App({innerChildren = null, outerChildren = null}) { return ( <Suspense fallback={<Text text="OuterFallback" />}> <Text text="Outer" /> {outerChildren} <Suspense fallback={<Text text="InnerFallback" />}> <Text text="Inner" /> {innerChildren} </Suspense> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'Text:Outer render', 'Text:Inner render', 'Text:Outer create layout', 'Text:Inner create layout', 'Text:Outer create passive', 'Text:Inner create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="Inner" /> </>, ); // Suspend the inner Suspense subtree (only inner effects should be destroyed) await act(() => { ReactNoop.render( <App innerChildren={<AsyncText text="InnerAsync_1" ms={1000} />} />, ); }); assertLog([ 'Text:Outer render', 'Text:Inner render', 'Suspend:InnerAsync_1', 'Text:InnerFallback render', 'Text:Inner destroy layout', 'Text:InnerFallback create layout', 'Text:InnerFallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="Inner" hidden={true} /> <span prop="InnerFallback" /> </>, ); // Suspend the outer Suspense subtree (outer effects and inner fallback effects should be destroyed) // (This check also ensures we don't destroy effects for mounted inner fallback.) await act(() => { ReactNoop.render( <App outerChildren={<AsyncText text="OuterAsync_1" ms={1000} />} innerChildren={<AsyncText text="InnerAsync_1" ms={1000} />} />, ); }); await advanceTimers(1000); assertLog([ 'Text:Outer render', 'Suspend:OuterAsync_1', 'Text:OuterFallback render', 'Text:Outer destroy layout', 'Text:InnerFallback destroy layout', 'Text:OuterFallback create layout', 'Text:OuterFallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" hidden={true} /> <span prop="Inner" hidden={true} /> <span prop="InnerFallback" hidden={true} /> <span prop="OuterFallback" /> </>, ); // Show the inner Suspense subtree (no effects should be recreated) await act(async () => { await resolveText('InnerAsync_1'); }); assertLog(['Text:Outer render', 'Suspend:OuterAsync_1']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" hidden={true} /> <span prop="Inner" hidden={true} /> <span prop="InnerFallback" hidden={true} /> <span prop="OuterFallback" /> </>, ); // Suspend the inner Suspense subtree (no effects should be destroyed) await act(() => { ReactNoop.render( <App outerChildren={<AsyncText text="OuterAsync_1" ms={1000} />} innerChildren={<AsyncText text="InnerAsync_2" ms={1000} />} />, ); }); await advanceTimers(1000); assertLog([ 'Text:Outer render', 'Suspend:OuterAsync_1', 'Text:OuterFallback render', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" hidden={true} /> <span prop="Inner" hidden={true} /> <span prop="InnerFallback" hidden={true} /> <span prop="OuterFallback" /> </>, ); // Show the outer Suspense subtree (only outer effects should be recreated) await act(async () => { await resolveText('OuterAsync_1'); }); assertLog([ 'Text:Outer render', 'AsyncText:OuterAsync_1 render', 'Text:Inner render', 'Suspend:InnerAsync_2', 'Text:InnerFallback render', 'Text:OuterFallback destroy layout', 'Text:Outer create layout', 'AsyncText:OuterAsync_1 create layout', 'Text:InnerFallback create layout', 'Text:OuterFallback destroy passive', 'AsyncText:OuterAsync_1 create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="OuterAsync_1" /> <span prop="Inner" hidden={true} /> <span prop="InnerFallback" /> </>, ); // Show the inner Suspense subtree (only inner effects should be recreated) await act(async () => { await resolveText('InnerAsync_2'); }); assertLog([ 'Text:Inner render', 'AsyncText:InnerAsync_2 render', 'Text:InnerFallback destroy layout', 'Text:Inner create layout', 'AsyncText:InnerAsync_2 create layout', 'Text:InnerFallback destroy passive', 'AsyncText:InnerAsync_2 create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="OuterAsync_1" /> <span prop="Inner" /> <span prop="InnerAsync_2" /> </>, ); // Suspend the outer Suspense subtree (all effects should be destroyed) await act(() => { ReactNoop.render( <App outerChildren={<AsyncText text="OuterAsync_2" ms={1000} />} innerChildren={<AsyncText text="InnerAsync_2" ms={1000} />} />, ); }); assertLog([ 'Text:Outer render', 'Suspend:OuterAsync_2', 'Text:OuterFallback render', 'Text:Outer destroy layout', 'AsyncText:OuterAsync_1 destroy layout', 'Text:Inner destroy layout', 'AsyncText:InnerAsync_2 destroy layout', 'Text:OuterFallback create layout', 'Text:OuterFallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" hidden={true} /> <span prop="OuterAsync_1" hidden={true} /> <span prop="Inner" hidden={true} /> <span prop="InnerAsync_2" hidden={true} /> <span prop="OuterFallback" /> </>, ); // Show the outer Suspense subtree (all effects should be recreated) await act(async () => { await resolveText('OuterAsync_2'); }); assertLog([ 'Text:Outer render', 'AsyncText:OuterAsync_2 render', 'Text:Inner render', 'AsyncText:InnerAsync_2 render', 'Text:OuterFallback destroy layout', 'Text:Outer create layout', 'AsyncText:OuterAsync_2 create layout', 'Text:Inner create layout', 'AsyncText:InnerAsync_2 create layout', 'Text:OuterFallback destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="OuterAsync_2" /> <span prop="Inner" /> <span prop="InnerAsync_2" /> </>, ); }); // @gate enableLegacyCache it('should show nested host nodes if multiple boundaries resolve at the same time', async () => { function App({innerChildren = null, outerChildren = null}) { return ( <Suspense fallback={<Text text="OuterFallback" />}> <Text text="Outer" /> {outerChildren} <Suspense fallback={<Text text="InnerFallback" />}> <Text text="Inner" /> {innerChildren} </Suspense> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'Text:Outer render', 'Text:Inner render', 'Text:Outer create layout', 'Text:Inner create layout', 'Text:Outer create passive', 'Text:Inner create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="Inner" /> </>, ); // Suspend the inner Suspense subtree (only inner effects should be destroyed) await act(() => { ReactNoop.render( <App innerChildren={<AsyncText text="InnerAsync_1" ms={1000} />} />, ); }); assertLog([ 'Text:Outer render', 'Text:Inner render', 'Suspend:InnerAsync_1', 'Text:InnerFallback render', 'Text:Inner destroy layout', 'Text:InnerFallback create layout', 'Text:InnerFallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="Inner" hidden={true} /> <span prop="InnerFallback" /> </>, ); // Suspend the outer Suspense subtree (outer effects and inner fallback effects should be destroyed) // (This check also ensures we don't destroy effects for mounted inner fallback.) await act(() => { ReactNoop.render( <App outerChildren={<AsyncText text="OuterAsync_1" ms={1000} />} innerChildren={<AsyncText text="InnerAsync_1" ms={1000} />} />, ); }); assertLog([ 'Text:Outer render', 'Suspend:OuterAsync_1', 'Text:OuterFallback render', 'Text:Outer destroy layout', 'Text:InnerFallback destroy layout', 'Text:OuterFallback create layout', 'Text:OuterFallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" hidden={true} /> <span prop="Inner" hidden={true} /> <span prop="InnerFallback" hidden={true} /> <span prop="OuterFallback" /> </>, ); // Resolve both suspended trees. await act(async () => { await resolveText('OuterAsync_1'); await resolveText('InnerAsync_1'); }); assertLog([ 'Text:Outer render', 'AsyncText:OuterAsync_1 render', 'Text:Inner render', 'AsyncText:InnerAsync_1 render', 'Text:OuterFallback destroy layout', 'Text:Outer create layout', 'AsyncText:OuterAsync_1 create layout', 'Text:Inner create layout', 'AsyncText:InnerAsync_1 create layout', 'Text:OuterFallback destroy passive', 'Text:InnerFallback destroy passive', 'AsyncText:OuterAsync_1 create passive', 'AsyncText:InnerAsync_1 create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Outer" /> <span prop="OuterAsync_1" /> <span prop="Inner" /> <span prop="InnerAsync_1" /> </>, ); }); // @gate enableLegacyCache it('should be cleaned up inside of a fallback that suspends', async () => { function App({fallbackChildren = null, outerChildren = null}) { return ( <> <Suspense fallback={ <> <Suspense fallback={<Text text="Fallback:Fallback" />}> <Text text="Fallback:Inside" /> {fallbackChildren} </Suspense> <Text text="Fallback:Outside" /> </> }> <Text text="Inside" /> {outerChildren} </Suspense> <Text text="Outside" /> </> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'Text:Inside render', 'Text:Outside render', 'Text:Inside create layout', 'Text:Outside create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Suspend the outer shell await act(async () => { ReactNoop.render( <App outerChildren={<AsyncText text="OutsideAsync" ms={1000} />} />, ); await waitFor([ 'Text:Inside render', 'Suspend:OutsideAsync', 'Text:Fallback:Inside render', 'Text:Fallback:Outside render', 'Text:Outside render', 'Text:Inside destroy layout', 'Text:Fallback:Inside create layout', 'Text:Fallback:Outside create layout', ]); await waitForAll([ 'Text:Fallback:Inside create passive', 'Text:Fallback:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" hidden={true} /> <span prop="Fallback:Inside" /> <span prop="Fallback:Outside" /> <span prop="Outside" /> </>, ); }); // Suspend the fallback and verify that it's effects get cleaned up as well await act(async () => { ReactNoop.render( <App fallbackChildren={<AsyncText text="FallbackAsync" ms={1000} />} outerChildren={<AsyncText text="OutsideAsync" ms={1000} />} />, ); await waitFor([ 'Text:Inside render', 'Suspend:OutsideAsync', 'Text:Fallback:Inside render', 'Suspend:FallbackAsync', 'Text:Fallback:Fallback render', 'Text:Fallback:Outside render', 'Text:Outside render', 'Text:Fallback:Inside destroy layout', 'Text:Fallback:Fallback create layout', ]); await waitForAll(['Text:Fallback:Fallback create passive']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" hidden={true} /> <span prop="Fallback:Inside" hidden={true} /> <span prop="Fallback:Fallback" /> <span prop="Fallback:Outside" /> <span prop="Outside" /> </>, ); }); // Resolving both resources should cleanup fallback effects and recreate main effects await act(async () => { await resolveText('FallbackAsync'); await resolveText('OutsideAsync'); }); assertLog([ 'Text:Inside render', 'AsyncText:OutsideAsync render', 'Text:Fallback:Fallback destroy layout', 'Text:Fallback:Outside destroy layout', 'Text:Inside create layout', 'AsyncText:OutsideAsync create layout', 'Text:Fallback:Inside destroy passive', 'Text:Fallback:Fallback destroy passive', 'Text:Fallback:Outside destroy passive', 'AsyncText:OutsideAsync create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" /> <span prop="OutsideAsync" /> <span prop="Outside" /> </>, ); }); // @gate enableLegacyCache it('should be cleaned up inside of a fallback that suspends (alternate)', async () => { function App({fallbackChildren = null, outerChildren = null}) { return ( <> <Suspense fallback={ <> <Suspense fallback={<Text text="Fallback:Fallback" />}> <Text text="Fallback:Inside" /> {fallbackChildren} </Suspense> <Text text="Fallback:Outside" /> </> }> <Text text="Inside" /> {outerChildren} </Suspense> <Text text="Outside" /> </> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'Text:Inside render', 'Text:Outside render', 'Text:Inside create layout', 'Text:Outside create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Suspend both the outer boundary and the fallback await act(() => { ReactNoop.render( <App outerChildren={<AsyncText text="OutsideAsync" ms={1000} />} fallbackChildren={<AsyncText text="FallbackAsync" ms={1000} />} />, ); }); assertLog([ 'Text:Inside render', 'Suspend:OutsideAsync', 'Text:Fallback:Inside render', 'Suspend:FallbackAsync', 'Text:Fallback:Fallback render', 'Text:Fallback:Outside render', 'Text:Outside render', 'Text:Inside destroy layout', 'Text:Fallback:Fallback create layout', 'Text:Fallback:Outside create layout', 'Text:Fallback:Fallback create passive', 'Text:Fallback:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" hidden={true} /> <span prop="Fallback:Fallback" /> <span prop="Fallback:Outside" /> <span prop="Outside" /> </>, ); // Resolving the inside fallback await act(async () => { await resolveText('FallbackAsync'); }); assertLog([ 'Text:Fallback:Inside render', 'AsyncText:FallbackAsync render', 'Text:Fallback:Fallback destroy layout', 'Text:Fallback:Inside create layout', 'AsyncText:FallbackAsync create layout', 'Text:Fallback:Fallback destroy passive', 'Text:Fallback:Inside create passive', 'AsyncText:FallbackAsync create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" hidden={true} /> <span prop="Fallback:Inside" /> <span prop="FallbackAsync" /> <span prop="Fallback:Outside" /> <span prop="Outside" /> </>, ); // Resolving the outer fallback only await act(async () => { await resolveText('OutsideAsync'); }); assertLog([ 'Text:Inside render', 'AsyncText:OutsideAsync render', 'Text:Fallback:Inside destroy layout', 'AsyncText:FallbackAsync destroy layout', 'Text:Fallback:Outside destroy layout', 'Text:Inside create layout', 'AsyncText:OutsideAsync create layout', 'Text:Fallback:Inside destroy passive', 'AsyncText:FallbackAsync destroy passive', 'Text:Fallback:Outside destroy passive', 'AsyncText:OutsideAsync create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" /> <span prop="OutsideAsync" /> <span prop="Outside" /> </>, ); }); // @gate enableLegacyCache it('should be cleaned up deeper inside of a subtree that suspends', async () => { function ConditionalSuspense({shouldSuspend}) { if (shouldSuspend) { readText('Suspend'); } return <Text text="Inside" />; } function App({children = null, shouldSuspend}) { return ( <> <Suspense fallback={<Text text="Fallback" />}> <ConditionalSuspense shouldSuspend={shouldSuspend} /> </Suspense> <Text text="Outside" /> </> ); } // Mount await act(() => { ReactNoop.render(<App shouldSuspend={false} />); }); assertLog([ 'Text:Inside render', 'Text:Outside render', 'Text:Inside create layout', 'Text:Outside create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Suspending a component in the middle of the tree // should still properly cleanup effects deeper in the tree await act(async () => { ReactNoop.render(<App shouldSuspend={true} />); await waitFor([ 'Suspend:Suspend', 'Text:Fallback render', 'Text:Outside render', 'Text:Inside destroy layout', 'Text:Fallback create layout', ]); await waitForAll(['Text:Fallback create passive']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); }); // Resolving should cleanup. await act(async () => { await resolveText('Suspend'); }); assertLog([ 'Text:Inside render', 'Text:Fallback destroy layout', 'Text:Inside create layout', 'Text:Fallback destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Inside" /> <span prop="Outside" /> </>, ); }); describe('that throw errors', () => { // @gate enableLegacyCache it('are properly handled for componentDidMount', async () => { let componentDidMountShouldThrow = false; class ThrowsInDidMount extends React.Component { componentWillUnmount() { Scheduler.log('ThrowsInDidMount componentWillUnmount'); } componentDidMount() { Scheduler.log('ThrowsInDidMount componentDidMount'); if (componentDidMountShouldThrow) { throw Error('expected'); } } render() { Scheduler.log('ThrowsInDidMount render'); return <span prop="ThrowsInDidMount" />; } } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> {children} <ThrowsInDidMount /> <Text text="Inside" /> </Suspense> <Text text="Outside" /> </> ); } await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App /> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'ThrowsInDidMount render', 'Text:Inside render', 'Text:Outside render', 'ThrowsInDidMount componentDidMount', 'Text:Inside create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInDidMount" /> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Schedule an update that causes React to suspend. await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App> <AsyncText text="Async" ms={1000} /> </App> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outside render', 'ThrowsInDidMount componentWillUnmount', 'Text:Inside destroy layout', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInDidMount" hidden={true} /> <span prop="Inside" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); // Resolve the pending suspense and throw componentDidMountShouldThrow = true; await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'ThrowsInDidMount render', 'Text:Inside render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', // Even though an error was thrown in componentDidMount, // subsequent layout effects should still be destroyed. 'ThrowsInDidMount componentDidMount', 'Text:Inside create layout', // Finish the in-progress commit 'Text:Fallback destroy passive', 'AsyncText:Async create passive', // Destroy layout and passive effects in the errored tree. 'App destroy layout', 'AsyncText:Async destroy layout', 'ThrowsInDidMount componentWillUnmount', 'Text:Inside destroy layout', 'Text:Outside destroy layout', 'AsyncText:Async destroy passive', 'Text:Inside destroy passive', 'Text:Outside destroy passive', // Render fallback 'ErrorBoundary render: catch', 'Text:Error render', 'Text:Error create layout', 'Text:Error create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Error" />); }); // @gate enableLegacyCache it('are properly handled for componentWillUnmount', async () => { class ThrowsInWillUnmount extends React.Component { componentDidMount() { Scheduler.log('ThrowsInWillUnmount componentDidMount'); } componentWillUnmount() { Scheduler.log('ThrowsInWillUnmount componentWillUnmount'); throw Error('expected'); } render() { Scheduler.log('ThrowsInWillUnmount render'); return <span prop="ThrowsInWillUnmount" />; } } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> {children} <ThrowsInWillUnmount /> <Text text="Inside" /> </Suspense> <Text text="Outside" /> </> ); } await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App /> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'ThrowsInWillUnmount render', 'Text:Inside render', 'Text:Outside render', 'ThrowsInWillUnmount componentDidMount', 'Text:Inside create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInWillUnmount" /> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Schedule an update that suspends and triggers our error code. await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App> <AsyncText text="Async" ms={1000} /> </App> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outside render', // Even though an error was thrown in componentWillUnmount, // subsequent layout effects should still be destroyed. 'ThrowsInWillUnmount componentWillUnmount', 'Text:Inside destroy layout', // Finish the in-progress commit 'Text:Fallback create layout', 'Text:Fallback create passive', // Destroy layout and passive effects in the errored tree. 'App destroy layout', 'Text:Fallback destroy layout', 'Text:Outside destroy layout', 'Text:Inside destroy passive', 'Text:Fallback destroy passive', 'Text:Outside destroy passive', // Render fallback 'ErrorBoundary render: catch', 'Text:Error render', 'Text:Error create layout', 'Text:Error create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Error" />); }); // @gate enableLegacyCache // @gate replayFailedUnitOfWorkWithInvokeGuardedCallback it('are properly handled for layout effect creation', async () => { let useLayoutEffectShouldThrow = false; function ThrowsInLayoutEffect() { Scheduler.log('ThrowsInLayoutEffect render'); React.useLayoutEffect(() => { Scheduler.log('ThrowsInLayoutEffect useLayoutEffect create'); if (useLayoutEffectShouldThrow) { throw Error('expected'); } return () => { Scheduler.log('ThrowsInLayoutEffect useLayoutEffect destroy'); }; }, []); return <span prop="ThrowsInLayoutEffect" />; } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> {children} <ThrowsInLayoutEffect /> <Text text="Inside" /> </Suspense> <Text text="Outside" /> </> ); } await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App /> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'ThrowsInLayoutEffect render', 'Text:Inside render', 'Text:Outside render', 'ThrowsInLayoutEffect useLayoutEffect create', 'Text:Inside create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInLayoutEffect" /> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Schedule an update that causes React to suspend. await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App> <AsyncText text="Async" ms={1000} /> </App> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outside render', 'ThrowsInLayoutEffect useLayoutEffect destroy', 'Text:Inside destroy layout', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInLayoutEffect" hidden={true} /> <span prop="Inside" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); // Resolve the pending suspense and throw useLayoutEffectShouldThrow = true; await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'ThrowsInLayoutEffect render', 'Text:Inside render', 'Text:Fallback destroy layout', // Even though an error was thrown in useLayoutEffect, // subsequent layout effects should still be created. 'AsyncText:Async create layout', 'ThrowsInLayoutEffect useLayoutEffect create', 'Text:Inside create layout', // Finish the in-progress commit 'Text:Fallback destroy passive', 'AsyncText:Async create passive', // Destroy layout and passive effects in the errored tree. 'App destroy layout', 'AsyncText:Async destroy layout', 'Text:Inside destroy layout', 'Text:Outside destroy layout', 'AsyncText:Async destroy passive', 'Text:Inside destroy passive', 'Text:Outside destroy passive', // Render fallback 'ErrorBoundary render: catch', 'Text:Error render', 'Text:Error create layout', 'Text:Error create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Error" />); }); // @gate enableLegacyCache // @gate replayFailedUnitOfWorkWithInvokeGuardedCallback it('are properly handled for layout effect destruction', async () => { function ThrowsInLayoutEffectDestroy() { Scheduler.log('ThrowsInLayoutEffectDestroy render'); React.useLayoutEffect(() => { Scheduler.log('ThrowsInLayoutEffectDestroy useLayoutEffect create'); return () => { Scheduler.log( 'ThrowsInLayoutEffectDestroy useLayoutEffect destroy', ); throw Error('expected'); }; }, []); return <span prop="ThrowsInLayoutEffectDestroy" />; } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> {children} <ThrowsInLayoutEffectDestroy /> <Text text="Inside" /> </Suspense> <Text text="Outside" /> </> ); } await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App /> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'ThrowsInLayoutEffectDestroy render', 'Text:Inside render', 'Text:Outside render', 'ThrowsInLayoutEffectDestroy useLayoutEffect create', 'Text:Inside create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInLayoutEffectDestroy" /> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Schedule an update that suspends and triggers our error code. await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App> <AsyncText text="Async" ms={1000} /> </App> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outside render', // Even though an error was thrown in useLayoutEffect destroy, // subsequent layout effects should still be destroyed. 'ThrowsInLayoutEffectDestroy useLayoutEffect destroy', 'Text:Inside destroy layout', // Finish the in-progress commit 'Text:Fallback create layout', 'Text:Fallback create passive', // Destroy layout and passive effects in the errored tree. 'App destroy layout', 'Text:Fallback destroy layout', 'Text:Outside destroy layout', 'Text:Inside destroy passive', 'Text:Fallback destroy passive', 'Text:Outside destroy passive', // Render fallback 'ErrorBoundary render: catch', 'Text:Error render', 'Text:Error create layout', 'Text:Error create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Error" />); }); }); // @gate enableLegacyCache it('should be only destroy layout effects once if a tree suspends in multiple places', async () => { class ClassText extends React.Component { componentDidMount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidMount`); } componentDidUpdate() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidUpdate`); } componentWillUnmount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentWillUnmount`); } render() { const {children, text} = this.props; Scheduler.log(`ClassText:${text} render`); return <span prop={text}>{children}</span>; } } function App({children = null}) { return ( <Suspense fallback={<ClassText text="Fallback" />}> <Text text="Function" /> {children} <ClassText text="Class" /> </Suspense> ); } await act(() => { ReactNoop.render(<App />); }); assertLog([ 'Text:Function render', 'ClassText:Class render', 'Text:Function create layout', 'ClassText:Class componentDidMount', 'Text:Function create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" /> <span prop="Class" /> </>, ); // Schedule an update that causes React to suspend. await act(async () => { ReactNoop.render( <App> <AsyncText text="Async_1" ms={1000} /> <AsyncText text="Async_2" ms={2000} /> </App>, ); await waitFor([ 'Text:Function render', 'Suspend:Async_1', 'ClassText:Fallback render', 'Text:Function destroy layout', 'ClassText:Class componentWillUnmount', 'ClassText:Fallback componentDidMount', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" hidden={true} /> <span prop="Class" hidden={true} /> <span prop="Fallback" /> </>, ); }); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async_1'); }); assertLog([ 'Text:Function render', 'AsyncText:Async_1 render', 'Suspend:Async_2', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" hidden={true} /> <span prop="Class" hidden={true} /> <span prop="Fallback" /> </>, ); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async_2'); }); assertLog([ 'Text:Function render', 'AsyncText:Async_1 render', 'AsyncText:Async_2 render', 'ClassText:Class render', 'ClassText:Fallback componentWillUnmount', 'Text:Function create layout', 'AsyncText:Async_1 create layout', 'AsyncText:Async_2 create layout', 'ClassText:Class componentDidMount', 'AsyncText:Async_1 create passive', 'AsyncText:Async_2 create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" /> <span prop="Async_1" /> <span prop="Async_2" /> <span prop="Class" /> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'Text:Function destroy layout', 'AsyncText:Async_1 destroy layout', 'AsyncText:Async_2 destroy layout', 'ClassText:Class componentWillUnmount', 'Text:Function destroy passive', 'AsyncText:Async_1 destroy passive', 'AsyncText:Async_2 destroy passive', ]); }); // @gate enableLegacyCache it('should be only destroy layout effects once if a component suspends multiple times', async () => { class ClassText extends React.Component { componentDidMount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidMount`); } componentDidUpdate() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentDidUpdate`); } componentWillUnmount() { const {text} = this.props; Scheduler.log(`ClassText:${text} componentWillUnmount`); } render() { const {children, text} = this.props; Scheduler.log(`ClassText:${text} render`); return <span prop={text}>{children}</span>; } } let textToRead = null; function Suspender() { Scheduler.log(`Suspender "${textToRead}" render`); if (textToRead !== null) { readText(textToRead); } return <span prop="Suspender" />; } function App({children = null}) { return ( <Suspense fallback={<ClassText text="Fallback" />}> <Text text="Function" /> <Suspender /> <ClassText text="Class" /> </Suspense> ); } await act(() => { ReactNoop.render(<App />); }); assertLog([ 'Text:Function render', 'Suspender "null" render', 'ClassText:Class render', 'Text:Function create layout', 'ClassText:Class componentDidMount', 'Text:Function create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" /> <span prop="Suspender" /> <span prop="Class" /> </>, ); // Schedule an update that causes React to suspend. textToRead = 'A'; await act(async () => { ReactNoop.render(<App />); await waitFor([ 'Text:Function render', 'Suspender "A" render', 'Suspend:A', 'ClassText:Fallback render', 'Text:Function destroy layout', 'ClassText:Class componentWillUnmount', 'ClassText:Fallback componentDidMount', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" hidden={true} /> <span prop="Suspender" hidden={true} /> <span prop="Class" hidden={true} /> <span prop="Fallback" /> </>, ); }); // Resolving the suspended resource should re-create inner layout effects. textToRead = 'B'; await act(async () => { await resolveText('A'); }); assertLog(['Text:Function render', 'Suspender "B" render', 'Suspend:B']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" hidden={true} /> <span prop="Suspender" hidden={true} /> <span prop="Class" hidden={true} /> <span prop="Fallback" /> </>, ); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('B'); }); assertLog([ 'Text:Function render', 'Suspender "B" render', 'ClassText:Class render', 'ClassText:Fallback componentWillUnmount', 'Text:Function create layout', 'ClassText:Class componentDidMount', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Function" /> <span prop="Suspender" /> <span prop="Class" /> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'Text:Function destroy layout', 'ClassText:Class componentWillUnmount', 'Text:Function destroy passive', ]); }); }); describe('refs within a tree that re-suspends in an update', () => { function RefCheckerOuter({Component}) { const refObject = React.useRef(null); const manualRef = React.useMemo(() => ({current: null}), []); const refCallback = React.useCallback(value => { Scheduler.log(`RefCheckerOuter refCallback value? ${value != null}`); manualRef.current = value; }, []); Scheduler.log(`RefCheckerOuter render`); React.useLayoutEffect(() => { Scheduler.log( `RefCheckerOuter create layout refObject? ${ refObject.current != null } refCallback? ${manualRef.current != null}`, ); return () => { Scheduler.log( `RefCheckerOuter destroy layout refObject? ${ refObject.current != null } refCallback? ${manualRef.current != null}`, ); }; }, []); return ( <> <Component ref={refObject} prop="refObject"> <RefCheckerInner forwardedRef={refObject} text="refObject" /> </Component> <Component ref={refCallback} prop="refCallback"> <RefCheckerInner forwardedRef={manualRef} text="refCallback" /> </Component> </> ); } function RefCheckerInner({forwardedRef, text}) { Scheduler.log(`RefCheckerInner:${text} render`); React.useLayoutEffect(() => { Scheduler.log( `RefCheckerInner:${text} create layout ref? ${ forwardedRef.current != null }`, ); return () => { Scheduler.log( `RefCheckerInner:${text} destroy layout ref? ${ forwardedRef.current != null }`, ); }; }, []); return null; } // @gate enableLegacyCache it('should not be cleared within legacy roots', async () => { class ClassComponent extends React.Component { render() { Scheduler.log(`ClassComponent:${this.props.prop} render`); return this.props.children; } } function App({children}) { Scheduler.log(`App render`); return ( <Suspense fallback={<Text text="Fallback" />}> {children} <RefCheckerOuter Component={ClassComponent} /> </Suspense> ); } await act(() => { ReactNoop.renderLegacySyncRoot(<App />); }); assertLog([ 'App render', 'RefCheckerOuter render', 'ClassComponent:refObject render', 'RefCheckerInner:refObject render', 'ClassComponent:refCallback render', 'RefCheckerInner:refCallback render', 'RefCheckerInner:refObject create layout ref? false', 'RefCheckerInner:refCallback create layout ref? false', 'RefCheckerOuter refCallback value? true', 'RefCheckerOuter create layout refObject? true refCallback? true', ]); expect(ReactNoop).toMatchRenderedOutput(null); // Suspend the inner Suspense subtree (only inner effects should be destroyed) await act(() => { ReactNoop.renderLegacySyncRoot( <App children={<AsyncText text="Async" ms={1000} />} />, ); }); await advanceTimers(1000); assertLog([ 'App render', 'Suspend:Async', 'RefCheckerOuter render', 'ClassComponent:refObject render', 'RefCheckerInner:refObject render', 'ClassComponent:refCallback render', 'RefCheckerInner:refCallback render', 'Text:Fallback render', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Fallback" />); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Async" />); await act(() => { ReactNoop.renderLegacySyncRoot(null); }); assertLog([ 'AsyncText:Async destroy layout', 'RefCheckerOuter destroy layout refObject? true refCallback? true', 'RefCheckerInner:refObject destroy layout ref? false', 'RefCheckerOuter refCallback value? false', 'RefCheckerInner:refCallback destroy layout ref? false', 'AsyncText:Async destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('should be cleared and reset for host components', async () => { function App({children}) { Scheduler.log(`App render`); return ( <Suspense fallback={<Text text="Fallback" />}> {children} <RefCheckerOuter Component="span" /> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'RefCheckerOuter render', 'RefCheckerInner:refObject render', 'RefCheckerInner:refCallback render', 'RefCheckerInner:refObject create layout ref? false', 'RefCheckerInner:refCallback create layout ref? false', 'RefCheckerOuter refCallback value? true', 'RefCheckerOuter create layout refObject? true refCallback? true', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="refObject" /> <span prop="refCallback" /> </>, ); // Suspend the inner Suspense subtree (only inner effects should be destroyed) await act(() => { ReactNoop.render( <App children={<AsyncText text="Async" ms={1000} />} />, ); }); await advanceTimers(1000); assertLog([ 'App render', 'Suspend:Async', 'Text:Fallback render', 'RefCheckerOuter destroy layout refObject? true refCallback? true', 'RefCheckerInner:refObject destroy layout ref? false', 'RefCheckerOuter refCallback value? false', 'RefCheckerInner:refCallback destroy layout ref? false', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="refObject" hidden={true} /> <span prop="refCallback" hidden={true} /> <span prop="Fallback" /> </>, ); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'RefCheckerOuter render', 'RefCheckerInner:refObject render', 'RefCheckerInner:refCallback render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'RefCheckerInner:refObject create layout ref? false', 'RefCheckerInner:refCallback create layout ref? false', 'RefCheckerOuter refCallback value? true', 'RefCheckerOuter create layout refObject? true refCallback? true', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Async" /> <span prop="refObject" /> <span prop="refCallback" /> </>, ); await act(() => { ReactNoop.render(null); }); assertLog([ 'AsyncText:Async destroy layout', 'RefCheckerOuter destroy layout refObject? true refCallback? true', 'RefCheckerInner:refObject destroy layout ref? false', 'RefCheckerOuter refCallback value? false', 'RefCheckerInner:refCallback destroy layout ref? false', 'AsyncText:Async destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('should be cleared and reset for class components', async () => { class ClassComponent extends React.Component { render() { Scheduler.log(`ClassComponent:${this.props.prop} render`); return this.props.children; } } function App({children}) { Scheduler.log(`App render`); return ( <Suspense fallback={<Text text="Fallback" />}> {children} <RefCheckerOuter Component={ClassComponent} /> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'RefCheckerOuter render', 'ClassComponent:refObject render', 'RefCheckerInner:refObject render', 'ClassComponent:refCallback render', 'RefCheckerInner:refCallback render', 'RefCheckerInner:refObject create layout ref? false', 'RefCheckerInner:refCallback create layout ref? false', 'RefCheckerOuter refCallback value? true', 'RefCheckerOuter create layout refObject? true refCallback? true', ]); expect(ReactNoop).toMatchRenderedOutput(null); // Suspend the inner Suspense subtree (only inner effects should be destroyed) await act(() => { ReactNoop.render( <App children={<AsyncText text="Async" ms={1000} />} />, ); }); await advanceTimers(1000); assertLog([ 'App render', 'Suspend:Async', 'Text:Fallback render', 'RefCheckerOuter destroy layout refObject? true refCallback? true', 'RefCheckerInner:refObject destroy layout ref? false', 'RefCheckerOuter refCallback value? false', 'RefCheckerInner:refCallback destroy layout ref? false', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Fallback" />); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'RefCheckerOuter render', 'ClassComponent:refObject render', 'RefCheckerInner:refObject render', 'ClassComponent:refCallback render', 'RefCheckerInner:refCallback render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'RefCheckerInner:refObject create layout ref? false', 'RefCheckerInner:refCallback create layout ref? false', 'RefCheckerOuter refCallback value? true', 'RefCheckerOuter create layout refObject? true refCallback? true', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Async" />); await act(() => { ReactNoop.render(null); }); assertLog([ 'AsyncText:Async destroy layout', 'RefCheckerOuter destroy layout refObject? true refCallback? true', 'RefCheckerInner:refObject destroy layout ref? false', 'RefCheckerOuter refCallback value? false', 'RefCheckerInner:refCallback destroy layout ref? false', 'AsyncText:Async destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('should be cleared and reset for function components with useImperativeHandle', async () => { const FunctionComponent = React.forwardRef((props, ref) => { Scheduler.log('FunctionComponent render'); React.useImperativeHandle( ref, () => ({ // Noop }), [], ); return props.children; }); FunctionComponent.displayName = 'FunctionComponent'; function App({children}) { Scheduler.log(`App render`); return ( <Suspense fallback={<Text text="Fallback" />}> {children} <RefCheckerOuter Component={FunctionComponent} /> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'RefCheckerOuter render', 'FunctionComponent render', 'RefCheckerInner:refObject render', 'FunctionComponent render', 'RefCheckerInner:refCallback render', 'RefCheckerInner:refObject create layout ref? false', 'RefCheckerInner:refCallback create layout ref? false', 'RefCheckerOuter refCallback value? true', 'RefCheckerOuter create layout refObject? true refCallback? true', ]); expect(ReactNoop).toMatchRenderedOutput(null); // Suspend the inner Suspense subtree (only inner effects should be destroyed) await act(() => { ReactNoop.render( <App children={<AsyncText text="Async" ms={1000} />} />, ); }); await advanceTimers(1000); assertLog([ 'App render', 'Suspend:Async', 'Text:Fallback render', 'RefCheckerOuter destroy layout refObject? true refCallback? true', 'RefCheckerInner:refObject destroy layout ref? false', 'RefCheckerOuter refCallback value? false', 'RefCheckerInner:refCallback destroy layout ref? false', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Fallback" />); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'RefCheckerOuter render', 'FunctionComponent render', 'RefCheckerInner:refObject render', 'FunctionComponent render', 'RefCheckerInner:refCallback render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'RefCheckerInner:refObject create layout ref? false', 'RefCheckerInner:refCallback create layout ref? false', 'RefCheckerOuter refCallback value? true', 'RefCheckerOuter create layout refObject? true refCallback? true', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Async" />); await act(() => { ReactNoop.render(null); }); assertLog([ 'AsyncText:Async destroy layout', 'RefCheckerOuter destroy layout refObject? true refCallback? true', 'RefCheckerInner:refObject destroy layout ref? false', 'RefCheckerOuter refCallback value? false', 'RefCheckerInner:refCallback destroy layout ref? false', 'AsyncText:Async destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('should not reset for user-managed values', async () => { function RefChecker({forwardedRef}) { Scheduler.log(`RefChecker render`); React.useLayoutEffect(() => { Scheduler.log( `RefChecker create layout ref? ${forwardedRef.current === 'test'}`, ); return () => { Scheduler.log( `RefChecker destroy layout ref? ${ forwardedRef.current === 'test' }`, ); }; }, []); return null; } function App({children = null}) { const ref = React.useRef('test'); Scheduler.log(`App render`); React.useLayoutEffect(() => { Scheduler.log(`App create layout ref? ${ref.current === 'test'}`); return () => { Scheduler.log(`App destroy layout ref? ${ref.current === 'test'}`); }; }, []); return ( <Suspense fallback={<Text text="Fallback" />}> {children} <RefChecker forwardedRef={ref} /> </Suspense> ); } // Mount await act(() => { ReactNoop.render(<App />); }); assertLog([ 'App render', 'RefChecker render', 'RefChecker create layout ref? true', 'App create layout ref? true', ]); expect(ReactNoop).toMatchRenderedOutput(null); // Suspend the inner Suspense subtree (only inner effects should be destroyed) await act(() => { ReactNoop.render( <App children={<AsyncText text="Async" ms={1000} />} />, ); }); await advanceTimers(1000); assertLog([ 'App render', 'Suspend:Async', 'Text:Fallback render', 'RefChecker destroy layout ref? true', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Fallback" />); // Resolving the suspended resource should re-create inner layout effects. await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'RefChecker render', 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'RefChecker create layout ref? true', 'Text:Fallback destroy passive', 'AsyncText:Async create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Async" />); await act(() => { ReactNoop.render(null); }); assertLog([ 'App destroy layout ref? true', 'AsyncText:Async destroy layout', 'RefChecker destroy layout ref? true', 'AsyncText:Async destroy passive', ]); expect(ReactNoop).toMatchRenderedOutput(null); }); describe('that throw errors', () => { // @gate enableLegacyCache // @gate replayFailedUnitOfWorkWithInvokeGuardedCallback it('are properly handled in ref callbacks', async () => { let useRefCallbackShouldThrow = false; function ThrowsInRefCallback() { Scheduler.log('ThrowsInRefCallback render'); const refCallback = React.useCallback(value => { Scheduler.log('ThrowsInRefCallback refCallback ref? ' + !!value); if (useRefCallbackShouldThrow) { throw Error('expected'); } }, []); return <span ref={refCallback} prop="ThrowsInRefCallback" />; } function App({children = null}) { Scheduler.log('App render'); React.useLayoutEffect(() => { Scheduler.log('App create layout'); return () => { Scheduler.log('App destroy layout'); }; }, []); return ( <> <Suspense fallback={<Text text="Fallback" />}> {children} <ThrowsInRefCallback /> <Text text="Inside" /> </Suspense> <Text text="Outside" /> </> ); } await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App /> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'ThrowsInRefCallback render', 'Text:Inside render', 'Text:Outside render', 'ThrowsInRefCallback refCallback ref? true', 'Text:Inside create layout', 'Text:Outside create layout', 'App create layout', 'Text:Inside create passive', 'Text:Outside create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInRefCallback" /> <span prop="Inside" /> <span prop="Outside" /> </>, ); // Schedule an update that causes React to suspend. await act(() => { ReactNoop.render( <ErrorBoundary fallback={<Text text="Error" />}> <App> <AsyncText text="Async" ms={1000} /> </App> </ErrorBoundary>, ); }); assertLog([ 'ErrorBoundary render: try', 'App render', 'Suspend:Async', 'Text:Fallback render', 'Text:Outside render', 'ThrowsInRefCallback refCallback ref? false', 'Text:Inside destroy layout', 'Text:Fallback create layout', 'Text:Fallback create passive', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="ThrowsInRefCallback" hidden={true} /> <span prop="Inside" hidden={true} /> <span prop="Fallback" /> <span prop="Outside" /> </>, ); // Resolve the pending suspense and throw useRefCallbackShouldThrow = true; await act(async () => { await resolveText('Async'); }); assertLog([ 'AsyncText:Async render', 'ThrowsInRefCallback render', 'Text:Inside render', // Even though an error was thrown in refCallback, // subsequent layout effects should still be created. 'Text:Fallback destroy layout', 'AsyncText:Async create layout', 'ThrowsInRefCallback refCallback ref? true', 'Text:Inside create layout', // Finish the in-progress commit 'Text:Fallback destroy passive', 'AsyncText:Async create passive', // Destroy layout and passive effects in the errored tree. 'App destroy layout', 'AsyncText:Async destroy layout', 'ThrowsInRefCallback refCallback ref? false', 'Text:Inside destroy layout', 'Text:Outside destroy layout', 'AsyncText:Async destroy passive', 'Text:Inside destroy passive', 'Text:Outside destroy passive', // Render fallback 'ErrorBoundary render: catch', 'Text:Error render', 'Text:Error create layout', 'Text:Error create passive', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Error" />); }); }); }); });
30.539829
107
0.538725
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 {SchedulingEvent} from '../types'; export function isStateUpdateEvent(event: SchedulingEvent): boolean %checks { return event.type === 'schedule-state-update'; }
26.214286
77
0.718421
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 {CacheDispatcher} from 'react-reconciler/src/ReactInternalTypes'; /** * Keeps track of the current Cache dispatcher. */ const ReactCurrentCache = { current: (null: null | CacheDispatcher), }; export default ReactCurrentCache;
21.45
77
0.723214
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 */ // Renderers that don't support test selectors // can re-export everything from this module. function shim(...args: any): empty { throw new Error( 'The current renderer does not support test selectors. ' + 'This error is likely caused by a bug in React. ' + 'Please file an issue.', ); } // Test selectors (when unsupported) export const supportsTestSelectors = false; export const findFiberRoot = shim; export const getBoundingRect = shim; export const getTextContent = shim; export const isHiddenSubtree = shim; export const matchAccessibilityRole = shim; export const setFocusIfFocusable = shim; export const setupIntersectionObserver = shim;
28.1
66
0.733945
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 {Writable} from 'stream'; import {TextEncoder} from 'util'; import {createHash} from 'crypto'; interface MightBeFlushable { flush?: () => void; } export type Destination = Writable & MightBeFlushable; export type PrecomputedChunk = Uint8Array; export opaque type Chunk = string; export type BinaryChunk = Uint8Array; export function scheduleWork(callback: () => void) { setImmediate(callback); } export function flushBuffered(destination: Destination) { // If we don't have any more data to send right now. // Flush whatever is in the buffer to the wire. if (typeof destination.flush === 'function') { // By convention the Zlib streams provide a flush function for this purpose. // For Express, compression middleware adds this method. destination.flush(); } } const VIEW_SIZE = 2048; let currentView = null; let writtenBytes = 0; let destinationHasCapacity = true; export function beginWriting(destination: Destination) { currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; destinationHasCapacity = true; } function writeStringChunk(destination: Destination, stringChunk: string) { if (stringChunk.length === 0) { return; } // maximum possible view needed to encode entire string if (stringChunk.length * 3 > VIEW_SIZE) { if (writtenBytes > 0) { writeToDestination( destination, ((currentView: any): Uint8Array).subarray(0, writtenBytes), ); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } writeToDestination(destination, textEncoder.encode(stringChunk)); return; } let target: Uint8Array = (currentView: any); if (writtenBytes > 0) { target = ((currentView: any): Uint8Array).subarray(writtenBytes); } const {read, written} = textEncoder.encodeInto(stringChunk, target); writtenBytes += written; if (read < stringChunk.length) { writeToDestination( destination, (currentView: any).subarray(0, writtenBytes), ); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = textEncoder.encodeInto( stringChunk.slice(read), (currentView: any), ).written; } if (writtenBytes === VIEW_SIZE) { writeToDestination(destination, (currentView: any)); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } } function writeViewChunk( destination: Destination, chunk: PrecomputedChunk | BinaryChunk, ) { if (chunk.byteLength === 0) { return; } if (chunk.byteLength > VIEW_SIZE) { if (__DEV__) { if (precomputedChunkSet && precomputedChunkSet.has(chunk)) { console.error( 'A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.', ); } } // this chunk may overflow a single view which implies it was not // one that is cached by the streaming renderer. We will enqueu // it directly and expect it is not re-used if (writtenBytes > 0) { writeToDestination( destination, ((currentView: any): Uint8Array).subarray(0, writtenBytes), ); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } writeToDestination(destination, chunk); return; } let bytesToWrite = chunk; const allowableBytes = ((currentView: any): Uint8Array).length - writtenBytes; if (allowableBytes < bytesToWrite.byteLength) { // this chunk would overflow the current view. We enqueue a full view // and start a new view with the remaining chunk if (allowableBytes === 0) { // the current view is already full, send it writeToDestination(destination, (currentView: any)); } else { // fill up the current view and apply the remaining chunk bytes // to a new view. ((currentView: any): Uint8Array).set( bytesToWrite.subarray(0, allowableBytes), writtenBytes, ); writtenBytes += allowableBytes; writeToDestination(destination, (currentView: any)); bytesToWrite = bytesToWrite.subarray(allowableBytes); } currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } ((currentView: any): Uint8Array).set(bytesToWrite, writtenBytes); writtenBytes += bytesToWrite.byteLength; if (writtenBytes === VIEW_SIZE) { writeToDestination(destination, (currentView: any)); currentView = new Uint8Array(VIEW_SIZE); writtenBytes = 0; } } export function writeChunk( destination: Destination, chunk: PrecomputedChunk | Chunk | BinaryChunk, ): void { if (typeof chunk === 'string') { writeStringChunk(destination, chunk); } else { writeViewChunk(destination, ((chunk: any): PrecomputedChunk | BinaryChunk)); } } function writeToDestination( destination: Destination, view: string | Uint8Array, ) { const currentHasCapacity = destination.write(view); destinationHasCapacity = destinationHasCapacity && currentHasCapacity; } export function writeChunkAndReturn( destination: Destination, chunk: PrecomputedChunk | Chunk, ): boolean { writeChunk(destination, chunk); return destinationHasCapacity; } export function completeWriting(destination: Destination) { if (currentView && writtenBytes > 0) { destination.write(currentView.subarray(0, writtenBytes)); } currentView = null; writtenBytes = 0; destinationHasCapacity = true; } export function close(destination: Destination) { destination.end(); } const textEncoder = new TextEncoder(); export function stringToChunk(content: string): Chunk { return content; } const precomputedChunkSet = __DEV__ ? new Set<PrecomputedChunk>() : null; export function stringToPrecomputedChunk(content: string): PrecomputedChunk { const precomputedChunk = textEncoder.encode(content); if (__DEV__) { if (precomputedChunkSet) { precomputedChunkSet.add(precomputedChunk); } } return precomputedChunk; } export function typedArrayToBinaryChunk( content: $ArrayBufferView, ): BinaryChunk { // Convert any non-Uint8Array array to Uint8Array. We could avoid this for Uint8Arrays. return new Uint8Array(content.buffer, content.byteOffset, content.byteLength); } export function clonePrecomputedChunk( precomputedChunk: PrecomputedChunk, ): PrecomputedChunk { return precomputedChunk.length > VIEW_SIZE ? precomputedChunk.slice() : precomputedChunk; } export function byteLengthOfChunk(chunk: Chunk | PrecomputedChunk): number { return typeof chunk === 'string' ? Buffer.byteLength(chunk, 'utf8') : chunk.byteLength; } export function byteLengthOfBinaryChunk(chunk: BinaryChunk): number { return chunk.byteLength; } export function closeWithError(destination: Destination, error: mixed): void { // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. destination.destroy(error); } export function createFastHash(input: string): string | number { const hash = createHash('md5'); hash.update(input); return hash.digest('hex'); }
28.513834
177
0.704125
owtf
'use client'; var React = require('react'); function Note() { return 'This component was exported on a commonJS module and imported into ESM as a named import.'; } module.exports = { Note, };
15.666667
101
0.688442
null
#!/usr/bin/env node 'use strict'; const {readFileSync, writeFileSync} = require('fs'); const {readJson, writeJson} = require('fs-extra'); const {join} = require('path'); const run = async ({cwd, packages, skipPackages, tags}) => { if (!tags.includes('latest')) { // Don't update version numbers for alphas. return; } const nodeModulesPath = join(cwd, 'build/node_modules'); const packagesPath = join(cwd, 'packages'); // Update package versions and dependencies (in source) to mirror what was published to NPM. for (let i = 0; i < packages.length; i++) { const packageName = packages[i]; const publishedPackageJSON = await readJson( join(nodeModulesPath, packageName, 'package.json') ); const sourcePackageJSONPath = join( packagesPath, packageName, 'package.json' ); const sourcePackageJSON = await readJson(sourcePackageJSONPath); sourcePackageJSON.version = publishedPackageJSON.version; sourcePackageJSON.dependencies = publishedPackageJSON.dependencies; sourcePackageJSON.peerDependencies = publishedPackageJSON.peerDependencies; await writeJson(sourcePackageJSONPath, sourcePackageJSON, {spaces: 2}); } // Update the shared React version source file. // (Unless this release does not include an update to React) if (!skipPackages.includes('react')) { const sourceReactVersionPath = join(cwd, 'packages/shared/ReactVersion.js'); const {version} = await readJson( join(nodeModulesPath, 'react', 'package.json') ); const sourceReactVersion = readFileSync( sourceReactVersionPath, 'utf8' ).replace(/export default '[^']+';/, `export default '${version}';`); writeFileSync(sourceReactVersionPath, sourceReactVersion); } }; module.exports = run;
32.792453
94
0.700559
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 './ReactSharedSubset'; export {jsx, jsxs, jsxDEV} from './jsx/ReactJSX';
23.333333
66
0.690722
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 { Request, PostponedState, ErrorInfo, PostponeInfo, } from 'react-server/src/ReactFizzServer'; import type {ReactNodeList, ReactFormState} from 'shared/ReactTypes'; import type {Writable} from 'stream'; import type { BootstrapScriptDescriptor, HeadersDescriptor, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; import type {Destination} from 'react-server/src/ReactServerStreamConfigNode'; import type {ImportMap} from '../shared/ReactDOMTypes'; import ReactVersion from 'shared/ReactVersion'; import { createRequest, resumeRequest, startWork, startFlowing, stopFlowing, abort, prepareForStartFlowingIfBeforeAllReady, } from 'react-server/src/ReactFizzServer'; import { createResumableState, createRenderState, resumeRenderState, createRootFormatContext, } from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; function createDrainHandler(destination: Destination, request: Request) { return () => startFlowing(request, destination); } function createCancelHandler(request: Request, reason: string) { return () => { stopFlowing(request); // eslint-disable-next-line react-internal/prod-error-codes abort(request, new Error(reason)); }; } type Options = { identifierPrefix?: string, namespaceURI?: string, nonce?: string, bootstrapScriptContent?: string, bootstrapScripts?: Array<string | BootstrapScriptDescriptor>, bootstrapModules?: Array<string | BootstrapScriptDescriptor>, progressiveChunkSize?: number, onShellReady?: () => void, onShellError?: (error: mixed) => void, onAllReady?: () => void, onError?: (error: mixed, errorInfo: ErrorInfo) => ?string, onPostpone?: (reason: string, postponeInfo: PostponeInfo) => void, unstable_externalRuntimeSrc?: string | BootstrapScriptDescriptor, importMap?: ImportMap, formState?: ReactFormState<any, any> | null, onHeaders?: (headers: HeadersDescriptor) => void, maxHeadersLength?: number, }; type ResumeOptions = { nonce?: string, onShellReady?: () => void, onShellError?: (error: mixed) => void, onAllReady?: () => void, onError?: (error: mixed, errorInfo: ErrorInfo) => ?string, onPostpone?: (reason: string, postponeInfo: PostponeInfo) => void, }; type PipeableStream = { // Cancel any pending I/O and put anything remaining into // client rendered mode. abort(reason: mixed): void, pipe<T: Writable>(destination: T): T, }; function createRequestImpl(children: ReactNodeList, options: void | Options) { const resumableState = createResumableState( options ? options.identifierPrefix : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined, ); return createRequest( children, resumableState, createRenderState( resumableState, options ? options.nonce : undefined, options ? options.unstable_externalRuntimeSrc : undefined, options ? options.importMap : undefined, options ? options.onHeaders : undefined, options ? options.maxHeadersLength : undefined, ), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, options ? options.onAllReady : undefined, options ? options.onShellReady : undefined, options ? options.onShellError : undefined, undefined, options ? options.onPostpone : undefined, options ? options.formState : undefined, ); } function renderToPipeableStream( children: ReactNodeList, options?: Options, ): PipeableStream { const request = createRequestImpl(children, options); 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; prepareForStartFlowingIfBeforeAllReady(request); startFlowing(request, destination); destination.on('drain', createDrainHandler(destination, request)); destination.on( 'error', createCancelHandler( request, 'The destination stream errored while writing data.', ), ); destination.on( 'close', createCancelHandler(request, 'The destination stream closed early.'), ); return destination; }, abort(reason: mixed) { abort(request, reason); }, }; } function resumeRequestImpl( children: ReactNodeList, postponedState: PostponedState, options: void | ResumeOptions, ) { return resumeRequest( children, postponedState, resumeRenderState( postponedState.resumableState, options ? options.nonce : undefined, ), options ? options.onError : undefined, options ? options.onAllReady : undefined, options ? options.onShellReady : undefined, options ? options.onShellError : undefined, undefined, options ? options.onPostpone : undefined, ); } function resumeToPipeableStream( children: ReactNodeList, postponedState: PostponedState, options?: ResumeOptions, ): PipeableStream { const request = resumeRequestImpl(children, postponedState, options); let hasStartedFlowing = false; startWork(request); return { pipe<T: Writable>(destination: T): T { if (hasStartedFlowing) { throw new Error( 'React currently only supports piping to one writable stream.', ); } hasStartedFlowing = true; startFlowing(request, destination); destination.on('drain', createDrainHandler(destination, request)); destination.on( 'error', createCancelHandler( request, 'The destination stream errored while writing data.', ), ); destination.on( 'close', createCancelHandler(request, 'The destination stream closed early.'), ); return destination; }, abort(reason: mixed) { abort(request, reason); }, }; } export { renderToPipeableStream, resumeToPipeableStream, ReactVersion as version, };
28.152466
78
0.697077
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 './static.node';
20.454545
66
0.680851
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type { CurrentDispatcherRef, ReactRenderer, WorkTagMap, ConsolePatchSettings, } from './types'; import {format, formatWithStyles} from './utils'; import {getInternalReactConstants} from './renderer'; import {getStackByFiberInDevAndProd} from './DevToolsFiberComponentStack'; import {consoleManagedByDevToolsDuringStrictMode} from 'react-devtools-feature-flags'; import {castBool, castBrowserTheme} from '../utils'; const OVERRIDE_CONSOLE_METHODS = ['error', 'trace', 'warn']; const DIMMED_NODE_CONSOLE_COLOR = '\x1b[2m%s\x1b[0m'; // React's custom built component stack strings match "\s{4}in" // Chrome's prefix matches "\s{4}at" const PREFIX_REGEX = /\s{4}(in|at)\s{1}/; // Firefox and Safari have no prefix ("") // but we can fallback to looking for location info (e.g. "foo.js:12:345") const ROW_COLUMN_NUMBER_REGEX = /:\d+:\d+(\n|$)/; export function isStringComponentStack(text: string): boolean { return PREFIX_REGEX.test(text) || ROW_COLUMN_NUMBER_REGEX.test(text); } const STYLE_DIRECTIVE_REGEX = /^%c/; // This function tells whether or not the arguments for a console // method has been overridden by the patchForStrictMode function. // If it has we'll need to do some special formatting of the arguments // so the console color stays consistent function isStrictModeOverride(args: Array<string>, method: string): boolean { return ( args.length >= 2 && STYLE_DIRECTIVE_REGEX.test(args[0]) && args[1] === `color: ${getConsoleColor(method) || ''}` ); } function getConsoleColor(method: string): ?string { switch (method) { case 'warn': return consoleSettingsRef.browserTheme === 'light' ? process.env.LIGHT_MODE_DIMMED_WARNING_COLOR : process.env.DARK_MODE_DIMMED_WARNING_COLOR; case 'error': return consoleSettingsRef.browserTheme === 'light' ? process.env.LIGHT_MODE_DIMMED_ERROR_COLOR : process.env.DARK_MODE_DIMMED_ERROR_COLOR; case 'log': default: return consoleSettingsRef.browserTheme === 'light' ? process.env.LIGHT_MODE_DIMMED_LOG_COLOR : process.env.DARK_MODE_DIMMED_LOG_COLOR; } } type OnErrorOrWarning = ( fiber: Fiber, type: 'error' | 'warn', args: Array<any>, ) => void; const injectedRenderers: Map< ReactRenderer, { currentDispatcherRef: CurrentDispatcherRef, getCurrentFiber: () => Fiber | null, onErrorOrWarning: ?OnErrorOrWarning, workTagMap: WorkTagMap, }, > = new Map(); let targetConsole: Object = console; let targetConsoleMethods: {[string]: $FlowFixMe} = {}; for (const method in console) { targetConsoleMethods[method] = console[method]; } let unpatchFn: null | (() => void) = null; let isNode = false; try { isNode = this === global; } catch (error) {} // Enables e.g. Jest tests to inject a mock console object. export function dangerous_setTargetConsoleForTesting( targetConsoleForTesting: Object, ): void { targetConsole = targetConsoleForTesting; targetConsoleMethods = ({}: {[string]: $FlowFixMe}); for (const method in targetConsole) { targetConsoleMethods[method] = console[method]; } } // v16 renderers should use this method to inject internals necessary to generate a component stack. // These internals will be used if the console is patched. // Injecting them separately allows the console to easily be patched or un-patched later (at runtime). export function registerRenderer( renderer: ReactRenderer, onErrorOrWarning?: OnErrorOrWarning, ): void { const { currentDispatcherRef, getCurrentFiber, findFiberByHostInstance, version, } = renderer; // Ignore React v15 and older because they don't expose a component stack anyway. if (typeof findFiberByHostInstance !== 'function') { return; } // currentDispatcherRef gets injected for v16.8+ to support hooks inspection. // getCurrentFiber gets injected for v16.9+. if (currentDispatcherRef != null && typeof getCurrentFiber === 'function') { const {ReactTypeOfWork} = getInternalReactConstants(version); injectedRenderers.set(renderer, { currentDispatcherRef, getCurrentFiber, workTagMap: ReactTypeOfWork, onErrorOrWarning, }); } } const consoleSettingsRef: ConsolePatchSettings = { appendComponentStack: false, breakOnConsoleErrors: false, showInlineWarningsAndErrors: false, hideConsoleLogsInStrictMode: false, browserTheme: 'dark', }; // Patches console methods to append component stack for the current fiber. // Call unpatch() to remove the injected behavior. export function patch({ appendComponentStack, breakOnConsoleErrors, showInlineWarningsAndErrors, hideConsoleLogsInStrictMode, browserTheme, }: ConsolePatchSettings): void { // Settings may change after we've patched the console. // Using a shared ref allows the patch function to read the latest values. consoleSettingsRef.appendComponentStack = appendComponentStack; consoleSettingsRef.breakOnConsoleErrors = breakOnConsoleErrors; consoleSettingsRef.showInlineWarningsAndErrors = showInlineWarningsAndErrors; consoleSettingsRef.hideConsoleLogsInStrictMode = hideConsoleLogsInStrictMode; consoleSettingsRef.browserTheme = browserTheme; if ( appendComponentStack || breakOnConsoleErrors || showInlineWarningsAndErrors ) { if (unpatchFn !== null) { // Don't patch twice. return; } const originalConsoleMethods: {[string]: $FlowFixMe} = {}; unpatchFn = () => { for (const method in originalConsoleMethods) { try { targetConsole[method] = originalConsoleMethods[method]; } catch (error) {} } }; OVERRIDE_CONSOLE_METHODS.forEach(method => { try { const originalMethod = (originalConsoleMethods[method] = targetConsole[ method ].__REACT_DEVTOOLS_ORIGINAL_METHOD__ ? targetConsole[method].__REACT_DEVTOOLS_ORIGINAL_METHOD__ : targetConsole[method]); // $FlowFixMe[missing-local-annot] const overrideMethod = (...args) => { let shouldAppendWarningStack = false; if (method !== 'log') { if (consoleSettingsRef.appendComponentStack) { const lastArg = args.length > 0 ? args[args.length - 1] : null; const alreadyHasComponentStack = typeof lastArg === 'string' && isStringComponentStack(lastArg); // If we are ever called with a string that already has a component stack, // e.g. a React error/warning, don't append a second stack. shouldAppendWarningStack = !alreadyHasComponentStack; } } const shouldShowInlineWarningsAndErrors = consoleSettingsRef.showInlineWarningsAndErrors && (method === 'error' || method === 'warn'); // Search for the first renderer that has a current Fiber. // We don't handle the edge case of stacks for more than one (e.g. interleaved renderers?) // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const { currentDispatcherRef, getCurrentFiber, onErrorOrWarning, workTagMap, } of injectedRenderers.values()) { const current: ?Fiber = getCurrentFiber(); if (current != null) { try { if (shouldShowInlineWarningsAndErrors) { // patch() is called by two places: (1) the hook and (2) the renderer backend. // The backend is what implements a message queue, so it's the only one that injects onErrorOrWarning. if (typeof onErrorOrWarning === 'function') { onErrorOrWarning( current, ((method: any): 'error' | 'warn'), // Copy args before we mutate them (e.g. adding the component stack) args.slice(), ); } } if (shouldAppendWarningStack) { const componentStack = getStackByFiberInDevAndProd( workTagMap, current, currentDispatcherRef, ); if (componentStack !== '') { if (isStrictModeOverride(args, method)) { args[0] = `${args[0]} %s`; args.push(componentStack); } else { args.push(componentStack); } } } } catch (error) { // Don't let a DevTools or React internal error interfere with logging. setTimeout(() => { throw error; }, 0); } finally { break; } } } if (consoleSettingsRef.breakOnConsoleErrors) { // --- Welcome to debugging with React DevTools --- // This debugger statement means that you've enabled the "break on warnings" feature. // Use the browser's Call Stack panel to step out of this override function- // to where the original warning or error was logged. // eslint-disable-next-line no-debugger debugger; } originalMethod(...args); }; overrideMethod.__REACT_DEVTOOLS_ORIGINAL_METHOD__ = originalMethod; originalMethod.__REACT_DEVTOOLS_OVERRIDE_METHOD__ = overrideMethod; targetConsole[method] = overrideMethod; } catch (error) {} }); } else { unpatch(); } } // Removed component stack patch from console methods. export function unpatch(): void { if (unpatchFn !== null) { unpatchFn(); unpatchFn = null; } } let unpatchForStrictModeFn: null | (() => void) = null; // NOTE: KEEP IN SYNC with src/hook.js:patchConsoleForInitialRenderInStrictMode export function patchForStrictMode() { if (consoleManagedByDevToolsDuringStrictMode) { const overrideConsoleMethods = [ 'error', 'group', 'groupCollapsed', 'info', 'log', 'trace', 'warn', ]; if (unpatchForStrictModeFn !== null) { // Don't patch twice. return; } const originalConsoleMethods: {[string]: $FlowFixMe} = {}; unpatchForStrictModeFn = () => { for (const method in originalConsoleMethods) { try { targetConsole[method] = originalConsoleMethods[method]; } catch (error) {} } }; overrideConsoleMethods.forEach(method => { try { const originalMethod = (originalConsoleMethods[method] = targetConsole[ method ].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ ? targetConsole[method].__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ : targetConsole[method]); // $FlowFixMe[missing-local-annot] const overrideMethod = (...args) => { if (!consoleSettingsRef.hideConsoleLogsInStrictMode) { // Dim the text color of the double logs if we're not // hiding them. if (isNode) { originalMethod(DIMMED_NODE_CONSOLE_COLOR, format(...args)); } else { const color = getConsoleColor(method); if (color) { originalMethod(...formatWithStyles(args, `color: ${color}`)); } else { throw Error('Console color is not defined'); } } } }; overrideMethod.__REACT_DEVTOOLS_STRICT_MODE_ORIGINAL_METHOD__ = originalMethod; originalMethod.__REACT_DEVTOOLS_STRICT_MODE_OVERRIDE_METHOD__ = overrideMethod; targetConsole[method] = overrideMethod; } catch (error) {} }); } } // NOTE: KEEP IN SYNC with src/hook.js:unpatchConsoleForInitialRenderInStrictMode export function unpatchForStrictMode(): void { if (consoleManagedByDevToolsDuringStrictMode) { if (unpatchForStrictModeFn !== null) { unpatchForStrictModeFn(); unpatchForStrictModeFn = null; } } } export function patchConsoleUsingWindowValues() { const appendComponentStack = castBool(window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__) ?? true; const breakOnConsoleErrors = castBool(window.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__) ?? false; const showInlineWarningsAndErrors = castBool(window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__) ?? true; const hideConsoleLogsInStrictMode = castBool(window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__) ?? false; const browserTheme = castBrowserTheme(window.__REACT_DEVTOOLS_BROWSER_THEME__) ?? 'dark'; patch({ appendComponentStack, breakOnConsoleErrors, showInlineWarningsAndErrors, hideConsoleLogsInStrictMode, browserTheme, }); } // After receiving cached console patch settings from React Native, we set them on window. // When the console is initially patched (in renderer.js and hook.js), these values are read. // The browser extension (etc.) sets these values on window, but through another method. export function writeConsolePatchSettingsToWindow( settings: ConsolePatchSettings, ): void { window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = settings.appendComponentStack; window.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = settings.breakOnConsoleErrors; window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = settings.showInlineWarningsAndErrors; window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = settings.hideConsoleLogsInStrictMode; window.__REACT_DEVTOOLS_BROWSER_THEME__ = settings.browserTheme; } export function installConsoleFunctionsToWindow(): void { window.__REACT_DEVTOOLS_CONSOLE_FUNCTIONS__ = { patchConsoleUsingWindowValues, registerRendererWithConsole: registerRenderer, }; }
32.926014
120
0.644716
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'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; global.TextDecoder = require('util').TextDecoder; // Don't wait before processing work on the server. // TODO: we can replace this with FlightServer.act(). global.setImmediate = cb => cb(); let act; let use; let clientExports; let moduleMap; let React; let ReactDOMClient; let ReactServerDOMServer; let ReactServerDOMClient; let Suspense; class Destination { #buffer = ''; #controller = null; constructor() { const self = this; this.stream = new ReadableStream({ start(controller) { self.#controller = controller; }, }); } write(chunk) { this.#buffer += chunk; } beginWriting() {} completeWriting() {} flushBuffered() { if (!this.#controller) { throw new Error('Expected a controller.'); } this.#controller.enqueue(this.#buffer); this.#buffer = ''; } close() {} onError() {} } class ClientReferenceImpl { constructor(moduleId) { this.moduleId = moduleId; } getModuleId() { return this.moduleId; } } describe('ReactFlightDOM for FB', () => { beforeEach(() => { // For this first reset we are going to load the dom-node version of react-server-dom-turbopack/server // This can be thought of as essentially being the React Server Components scope with react-server // condition jest.resetModules(); jest.mock('react', () => require('react/src/ReactSharedSubsetFB')); jest.mock('shared/ReactFeatureFlags', () => { jest.mock( 'ReactFeatureFlags', () => jest.requireActual('shared/forks/ReactFeatureFlags.www-dynamic'), {virtual: true}, ); return jest.requireActual('shared/forks/ReactFeatureFlags.www'); }); clientExports = value => { return new ClientReferenceImpl(value.name); }; moduleMap = { resolveClientReference(metadata) { throw new Error('Do not expect to load client components.'); }, }; ReactServerDOMServer = require('../ReactFlightDOMServerFB'); ReactServerDOMServer.setConfig({ byteLength: str => Buffer.byteLength(str), isClientReference: reference => reference instanceof ClientReferenceImpl, }); // This reset is to load modules for the SSR/Browser scope. jest.resetModules(); __unmockReact(); act = require('internal-test-utils').act; React = require('react'); use = React.use; Suspense = React.Suspense; ReactDOMClient = require('react-dom/client'); ReactServerDOMClient = require('../ReactFlightDOMClientFB'); }); it('should resolve HTML with renderToDestination', async () => { function Text({children}) { return <span>{children}</span>; } function HTML() { return ( <div> <Text>hello</Text> <Text>world</Text> </div> ); } function App() { const model = { html: <HTML />, }; return model; } const destination = new Destination(); ReactServerDOMServer.renderToDestination(destination, <App />); const response = ReactServerDOMClient.createFromReadableStream( destination.stream, { moduleMap, }, ); const model = await response; expect(model).toEqual({ html: ( <div> <span>hello</span> <span>world</span> </div> ), }); }); it('should resolve the root', async () => { // Model function Text({children}) { return <span>{children}</span>; } function HTML() { return ( <div> <Text>hello</Text> <Text>world</Text> </div> ); } function RootModel() { return { html: <HTML />, }; } // View function Message({response}) { return <section>{use(response).html}</section>; } function App({response}) { return ( <Suspense fallback={<h1>Loading...</h1>}> <Message response={response} /> </Suspense> ); } const destination = new Destination(); ReactServerDOMServer.renderToDestination(destination, <RootModel />); const response = ReactServerDOMClient.createFromReadableStream( destination.stream, { moduleMap, }, ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App response={response} />); }); expect(container.innerHTML).toBe( '<section><div><span>hello</span><span>world</span></div></section>', ); }); it('should not get confused by $', async () => { // Model function RootModel() { return {text: '$1'}; } // View function Message({response}) { return <p>{use(response).text}</p>; } function App({response}) { return ( <Suspense fallback={<h1>Loading...</h1>}> <Message response={response} /> </Suspense> ); } const destination = new Destination(); ReactServerDOMServer.renderToDestination(destination, <RootModel />); const response = ReactServerDOMClient.createFromReadableStream( destination.stream, { moduleMap, }, ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App response={response} />); }); expect(container.innerHTML).toBe('<p>$1</p>'); }); it('should not get confused by @', async () => { // Model function RootModel() { return {text: '@div'}; } // View function Message({response}) { return <p>{use(response).text}</p>; } function App({response}) { return ( <Suspense fallback={<h1>Loading...</h1>}> <Message response={response} /> </Suspense> ); } const destination = new Destination(); ReactServerDOMServer.renderToDestination(destination, <RootModel />); const response = ReactServerDOMClient.createFromReadableStream( destination.stream, { moduleMap, }, ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App response={response} />); }); expect(container.innerHTML).toBe('<p>@div</p>'); }); it('should be able to render a client component', async () => { const Component = function ({greeting}) { return greeting + ' World'; }; function Print({response}) { return <p>{use(response)}</p>; } function App({response}) { return ( <Suspense fallback={<h1>Loading...</h1>}> <Print response={response} /> </Suspense> ); } const ClientComponent = clientExports(Component); const destination = new Destination(); ReactServerDOMServer.renderToDestination( destination, <ClientComponent greeting={'Hello'} />, moduleMap, ); const response = ReactServerDOMClient.createFromReadableStream( destination.stream, { moduleMap: { resolveClientReference(metadata) { return { getModuleId() { return metadata.moduleId; }, load() { return Promise.resolve(Component); }, }; }, }, }, ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App response={response} />); }); expect(container.innerHTML).toBe('<p>Hello World</p>'); }); it('should render long strings', async () => { // Model const longString = 'Lorem Ipsum ❤️ '.repeat(100); function RootModel() { return {text: longString}; } // View function Message({response}) { return <p>{use(response).text}</p>; } function App({response}) { return ( <Suspense fallback={<h1>Loading...</h1>}> <Message response={response} /> </Suspense> ); } const destination = new Destination(); ReactServerDOMServer.renderToDestination(destination, <RootModel />); const response = ReactServerDOMClient.createFromReadableStream( destination.stream, { moduleMap, }, ); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App response={response} />); }); expect(container.innerHTML).toBe('<p>' + longString + '</p>'); }); // TODO: `registerClientComponent` need to be able to support this it.skip('throws when accessing a member below the client exports', () => { const ClientModule = clientExports({ Component: {deep: 'thing'}, }); function dotting() { return ClientModule.Component.deep; } expect(dotting).toThrowError( 'Cannot access Component.deep on the server. ' + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.', ); }); });
24.680108
106
0.594849
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 */ // These tests are based on ReactJSXElement-test, // ReactJSXElementValidator-test, ReactComponent-test, // and ReactElementJSX-test. jest.mock('react/jsx-runtime', () => require('./jsx-runtime'), {virtual: true}); jest.mock('react/jsx-dev-runtime', () => require('./jsx-dev-runtime'), { virtual: true, }); let React = require('react'); let ReactDOM = require('react-dom'); let ReactTestUtils = { renderIntoDocument(el) { const container = document.createElement('div'); return ReactDOM.render(el, container); }, }; let PropTypes = require('prop-types'); let Component = class Component extends React.Component { render() { return <div />; } }; let RequiredPropComponent = class extends React.Component { render() { return <span>{this.props.prop}</span>; } }; RequiredPropComponent.displayName = 'RequiredPropComponent'; RequiredPropComponent.propTypes = {prop: PropTypes.string.isRequired}; it('works', () => { const container = document.createElement('div'); ReactDOM.render(<h1>hello</h1>, container); expect(container.textContent).toBe('hello'); }); 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 (process.env.NODE_ENV === 'development') { 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 element = <Component key="12" ref="34" foo="56" />; expect(element.type).toBe(Component); expect(element.key).toBe('12'); expect(element.ref).toBe('34'); 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 container = document.createElement('div'); const instance = ReactDOM.render(<NormalizingComponent />, container); expect(instance.props.prop).toBe('testKey'); const inst2 = ReactDOM.render( <NormalizingComponent prop={null} />, container ); expect(inst2.props.prop).toBe(null); }); it('warns for keys for arrays of elements in children position', () => { expect(() => ReactTestUtils.renderIntoDocument( <Component>{[<Component />, <Component />]}</Component> ) ).toErrorDev('Each child in a list should have a unique "key" prop.'); }); it('warns for keys for arrays of elements with owner info', () => { class InnerComponent extends React.Component { render() { return <Component>{this.props.childSet}</Component>; } } class ComponentWrapper extends React.Component { render() { return <InnerComponent childSet={[<Component />, <Component />]} />; } } expect(() => ReactTestUtils.renderIntoDocument(<ComponentWrapper />) ).toErrorDev( 'Each child in a list should have a unique "key" prop.' + '\n\nCheck the render method of `InnerComponent`. ' + 'It was passed a child from ComponentWrapper. ' ); }); it('does not warn for arrays of elements with keys', () => { ReactTestUtils.renderIntoDocument( <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component> ); }); it('does not warn for iterable elements with keys', () => { const iterable = { '@@iterator': function () { let i = 0; return { next: function () { const done = ++i > 2; return { value: done ? undefined : <Component key={'#' + i} />, done: done, }; }, }; }, }; ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>); }); it('does not warn for numeric keys in entry iterable as a child', () => { const iterable = { '@@iterator': function () { let i = 0; return { next: function () { const done = ++i > 2; return {value: done ? undefined : [i, <Component />], done: done}; }, }; }, }; iterable.entries = iterable['@@iterator']; ReactTestUtils.renderIntoDocument(<Component>{iterable}</Component>); }); it('does not warn when the element is directly as children', () => { ReactTestUtils.renderIntoDocument( <Component> <Component /> <Component /> </Component> ); }); it('does not warn when the child array contains non-elements', () => { void (<Component>{[{}, {}]}</Component>); }); it('should give context for PropType errors in nested components.', () => { // In this test, we're making sure that if a proptype error is found in a // component, we give a small hint as to which parent instantiated that // component as per warnings about key usage in ReactElementValidator. function MyComp({color}) { return <div>My color is {color}</div>; } MyComp.propTypes = { color: PropTypes.string, }; class ParentComp extends React.Component { render() { return <MyComp color={123} />; } } expect(() => ReactTestUtils.renderIntoDocument(<ParentComp />)).toErrorDev( 'Warning: Failed prop type: ' + 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + 'expected `string`.\n' + ' in color (at **)\n' + ' in ParentComp (at **)' ); }); it('gives a helpful error when passing null, undefined, or boolean', () => { const Undefined = undefined; const Null = null; const True = true; const Div = 'div'; expect(() => void (<Undefined />)).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: undefined. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.' + (process.env.BABEL_ENV === 'development' ? '\n\nCheck your code at **.' : ''), {withoutStack: true} ); expect(() => void (<Null />)).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + (process.env.BABEL_ENV === 'development' ? '\n\nCheck your code at **.' : ''), {withoutStack: true} ); expect(() => void (<True />)).toErrorDev( 'Warning: React.jsx: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.' + (process.env.BABEL_ENV === 'development' ? '\n\nCheck your code at **.' : ''), {withoutStack: true} ); // No error expected void (<Div />); }); it('should check default prop values', () => { RequiredPropComponent.defaultProps = {prop: null}; expect(() => ReactTestUtils.renderIntoDocument(<RequiredPropComponent />) ).toErrorDev( 'Warning: Failed prop type: The prop `prop` is marked as required in ' + '`RequiredPropComponent`, but its value is `null`.\n' + ' in RequiredPropComponent (at **)' ); }); it('should warn on invalid prop types', () => { // Since there is no prevalidation step for ES6 classes, there is no hook // for us to issue a warning earlier than element creation when the error // actually occurs. Since this step is skipped in production, we should just // warn instead of throwing for this case. class NullPropTypeComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } NullPropTypeComponent.propTypes = { prop: null, }; expect(() => ReactTestUtils.renderIntoDocument(<NullPropTypeComponent />) ).toErrorDev( 'NullPropTypeComponent: prop type `prop` is invalid; it must be a ' + 'function, usually from the `prop-types` package,' ); }); it('should warn on invalid context types', () => { class NullContextTypeComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } NullContextTypeComponent.contextTypes = { prop: null, }; expect(() => ReactTestUtils.renderIntoDocument(<NullContextTypeComponent />) ).toErrorDev( 'NullContextTypeComponent: context type `prop` is invalid; it must ' + 'be a function, usually from the `prop-types` package,' ); }); it('should warn if getDefaultProps is specified on the class', () => { class GetDefaultPropsComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } GetDefaultPropsComponent.getDefaultProps = () => ({ prop: 'foo', }); expect(() => ReactTestUtils.renderIntoDocument(<GetDefaultPropsComponent />) ).toErrorDev( 'getDefaultProps is only used on classic React.createClass definitions.' + ' Use a static property named `defaultProps` instead.', {withoutStack: true} ); }); it('should warn if component declares PropTypes instead of propTypes', () => { class MisspelledPropTypesComponent extends React.Component { render() { return <span>{this.props.prop}</span>; } } MisspelledPropTypesComponent.PropTypes = { prop: PropTypes.string, }; expect(() => ReactTestUtils.renderIntoDocument( <MisspelledPropTypesComponent prop="hi" /> ) ).toErrorDev( 'Warning: Component MisspelledPropTypesComponent declared `PropTypes` ' + 'instead of `propTypes`. Did you misspell the property assignment?', {withoutStack: true} ); }); it('warns for fragments with illegal attributes', () => { class Foo extends React.Component { render() { return <React.Fragment a={1}>hello</React.Fragment>; } } expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toErrorDev( 'Invalid prop `a` supplied to `React.Fragment`. React.Fragment ' + 'can only have `key` and `children` props.' ); }); it('warns for fragments with refs', () => { class Foo extends React.Component { render() { return ( <React.Fragment ref={bar => { this.foo = bar; }}> hello </React.Fragment> ); } } expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toErrorDev( 'Invalid attribute `ref` supplied to `React.Fragment`.' ); }); it('does not warn for fragments of multiple elements without keys', () => { ReactTestUtils.renderIntoDocument( <> <span>1</span> <span>2</span> </> ); }); it('warns for fragments of multiple elements with same key', () => { expect(() => ReactTestUtils.renderIntoDocument( <> <span key="a">1</span> <span key="a">2</span> <span key="b">3</span> </> ) ).toErrorDev('Encountered two children with the same key, `a`.', { withoutStack: true, }); }); it('does not call lazy initializers eagerly', () => { let didCall = false; const Lazy = React.lazy(() => { didCall = true; return {then() {}}; }); <Lazy />; expect(didCall).toBe(false); }); it('supports classic refs', () => { class Foo extends React.Component { render() { return <div className="foo" ref="inner" />; } } const container = document.createElement('div'); const instance = ReactDOM.render(<Foo />, container); expect(instance.refs.inner.className).toBe('foo'); }); it('should support refs on owned components', () => { const innerObj = {}; const outerObj = {}; class Wrapper extends React.Component { getObject = () => { return this.props.object; }; render() { return <div>{this.props.children}</div>; } } class Component extends React.Component { render() { const inner = <Wrapper object={innerObj} ref="inner" />; const outer = ( <Wrapper object={outerObj} ref="outer"> {inner} </Wrapper> ); return outer; } componentDidMount() { expect(this.refs.inner.getObject()).toEqual(innerObj); expect(this.refs.outer.getObject()).toEqual(outerObj); } } ReactTestUtils.renderIntoDocument(<Component />); }); it('should support callback-style refs', () => { const innerObj = {}; const outerObj = {}; class Wrapper extends React.Component { getObject = () => { return this.props.object; }; render() { return <div>{this.props.children}</div>; } } let mounted = false; class Component extends React.Component { render() { const inner = ( <Wrapper object={innerObj} ref={c => (this.innerRef = c)} /> ); const outer = ( <Wrapper object={outerObj} ref={c => (this.outerRef = c)}> {inner} </Wrapper> ); return outer; } componentDidMount() { expect(this.innerRef.getObject()).toEqual(innerObj); expect(this.outerRef.getObject()).toEqual(outerObj); mounted = true; } } ReactTestUtils.renderIntoDocument(<Component />); expect(mounted).toBe(true); }); it('should support object-style refs', () => { const innerObj = {}; const outerObj = {}; class Wrapper extends React.Component { getObject = () => { return this.props.object; }; render() { return <div>{this.props.children}</div>; } } let mounted = false; class Component extends React.Component { constructor() { super(); this.innerRef = React.createRef(); this.outerRef = React.createRef(); } render() { const inner = <Wrapper object={innerObj} ref={this.innerRef} />; const outer = ( <Wrapper object={outerObj} ref={this.outerRef}> {inner} </Wrapper> ); return outer; } componentDidMount() { expect(this.innerRef.current.getObject()).toEqual(innerObj); expect(this.outerRef.current.getObject()).toEqual(outerObj); mounted = true; } } ReactTestUtils.renderIntoDocument(<Component />); expect(mounted).toBe(true); }); it('should support new-style refs with mixed-up owners', () => { class Wrapper extends React.Component { getTitle = () => { return this.props.title; }; render() { return this.props.getContent(); } } let mounted = false; class Component extends React.Component { getInner = () => { // (With old-style refs, it's impossible to get a ref to this div // because Wrapper is the current owner when this function is called.) return <div className="inner" ref={c => (this.innerRef = c)} />; }; render() { return ( <Wrapper title="wrapper" ref={c => (this.wrapperRef = c)} getContent={this.getInner} /> ); } componentDidMount() { // Check .props.title to make sure we got the right elements back expect(this.wrapperRef.getTitle()).toBe('wrapper'); expect(this.innerRef.className).toBe('inner'); mounted = true; } } ReactTestUtils.renderIntoDocument(<Component />); expect(mounted).toBe(true); }); it('should warn when `key` is being accessed on composite element', () => { const container = document.createElement('div'); class Child extends React.Component { render() { return <div> {this.props.key} </div>; } } class Parent extends React.Component { render() { return ( <div> <Child key="0" /> <Child key="1" /> <Child key="2" /> </div> ); } } expect(() => ReactDOM.render(<Parent />, container)).toErrorDev( 'Child: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)' ); }); it('should warn when `ref` is being accessed', () => { const container = document.createElement('div'); class Child extends React.Component { render() { return <div> {this.props.ref} </div>; } } class Parent extends React.Component { render() { return ( <div> <Child ref="childElement" /> </div> ); } } expect(() => ReactDOM.render(<Parent />, container)).toErrorDev( 'Child: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)' ); }); it('should warn when owner and self are different for string refs', () => { class ClassWithRenderProp extends React.Component { render() { return this.props.children(); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp>{() => <div ref="myRef" />}</ClassWithRenderProp> ); } } const container = document.createElement('div'); if (process.env.BABEL_ENV === 'development') { expect(() => ReactDOM.render(<ClassParent />, container)).toErrorDev([ 'Warning: Component "ClassWithRenderProp" contains the string ref "myRef". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', ]); } else { ReactDOM.render(<ClassParent />, container); } });
27.582031
91
0.625877
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 ReactNoopPersistent; let act; describe('ReactPersistentUpdatesMinimalism', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoopPersistent = require('react-noop-renderer/persistent'); act = require('internal-test-utils').act; }); it('should render a simple component', async () => { function Child() { return <div>Hello World</div>; } function Parent() { return <Child />; } ReactNoopPersistent.startTrackingHostCounters(); await act(() => ReactNoopPersistent.render(<Parent />)); expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({ hostCloneCounter: 0, }); ReactNoopPersistent.startTrackingHostCounters(); await act(() => ReactNoopPersistent.render(<Parent />)); expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({ hostCloneCounter: 1, }); }); it('should not diff referentially equal host elements', async () => { function Leaf(props) { return ( <span> hello <b /> {props.name} </span> ); } const constEl = ( <div> <Leaf name="world" /> </div> ); function Child() { return constEl; } function Parent() { return <Child />; } ReactNoopPersistent.startTrackingHostCounters(); await act(() => ReactNoopPersistent.render(<Parent />)); expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({ hostCloneCounter: 0, }); ReactNoopPersistent.startTrackingHostCounters(); await act(() => ReactNoopPersistent.render(<Parent />)); expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({ hostCloneCounter: 0, }); }); it('should not diff parents of setState targets', async () => { let childInst; function Leaf(props) { return ( <span> hello <b /> {props.name} </span> ); } class Child extends React.Component { state = {name: 'Batman'}; render() { childInst = this; return ( <div> <Leaf name={this.state.name} /> </div> ); } } function Parent() { return ( <section> <div> <Leaf name="world" /> <Child /> <hr /> <Leaf name="world" /> </div> </section> ); } ReactNoopPersistent.startTrackingHostCounters(); await act(() => ReactNoopPersistent.render(<Parent />)); expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({ hostCloneCounter: 0, }); ReactNoopPersistent.startTrackingHostCounters(); await act(() => childInst.setState({name: 'Robin'})); expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({ // section // section > div // section > div > Child > div // section > div > Child > Leaf > span // section > div > Child > Leaf > span > b hostCloneCounter: 5, }); ReactNoopPersistent.startTrackingHostCounters(); await act(() => ReactNoopPersistent.render(<Parent />)); expect(ReactNoopPersistent.stopTrackingHostCounters()).toEqual({ // Parent > section // Parent > section > div // Parent > section > div > Leaf > span // Parent > section > div > Leaf > span > b // Parent > section > div > Child > div // Parent > section > div > Child > div > Leaf > span // Parent > section > div > Child > div > Leaf > span > b // Parent > section > div > hr // Parent > section > div > Leaf > span // Parent > section > div > Leaf > span > b hostCloneCounter: 10, }); }); });
24.617834
71
0.579707
owtf
/* * Copyright (c) Facebook, Inc. and its affiliates. */ import { createContext, memo, useState, useContext, useId, Suspense, useEffect, useRef, useTransition, } from 'react'; import cn from 'classnames'; import NextLink from 'next/link'; import ButtonLink from '../ButtonLink'; import {IconRestart} from '../Icon/IconRestart'; import BlogCard from 'components/MDX/BlogCard'; import {IconChevron} from 'components/Icon/IconChevron'; import {IconSearch} from 'components/Icon/IconSearch'; import {Logo} from 'components/Logo'; import Link from 'components/MDX/Link'; import CodeBlock from 'components/MDX/CodeBlock'; import {ExternalLink} from 'components/ExternalLink'; import sidebarBlog from '../../sidebarBlog.json'; function Section({children, background = null}) { return ( <div className={cn( 'mx-auto flex flex-col w-full', background === null && 'max-w-7xl', background === 'left-card' && 'bg-gradient-left dark:bg-gradient-left-dark border-t border-primary/10 dark:border-primary-dark/10 ', background === 'right-card' && 'bg-gradient-right dark:bg-gradient-right-dark border-t border-primary/5 dark:border-primary-dark/5' )} style={{ contain: 'content', }}> <div className="flex-col gap-2 flex grow w-full my-20 lg:my-32 mx-auto items-center"> {children} </div> </div> ); } function Header({children}) { return ( <h2 className="leading-xl font-display text-primary dark:text-primary-dark font-semibold text-5xl lg:text-6xl -mt-4 mb-7 w-full max-w-3xl lg:max-w-xl"> {children} </h2> ); } function Para({children}) { return ( <p className="max-w-3xl mx-auto text-lg lg:text-xl text-secondary dark:text-secondary-dark leading-normal"> {children} </p> ); } function Center({children}) { return ( <div className="px-5 lg:px-0 max-w-4xl lg:text-center text-white text-opacity-80 flex flex-col items-center justify-center"> {children} </div> ); } function FullBleed({children}) { return ( <div className="max-w-7xl mx-auto flex flex-col w-full">{children}</div> ); } function CurrentTime() { const [date, setDate] = useState(new Date()); const currentTime = date.toLocaleTimeString([], { hour: 'numeric', minute: 'numeric', }); useEffect(() => { const msPerMinute = 60 * 1000; let nextMinute = Math.floor(+date / msPerMinute + 1) * msPerMinute; const timeout = setTimeout(() => { if (Date.now() > nextMinute) { setDate(new Date()); } }, nextMinute - Date.now()); return () => clearTimeout(timeout); }, [date]); return <span suppressHydrationWarning>{currentTime}</span>; } const blogSidebar = sidebarBlog.routes[1]; if (blogSidebar.path !== '/blog') { throw Error('Could not find the blog route in sidebarBlog.json'); } const recentPosts = blogSidebar.routes.slice(0, 4).map((entry) => ({ title: entry.titleForHomepage, icon: entry.icon, date: entry.date, url: entry.path, })); export function HomeContent() { return ( <> <div className="ps-0"> <div className="mx-5 mt-12 lg:mt-24 mb-20 lg:mb-32 flex flex-col justify-center"> <Logo className={cn( 'mt-4 mb-3 text-link dark:text-link-dark w-24 lg:w-28 self-center text-sm me-0 flex origin-center transition-all ease-in-out' )} /> <h1 className="text-5xl font-display lg:text-6xl self-center flex font-semibold leading-snug text-primary dark:text-primary-dark"> React </h1> <p className="text-4xl font-display max-w-lg md:max-w-full py-1 text-center text-secondary dark:text-primary-dark leading-snug self-center"> The library for web and native user interfaces </p> <div className="mt-5 self-center flex gap-2 w-full sm:w-auto flex-col sm:flex-row"> <ButtonLink href={'/learn'} type="primary" size="lg" className="w-full sm:w-auto justify-center" label="Learn React"> Learn React </ButtonLink> <ButtonLink href={'/reference/react'} type="secondary" size="lg" className="w-full sm:w-auto justify-center" label="API Reference"> API Reference </ButtonLink> </div> </div> <Section background="left-card"> <Center> <Header>Create user interfaces from components</Header> <Para> React lets you build user interfaces out of individual pieces called components. Create your own React components like{' '} <Code>Thumbnail</Code>, <Code>LikeButton</Code>, and{' '} <Code>Video</Code>. Then combine them into entire screens, pages, and apps. </Para> </Center> <FullBleed> <Example1 /> </FullBleed> <Center> <Para> Whether you work on your own or with thousands of other developers, using React feels the same. It is designed to let you seamlessly combine components written by independent people, teams, and organizations. </Para> </Center> </Section> <Section background="right-card"> <Center> <Header>Write components with code and markup</Header> <Para> React components are JavaScript functions. Want to show some content conditionally? Use an <Code>if</Code> statement. Displaying a list? Try array <Code>map()</Code>. Learning React is learning programming. </Para> </Center> <FullBleed> <Example2 /> </FullBleed> <Center> <Para> This markup syntax is called JSX. It is a JavaScript syntax extension popularized by React. Putting JSX markup close to related rendering logic makes React components easy to create, maintain, and delete. </Para> </Center> </Section> <Section background="left-card"> <Center> <Header>Add interactivity wherever you need it</Header> <Para> React components receive data and return what should appear on the screen. You can pass them new data in response to an interaction, like when the user types into an input. React will then update the screen to match the new data. </Para> </Center> <FullBleed> <Example3 /> </FullBleed> <Center> <Para> You don’t have to build your whole page in React. Add React to your existing HTML page, and render interactive React components anywhere on it. </Para> <div className="flex justify-start w-full lg:justify-center"> <CTA color="gray" icon="code" href="/learn/add-react-to-an-existing-project"> Add React to your page </CTA> </div> </Center> </Section> <Section background="right-card"> <Center> <Header> Go full-stack <br className="hidden lg:inline" /> with a framework </Header> <Para> React is a library. It lets you put components together, but it doesn’t prescribe how to do routing and data fetching. To build an entire app with React, we recommend a full-stack React framework like <Link href="https://nextjs.org">Next.js</Link> or{' '} <Link href="https://remix.run">Remix</Link>. </Para> </Center> <FullBleed> <Example4 /> </FullBleed> <Center> <Para> React is also an architecture. Frameworks that implement it let you fetch data in asynchronous components that run on the server or even during the build. Read data from a file or a database, and pass it down to your interactive components. </Para> <div className="flex justify-start w-full lg:justify-center"> <CTA color="gray" icon="framework" href="/learn/start-a-new-react-project"> Get started with a framework </CTA> </div> </Center> </Section> <Section background="left-card"> <div className="mx-auto flex flex-col w-full"> <div className="mx-auto max-w-4xl lg:text-center items-center px-5 flex flex-col"> <Header>Use the best from every platform</Header> <Para> People love web and native apps for different reasons. React lets you build both web apps and native apps using the same skills. It leans upon each platform’s unique strengths to let your interfaces feel just right on every platform. </Para> </div> <div className="max-w-7xl mx-auto flex flex-col lg:flex-row mt-16 mb-20 lg:mb-28 px-5 gap-20 lg:gap-5"> <div className="relative lg:w-6/12 flex"> <div className="absolute -bottom-8 lg:-bottom-10 z-10 w-full"> <WebIcons /> </div> <BrowserChrome hasRefresh={false} domain="example.com"> <div className="relative overflow-hidden"> <div className="absolute inset-0 bg-gradient-right" /> <div className="bg-wash relative h-14 w-full" /> <div className="relative flex items-start justify-center flex-col flex-1 pb-16 pt-5 gap-3 px-5 lg:px-10 lg:pt-8"> <h4 className="leading-tight text-primary font-semibold text-3xl lg:text-4xl"> Stay true to the web </h4> <p className="lg:text-xl leading-normal text-secondary"> People expect web app pages to load fast. On the server, React lets you start streaming HTML while you’re still fetching data, progressively filling in the remaining content before any JavaScript code loads. On the client, React can use standard web APIs to keep your UI responsive even in the middle of rendering. </p> </div> </div> </BrowserChrome> </div> <div className="relative lg:w-6/12 flex"> <div className="absolute -bottom-8 lg:-bottom-10 z-10 w-full"> <NativeIcons /> </div> <figure className="mx-auto max-w-3xl h-auto"> <div className="p-2.5 bg-gray-95 dark:bg-black rounded-2xl shadow-nav dark:shadow-nav-dark"> <div className="bg-gradient-right dark:bg-gradient-right-dark px-3 sm:px-3 pb-12 lg:pb-20 rounded-lg overflow-hidden"> <div className="select-none w-full h-14 flex flex-row items-start pt-3 -mb-2.5 justify-between text-tertiary dark:text-tertiary-dark"> <span className="uppercase tracking-wide leading-none font-bold text-sm text-tertiary dark:text-tertiary-dark"> <CurrentTime /> </span> <div className="gap-2 flex -mt-0.5"> <svg width="16" height="20" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" clipRule="evenodd" d="M34.852 6.22836C35.973 5.76401 37.2634 6.02068 38.1214 6.87868L53.1214 21.8787C53.7485 22.5058 54.066 23.3782 53.9886 24.2617C53.9113 25.1451 53.447 25.9491 52.7205 26.4577L39.0886 36.0003L52.7204 45.5423C53.447 46.0508 53.9113 46.8548 53.9886 47.7383C54.066 48.6218 53.7485 49.4942 53.1214 50.1213L38.1214 65.1213C37.2634 65.9793 35.973 66.236 34.852 65.7716C33.731 65.3073 33.0001 64.2134 33.0001 63V40.2624L22.7205 47.4583C21.3632 48.4085 19.4926 48.0784 18.5424 46.721C17.5922 45.3637 17.9223 43.4931 19.2797 42.543L28.6258 36.0004L19.2797 29.4583C17.9224 28.5082 17.5922 26.6376 18.5424 25.2803C19.4925 23.9229 21.3631 23.5928 22.7204 24.5429L33.0001 31.7384V9C33.0001 7.78661 33.731 6.6927 34.852 6.22836ZM39.0001 43.2622L46.3503 48.4072L39.0001 55.7574V43.2622ZM39.0001 28.7382V16.2426L46.3503 23.5929L39.0001 28.7382Z" fill="currentColor" /> </svg> <svg width="16" height="20" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9 27C9.82864 27 10.5788 26.664 11.1217 26.1209C11.2116 26.0355 11.3037 25.9526 11.397 25.871C11.625 25.6714 11.9885 25.3677 12.4871 24.9938C13.4847 24.2455 15.0197 23.219 17.0912 22.1833C21.2243 20.1167 27.5179 18 35.9996 18C44.4813 18 50.7748 20.1167 54.9079 22.1833C56.9794 23.219 58.5144 24.2455 59.5121 24.9938C59.6056 25.0639 60.8802 26.1233 60.8802 26.1233C61.423 26.6652 62.1724 27 63 27C64.6569 27 66 25.6569 66 24C66 22.8871 65.3475 22.0506 64.5532 21.3556C64.2188 21.0629 63.7385 20.6635 63.1121 20.1938C61.8597 19.2545 60.0197 18.031 57.5912 16.8167C52.7243 14.3833 45.5179 12 35.9996 12C26.4813 12 19.2748 14.3833 14.4079 16.8167C11.9794 18.031 10.1394 19.2545 8.88706 20.1938C8.26066 20.6635 7.78035 21.0629 7.44593 21.3556C7.2605 21.5178 7.07794 21.6834 6.9016 21.8555C6.33334 22.417 6 23.1999 6 24C6 25.6569 7.34315 27 9 27Z" fill="currentColor" /> <path fillRule="evenodd" clipRule="evenodd" d="M26.1116 48.631C24.2868 50.4378 21 49.0661 21 46.5C21 45.6707 21.3365 44.92 21.8804 44.3769C21.9856 44.2702 22.0973 44.1695 22.209 44.0697C22.3915 43.9065 22.6466 43.6885 22.9713 43.4344C23.6195 42.9271 24.5536 42.2694 25.7509 41.6163C28.1445 40.3107 31.6365 39 35.9999 39C40.3634 39 43.8554 40.3107 46.249 41.6163C47.4463 42.2694 48.3804 42.9271 49.0286 43.4344C50.0234 44.213 51 45.134 51 46.5C51 48.1569 49.6569 49.5 48 49.5C47.1724 49.5 46.4231 49.1649 45.8803 48.623C45.7028 48.4617 45.5197 48.3073 45.3307 48.1594C44.9007 47.8229 44.2411 47.3556 43.3759 46.8837C41.6445 45.9393 39.1365 45 35.9999 45C32.8634 45 30.3554 45.9393 28.624 46.8837C27.7588 47.3556 27.0992 47.8229 26.6692 48.1594C26.3479 48.4109 26.155 48.5899 26.1116 48.631Z" fill="currentColor" /> <path d="M36 63C39.3137 63 42 60.3137 42 57C42 53.6863 39.3137 51 36 51C32.6863 51 30 53.6863 30 57C30 60.3137 32.6863 63 36 63Z" fill="currentColor" /> <path d="M15 39C13.3431 39 12 37.6569 12 36C12 34.3892 13.3933 33.3427 14.5534 32.4503C15.5841 31.6574 17.0871 30.6231 19.04 29.5952C22.9506 27.537 28.6773 25.5 35.9997 25.5C43.3222 25.5 49.0488 27.537 52.9595 29.5952C54.9123 30.6231 56.4154 31.6574 57.4461 32.4503C57.9619 32.847 58.361 33.1846 58.6407 33.4324C59.4024 34.1073 60 34.9345 60 36C60 37.6569 58.6569 39 57 39C56.1737 39 55.4255 38.6662 54.8829 38.1258C54.5371 37.7978 54.1653 37.4964 53.7878 37.206C52.9903 36.5926 51.7746 35.7519 50.165 34.9048C46.9506 33.213 42.1773 31.5 35.9997 31.5C29.8222 31.5 25.0488 33.213 21.8345 34.9048C20.2248 35.7519 19.0091 36.5926 18.2117 37.206C17.6144 37.6654 17.2549 37.9951 17.1459 38.098C16.5581 38.6591 15.8222 39 15 39Z" fill="currentColor" /> </svg> <svg width="20" height="20" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12.9533 26.0038C13.224 24.7829 14.3285 24 15.579 24H50.421C51.6715 24 52.776 24.7829 53.0467 26.0038C53.4754 27.937 54 31.2691 54 36C54 40.7309 53.4754 44.063 53.0467 45.9962C52.776 47.2171 51.6715 48 50.421 48H15.579C14.3285 48 13.224 47.2171 12.9533 45.9962C12.5246 44.063 12 40.7309 12 36C12 31.2691 12.5246 27.937 12.9533 26.0038Z" fill="currentColor" /> <path fillRule="evenodd" clipRule="evenodd" d="M12.7887 15C8.77039 15 5.23956 17.668 4.48986 21.6158C3.74326 25.5473 3 30.7737 3 36C3 41.2263 3.74326 46.4527 4.48986 50.3842C5.23956 54.332 8.77039 57 12.7887 57H53.2113C57.2296 57 60.7604 54.332 61.5101 50.3842C61.8155 48.7765 62.1202 46.9522 62.3738 45H63.7918C64.5731 45 65.3283 44.8443 66 44.5491C67.2821 43.9857 68.2596 42.9142 68.5322 41.448C68.7927 40.0466 69 38.2306 69 36C69 33.7694 68.7927 31.9534 68.5322 30.552C68.2596 29.0858 67.2821 28.0143 66 27.4509C65.3283 27.1557 64.5731 27 63.7918 27H62.3738C62.1202 25.0478 61.8155 23.2235 61.5101 21.6158C60.7604 17.668 57.2296 15 53.2113 15H12.7887ZM53.2113 21H12.7887C11.3764 21 10.5466 21.8816 10.3845 22.7352C9.67563 26.4681 9 31.29 9 36C9 40.71 9.67563 45.5319 10.3845 49.2648C10.5466 50.1184 11.3764 51 12.7887 51H53.2113C54.6236 51 55.4534 50.1184 55.6155 49.2648C56.3244 45.5319 57 40.71 57 36C57 31.29 56.3244 26.4681 55.6155 22.7352C55.4534 21.8816 54.6236 21 53.2113 21Z" fill="currentColor" /> </svg> </div> </div> <div className="flex flex-col items-start justify-center pt-0 gap-3 px-2.5 lg:pt-8 lg:px-8"> <h4 className="leading-tight text-primary dark:text-primary-dark font-semibold text-3xl lg:text-4xl"> Go truly native </h4> <p className="h-full lg:text-xl text-secondary dark:text-secondary-dark leading-normal"> People expect native apps to look and feel like their platform.{' '} <Link href="https://reactnative.dev"> React Native </Link>{' '} and{' '} <Link href="https://github.com/expo/expo">Expo</Link>{' '} let you build apps in React for Android, iOS, and more. They look and feel native because their UIs{' '} <i>are</i> truly native. It’s not a web view—your React components render real Android and iOS views provided by the platform. </p> </div> </div> </div> </figure> </div> </div> <div className="px-5 lg:px-0 max-w-4xl mx-auto lg:text-center text-secondary dark:text-secondary-dark"> <Para> With React, you can be a web <i>and</i> a native developer. Your team can ship to many platforms without sacrificing the user experience. Your organization can bridge the platform silos, and form teams that own entire features end-to-end. </Para> <div className="flex justify-start w-full lg:justify-center"> <CTA color="gray" icon="native" href="https://reactnative.dev/"> Build for native platforms </CTA> </div> </div> </div> </Section> <Section background="right-card"> <div className="max-w-7xl mx-auto flex flex-col lg:flex-row px-5"> <div className="max-w-3xl lg:max-w-7xl gap-5 flex flex-col lg:flex-row lg:px-5"> <div className="w-full lg:w-6/12 max-w-3xl flex flex-col items-start justify-start lg:ps-5 lg:pe-10"> <Header>Upgrade when the future is ready</Header> <Para> React approaches changes with care. Every React commit is tested on business-critical surfaces with over a billion users. Over 100,000 React components at Meta help validate every migration strategy. </Para> <div className="order-last pt-5"> <Para> The React team is always researching how to improve React. Some research takes years to pay off. React has a high bar for taking a research idea into production. Only proven approaches become a part of React. </Para> <div className="hidden lg:flex justify-start w-full"> <CTA color="gray" icon="news" href="/blog"> Read more React news </CTA> </div> </div> </div> <div className="w-full lg:w-6/12"> <p className="uppercase tracking-wide font-bold text-sm text-tertiary dark:text-tertiary-dark flex flex-row gap-2 items-center mt-5 lg:-mt-2 w-full"> <IconChevron /> Latest React News </p> <div className="flex-col sm:flex-row flex-wrap flex gap-5 text-start my-5"> <div className="flex-1 min-w-[40%] text-start"> <BlogCard {...recentPosts[0]} /> </div> <div className="flex-1 min-w-[40%] text-start"> <BlogCard {...recentPosts[1]} /> </div> <div className="flex-1 min-w-[40%] text-start"> <BlogCard {...recentPosts[2]} /> </div> <div className="hidden sm:flex-1 sm:inline"> <BlogCard {...recentPosts[3]} /> </div> </div> <div className="flex lg:hidden justify-start w-full"> <CTA color="gray" icon="news" href="/blog"> Read more React news </CTA> </div> </div> </div> </div> </Section> <Section background="left-card"> <div className="w-full"> <div className="mx-auto flex flex-col max-w-4xl"> <Center> <Header> Join a community <br className="hidden lg:inline" /> of millions </Header> <Para> You’re not alone. Two million developers from all over the world visit the React docs every month. React is something that people and teams can agree on. </Para> </Center> </div> <CommunityGallery /> <div className="mx-auto flex flex-col max-w-4xl"> <Center> <Para> This is why React is more than a library, an architecture, or even an ecosystem. React is a community. It’s a place where you can ask for help, find opportunities, and meet new friends. You will meet both developers and designers, beginners and experts, researchers and artists, teachers and students. Our backgrounds may be very different, but React lets us all create user interfaces together. </Para> </Center> </div> </div> <div className="mt-20 px-5 lg:px-0 mb-6 max-w-4xl text-center text-opacity-80"> <Logo className="text-link dark:text-link-dark w-24 lg:w-28 mb-10 lg:mb-8 mt-12 h-auto mx-auto self-start" /> <Header> Welcome to the <br className="hidden lg:inline" /> React community </Header> <ButtonLink href={'/learn'} type="primary" size="lg" label="Take the Tutorial"> Get Started </ButtonLink> </div> </Section> </div> </> ); } function CTA({children, icon, href}) { let Tag; let extraProps; if (href.startsWith('https://')) { Tag = ExternalLink; } else { Tag = NextLink; extraProps = {legacyBehavior: false}; } return ( <Tag {...extraProps} href={href} className="focus:outline-none focus-visible:outline focus-visible:outline-link focus:outline-offset-2 focus-visible:dark:focus:outline-link-dark group cursor-pointer w-auto justify-center inline-flex font-bold items-center mt-10 outline-none hover:bg-gray-40/5 active:bg-gray-40/10 hover:dark:bg-gray-60/5 active:dark:bg-gray-60/10 leading-tight hover:bg-opacity-80 text-lg py-2.5 rounded-full px-4 sm:px-6 ease-in-out shadow-secondary-button-stroke dark:shadow-secondary-button-stroke-dark text-primary dark:text-primary-dark"> {icon === 'native' && ( <svg className="me-2.5 text-primary dark:text-primary-dark" fill="none" width="24" height="24" viewBox="0 0 72 72" aria-hidden="true"> <g clipPath="url(#clip0_8_10998)"> <path d="M54.0001 15H18.0001C16.3432 15 15.0001 16.3431 15.0001 18V42H33V48H12.9567L9.10021 57L24.0006 57C24.0006 55.3431 25.3437 54 27.0006 54H33V57.473C33 59.3786 33.3699 61.2582 34.0652 63H9.10021C4.79287 63 1.88869 58.596 3.5852 54.6368L9.0001 42V18C9.0001 13.0294 13.0295 9 18.0001 9H54.0001C58.9707 9 63.0001 13.0294 63.0001 18V25.4411C62.0602 25.0753 61.0589 24.8052 60.0021 24.6458C59.0567 24.5032 58.0429 24.3681 57.0001 24.2587V18C57.0001 16.3431 55.6569 15 54.0001 15Z" fill="currentColor" /> <path d="M48 42C48 40.3431 49.3431 39 51 39H54C55.6569 39 57 40.3431 57 42C57 43.6569 55.6569 45 54 45H51C49.3431 45 48 43.6569 48 42Z" fill="currentColor" /> <path fillRule="evenodd" clipRule="evenodd" d="M45.8929 30.5787C41.8093 31.1947 39 34.8257 39 38.9556V57.473C39 61.6028 41.8093 65.2339 45.8929 65.8499C48.0416 66.174 50.3981 66.4286 52.5 66.4286C54.6019 66.4286 56.9584 66.174 59.1071 65.8499C63.1907 65.2339 66 61.6028 66 57.473V38.9556C66 34.8258 63.1907 31.1947 59.1071 30.5787C56.9584 30.2545 54.6019 30 52.5 30C50.3981 30 48.0416 30.2545 45.8929 30.5787ZM60 57.473V38.9556C60 37.4615 59.0438 36.637 58.2121 36.5116C56.2014 36.2082 54.1763 36 52.5 36C50.8237 36 48.7986 36.2082 46.7879 36.5116C45.9562 36.637 45 37.4615 45 38.9556V57.473C45 58.9671 45.9562 59.7916 46.7879 59.917C48.7986 60.2203 50.8237 60.4286 52.5 60.4286C54.1763 60.4286 56.2014 60.2203 58.2121 59.917C59.0438 59.7916 60 58.9671 60 57.473Z" fill="currentColor" /> </g> <defs> <clipPath id="clip0_8_10998"> <rect width="72" height="72" fill="white" /> </clipPath> </defs> </svg> )} {icon === 'framework' && ( <svg className="me-2.5 text-primary dark:text-primary-dark" fill="none" width="24" height="24" viewBox="0 0 72 72" aria-hidden="true"> <g clipPath="url(#clip0_10_21081)"> <path fillRule="evenodd" clipRule="evenodd" d="M44.9136 29.0343C46.8321 26.9072 48 24.09 48 21C48 14.3726 42.6274 9 36 9C29.3726 9 24 14.3726 24 21C24 24.0904 25.1682 26.9079 27.0871 29.0351L21.0026 39.3787C20.0429 39.1315 19.0368 39 18 39C11.3726 39 6 44.3726 6 51C6 57.6274 11.3726 63 18 63C23.5915 63 28.2898 59.1757 29.6219 54H42.3781C43.7102 59.1757 48.4085 63 54 63C60.6274 63 66 57.6274 66 51C66 44.3726 60.6274 39 54 39C52.9614 39 51.9537 39.1319 50.9926 39.38L44.9136 29.0343ZM42 21C42 24.3137 39.3137 27 36 27C32.6863 27 30 24.3137 30 21C30 17.6863 32.6863 15 36 15C39.3137 15 42 17.6863 42 21ZM39.9033 32.3509C38.6796 32.7716 37.3665 33 36 33C34.6338 33 33.321 32.7717 32.0975 32.3512L26.2523 42.288C27.8635 43.8146 29.0514 45.7834 29.6219 48H42.3781C42.9482 45.785 44.1348 43.8175 45.7441 42.2913L39.9033 32.3509ZM54 57C50.6863 57 48 54.3137 48 51C48 47.6863 50.6863 45 54 45C57.3137 45 60 47.6863 60 51C60 54.3137 57.3137 57 54 57ZM24 51C24 47.6863 21.3137 45 18 45C14.6863 45 12 47.6863 12 51C12 54.3137 14.6863 57 18 57C21.3137 57 24 54.3137 24 51Z" fill="currentColor" /> </g> <defs> <clipPath id="clip0_10_21081"> <rect width="72" height="72" fill="white" /> </clipPath> </defs> </svg> )} {icon === 'code' && ( <svg className="me-2.5 text-primary dark:text-primary-dark" fill="none" width="24" height="24" viewBox="0 0 72 72" aria-hidden="true"> <g clipPath="url(#clip0_8_9064)"> <path d="M44.7854 22.1142C45.4008 20.5759 44.6525 18.83 43.1142 18.2146C41.5758 17.5993 39.8299 18.3475 39.2146 19.8859L27.2146 49.8859C26.5992 51.4242 27.3475 53.1702 28.8858 53.7855C30.4242 54.4008 32.1701 53.6526 32.7854 52.1142L44.7854 22.1142Z" fill="currentColor" /> <path d="M9.87868 38.1214C8.70711 36.9498 8.70711 35.0503 9.87868 33.8787L18.8787 24.8787C20.0503 23.7072 21.9497 23.7072 23.1213 24.8787C24.2929 26.0503 24.2929 27.9498 23.1213 29.1214L16.2426 36.0001L23.1213 42.8787C24.2929 44.0503 24.2929 45.9498 23.1213 47.1214C21.9497 48.293 20.0503 48.293 18.8787 47.1214L9.87868 38.1214Z" fill="currentColor" /> <path d="M62.1213 33.8787L53.1213 24.8787C51.9497 23.7072 50.0503 23.7072 48.8787 24.8787C47.7071 26.0503 47.7071 27.9498 48.8787 29.1214L55.7574 36.0001L48.8787 42.8787C47.7071 44.0503 47.7071 45.9498 48.8787 47.1214C50.0503 48.293 51.9497 48.293 53.1213 47.1214L62.1213 38.1214C63.2929 36.9498 63.2929 35.0503 62.1213 33.8787Z" fill="currentColor" /> </g> <defs> <clipPath id="clip0_8_9064"> <rect width="72" height="72" fill="white" /> </clipPath> </defs> </svg> )} {icon === 'news' && ( <svg className="me-2.5 text-primary dark:text-primary-dark" fill="none" width="24" height="24" viewBox="0 0 72 72" aria-hidden="true"> <path fillRule="evenodd" clipRule="evenodd" d="M12.7101 56.3758C13.0724 56.7251 13.6324 57 14.3887 57H57.6113C58.3676 57 58.9276 56.7251 59.2899 56.3758C59.6438 56.0346 59.8987 55.5407 59.9086 54.864C59.9354 53.022 59.9591 50.7633 59.9756 48H12.0244C12.0409 50.7633 12.0645 53.022 12.0914 54.864C12.1013 55.5407 12.3562 56.0346 12.7101 56.3758ZM12.0024 42H59.9976C59.9992 41.0437 60 40.0444 60 39C60 29.5762 59.9327 22.5857 59.8589 17.7547C59.8359 16.2516 58.6168 15 56.9938 15L15.0062 15C13.3832 15 12.1641 16.2516 12.1411 17.7547C12.0673 22.5857 12 29.5762 12 39C12 40.0444 12.0008 41.0437 12.0024 42ZM65.8582 17.6631C65.7843 12.8227 61.8348 9 56.9938 9H15.0062C10.1652 9 6.21572 12.8227 6.1418 17.6631C6.06753 22.5266 6 29.5477 6 39C6 46.2639 6.03988 51.3741 6.09205 54.9515C6.15893 59.537 9.80278 63 14.3887 63H57.6113C62.1972 63 65.8411 59.537 65.9079 54.9515C65.9601 51.3741 66 46.2639 66 39C66 29.5477 65.9325 22.5266 65.8582 17.6631ZM39 21C37.3431 21 36 22.3431 36 24C36 25.6569 37.3431 27 39 27H51C52.6569 27 54 25.6569 54 24C54 22.3431 52.6569 21 51 21H39ZM36 33C36 31.3431 37.3431 30 39 30H51C52.6569 30 54 31.3431 54 33C54 34.6569 52.6569 36 51 36H39C37.3431 36 36 34.6569 36 33ZM24 33C27.3137 33 30 30.3137 30 27C30 23.6863 27.3137 21 24 21C20.6863 21 18 23.6863 18 27C18 30.3137 20.6863 33 24 33Z" fill="currentColor" /> </svg> )} {children} <svg className="text-primary dark:text-primary-dark rtl:rotate-180" fill="none" width="24" height="24" viewBox="0 0 72 72" aria-hidden="true"> <path className="transition-transform ease-in-out translate-x-[-8px] group-hover:translate-x-[8px]" fillRule="evenodd" clipRule="evenodd" d="M40.0001 19.0245C41.0912 17.7776 42.9864 17.6513 44.2334 18.7423L58.9758 33.768C59.6268 34.3377 60.0002 35.1607 60.0002 36.0257C60.0002 36.8908 59.6268 37.7138 58.9758 38.2835L44.2335 53.3078C42.9865 54.3988 41.0913 54.2725 40.0002 53.0256C38.9092 51.7786 39.0355 49.8835 40.2824 48.7924L52.4445 36.0257L40.2823 23.2578C39.0354 22.1667 38.9091 20.2714 40.0001 19.0245Z" fill="currentColor" /> <path className="opacity-0 ease-in-out transition-opacity group-hover:opacity-100" d="M60 36.0273C60 37.6842 58.6569 39.0273 57 39.0273H15C13.3431 39.0273 12 37.6842 12 36.0273C12 34.3704 13.3431 33.0273 15 33.0273H57C58.6569 33.0273 60 34.3704 60 36.0273Z" fill="currentColor" /> </svg> </Tag> ); } const reactConf2021Cover = '/images/home/conf2021/cover.svg'; const reactConf2019Cover = '/images/home/conf2019/cover.svg'; const communityImages = [ { src: '/images/home/community/react_conf_fun.webp', alt: 'People singing karaoke at React Conf', }, { src: '/images/home/community/react_india_sunil.webp', alt: 'Sunil Pai speaking at React India', }, { src: '/images/home/community/react_conf_hallway.webp', alt: 'A hallway conversation between two people at React Conf', }, { src: '/images/home/community/react_india_hallway.webp', alt: 'A hallway conversation at React India', }, { src: '/images/home/community/react_conf_elizabet.webp', alt: 'Elizabet Oliveira speaking at React Conf', }, { src: '/images/home/community/react_india_selfie.webp', alt: 'People taking a group selfie at React India', }, { src: '/images/home/community/react_conf_nat.webp', alt: 'Nat Alison speaking at React Conf', }, { src: '/images/home/community/react_india_team.webp', alt: 'Organizers greeting attendees at React India', }, ]; function CommunityGallery() { const ref = useRef(); const [shouldPlay, setShouldPlay] = useState(false); useEffect(() => { const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { setShouldPlay(entry.isIntersecting); }); }, { root: null, rootMargin: `${window.innerHeight}px 0px`, } ); observer.observe(ref.current); return () => observer.disconnect(); }, []); const [isLazy, setIsLazy] = useState(true); // Either wait until we're scrolling close... useEffect(() => { if (!isLazy) { return; } const rootVertical = parseInt(window.innerHeight * 2.5); const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { setIsLazy(false); } }); }, { root: null, rootMargin: `${rootVertical}px 0px`, } ); observer.observe(ref.current); return () => observer.disconnect(); }, [isLazy]); // ... or until it's been a while after hydration. useEffect(() => { const timeout = setTimeout(() => { setIsLazy(false); }, 20 * 1000); return () => clearTimeout(timeout); }, []); return ( <div ref={ref} className="relative flex overflow-x-hidden overflow-y-visible w-auto"> <div className="w-full py-12 lg:py-20 whitespace-nowrap flex flex-row animate-marquee lg:animate-large-marquee" style={{ animationPlayState: shouldPlay ? 'running' : 'paused', }}> <CommunityImages isLazy={isLazy} /> </div> <div aria-hidden="true" className="w-full absolute top-0 py-12 lg:py-20 whitespace-nowrap flex flex-row animate-marquee2 lg:animate-large-marquee2" style={{ animationPlayState: shouldPlay ? 'running' : 'paused', }}> <CommunityImages isLazy={isLazy} /> </div> </div> ); } const CommunityImages = memo(function CommunityImages({isLazy}) { return ( <> {communityImages.map(({src, alt}, i) => ( <div key={i} className={cn( `group flex justify-center px-5 min-w-[50%] lg:min-w-[25%] rounded-2xl relative` )}> <div className={cn( 'h-auto relative rounded-2xl overflow-hidden before:-skew-x-12 before:absolute before:inset-0 before:-translate-x-full group-hover:before:animate-[shimmer_1s_forwards] before:bg-gradient-to-r before:from-transparent before:via-white/10 before:to-transparent transition-all ease-in-out duration-300', i % 2 === 0 ? 'rotate-2 group-hover:rotate-[-1deg] group-hover:scale-110 group-hover:shadow-lg lg:group-hover:shadow-2xl' : 'group-hover:rotate-1 group-hover:scale-110 group-hover:shadow-lg lg:group-hover:shadow-2xl rotate-[-2deg]' )}> <img loading={isLazy ? 'lazy' : 'eager'} src={src} alt={alt} className="aspect-[4/3] h-full w-full flex object-cover rounded-2xl bg-gray-10 dark:bg-gray-80" /> </div> </div> ))} </> ); }); function ExampleLayout({ filename, left, right, activeArea, hoverTopOffset = 0, }) { const contentRef = useRef(null); useNestedScrollLock(contentRef); const [overlayStyles, setOverlayStyles] = useState([]); useEffect(() => { if (activeArea) { const nodes = contentRef.current.querySelectorAll( '[data-hover="' + activeArea.name + '"]' ); const nextOverlayStyles = Array.from(nodes) .map((node) => { const parentRect = contentRef.current.getBoundingClientRect(); const nodeRect = node.getBoundingClientRect(); let top = Math.round(nodeRect.top - parentRect.top) - 8; let bottom = Math.round(nodeRect.bottom - parentRect.top) + 8; let left = Math.round(nodeRect.left - parentRect.left) - 8; let right = Math.round(nodeRect.right - parentRect.left) + 8; top = Math.max(top, hoverTopOffset); bottom = Math.min(bottom, parentRect.height - 12); if (top >= bottom) { return null; } return { width: right - left + 'px', height: bottom - top + 'px', transform: `translate(${left}px, ${top}px)`, }; }) .filter((s) => s !== null); setOverlayStyles(nextOverlayStyles); } }, [activeArea, hoverTopOffset]); return ( <div className="lg:ps-10 lg:pe-5 w-full"> <div className="mt-12 mb-2 lg:my-16 max-w-7xl mx-auto flex flex-col w-full lg:rounded-2xl lg:bg-card lg:dark:bg-card-dark"> <div className="flex-col gap-0 lg:gap-5 lg:rounded-2xl lg:bg-gray-10 lg:dark:bg-gray-70 shadow-inner-border dark:shadow-inner-border-dark lg:flex-row flex grow w-full mx-auto items-center bg-cover bg-center lg:bg-right ltr:lg:bg-[length:60%_100%] bg-no-repeat bg-meta-gradient dark:bg-meta-gradient-dark"> <div className="lg:-m-5 h-full shadow-nav dark:shadow-nav-dark lg:rounded-2xl bg-wash dark:bg-gray-95 w-full flex grow flex-col"> <div className="w-full bg-card dark:bg-wash-dark lg:rounded-t-2xl border-b border-black/5 dark:border-white/5"> <h3 className="text-sm my-1 mx-5 text-tertiary dark:text-tertiary-dark select-none text-start"> {filename} </h3> </div> {left} </div> <div ref={contentRef} className="relative mt-0 lg:-my-20 w-full p-2.5 xs:p-5 lg:p-10 flex grow justify-center"> {right} <div className={cn( 'absolute z-10 inset-0 pointer-events-none transition-opacity transform-gpu', activeArea ? 'opacity-100' : 'opacity-0' )}> {overlayStyles.map((styles, i) => ( <div key={i} className="top-0 start-0 bg-blue-30/5 border-2 border-link dark:border-link-dark absolute rounded-lg" style={styles} /> ))} </div> </div> </div> </div> </div> ); } function useCodeHover(areas) { const [hoverLine, setHoverLine] = useState(null); const area = areas.get(hoverLine); let meta; if (area) { const highlightLines = area.lines ?? [hoverLine]; meta = '```js {' + highlightLines.map((l) => l + 1).join(',') + '}'; } return [area, meta, setHoverLine]; } const example1Areas = new Map([ [2, {name: 'Video'}], [3, {name: 'Thumbnail'}], [4, {name: 'a'}], [5, {name: 'h3'}], [6, {name: 'p'}], [7, {name: 'a'}], [8, {name: 'LikeButton'}], [9, {name: 'Video'}], ]); function Example1() { const [area, meta, onLineHover] = useCodeHover(example1Areas); return ( <ExampleLayout filename="Video.js" activeArea={area} left={ <CodeBlock onLineHover={onLineHover} isFromPackageImport={false} noShadow={true} noMargin={true}> <div meta={meta}>{`function Video({ video }) { return ( <div> <Thumbnail video={video} /> <a href={video.url}> <h3>{video.title}</h3> <p>{video.description}</p> </a> <LikeButton video={video} /> </div> ); } `}</div> </CodeBlock> } right={ <ExamplePanel height="113px"> <Video video={{ id: 'ex1-0', title: 'My video', description: 'Video description', image: 'blue', url: null, }} /> </ExamplePanel> } /> ); } const example2Areas = new Map([ [8, {name: 'VideoList'}], [9, {name: 'h2'}], [11, {name: 'Video', lines: [11]}], [13, {name: 'VideoList'}], ]); function Example2() { const [area, meta, onLineHover] = useCodeHover(example2Areas); const videos = [ { id: 'ex2-0', title: 'First video', description: 'Video description', image: 'blue', }, { id: 'ex2-1', title: 'Second video', description: 'Video description', image: 'red', }, { id: 'ex2-2', title: 'Third video', description: 'Video description', image: 'green', }, ]; return ( <ExampleLayout filename="VideoList.js" activeArea={area} left={ <CodeBlock onLineHover={onLineHover} isFromPackageImport={false} noShadow={true} noMargin={true}> <div meta={meta}>{`function VideoList({ videos, emptyHeading }) { const count = videos.length; let heading = emptyHeading; if (count > 0) { const noun = count > 1 ? 'Videos' : 'Video'; heading = count + ' ' + noun; } return ( <section> <h2>{heading}</h2> {videos.map(video => <Video key={video.id} video={video} /> )} </section> ); }`}</div> </CodeBlock> } right={ <ExamplePanel height="22rem" noShadow={false} noPadding={true}> <div className="m-4"> <VideoList videos={videos} /> </div> </ExamplePanel> } /> ); } const example3Areas = new Map([ [6, {name: 'SearchableVideoList'}], [7, {name: 'SearchInput', lines: [7, 8, 9]}], [8, {name: 'SearchInput', lines: [7, 8, 9]}], [9, {name: 'SearchInput', lines: [7, 8, 9]}], [10, {name: 'VideoList', lines: [10, 11, 12]}], [11, {name: 'VideoList', lines: [10, 11, 12]}], [12, {name: 'VideoList', lines: [10, 11, 12]}], [13, {name: 'SearchableVideoList'}], ]); function Example3() { const [area, meta, onLineHover] = useCodeHover(example3Areas); const videos = [ { id: 'vids-0', title: 'React: The Documentary', description: 'The origin story of React', image: '/images/home/videos/documentary.webp', url: 'https://www.youtube.com/watch?v=8pDqJVdNa44', }, { id: 'vids-1', title: 'Rethinking Best Practices', description: 'Pete Hunt (2013)', image: '/images/home/videos/rethinking.jpg', url: 'https://www.youtube.com/watch?v=x7cQ3mrcKaY', }, { id: 'vids-2', title: 'Introducing React Native', description: 'Tom Occhino (2015)', image: '/images/home/videos/rn.jpg', url: 'https://www.youtube.com/watch?v=KVZ-P-ZI6W4', }, { id: 'vids-3', title: 'Introducing React Hooks', description: 'Sophie Alpert and Dan Abramov (2018)', image: '/images/home/videos/hooks.jpg', url: 'https://www.youtube.com/watch?v=V-QO-KO90iQ', }, { id: 'vids-4', title: 'Introducing Server Components', description: 'Dan Abramov and Lauren Tan (2020)', image: '/images/home/videos/rsc.jpg', url: 'https://www.youtube.com/watch?v=TQQPAU21ZUw', }, ]; return ( <ExampleLayout filename="SearchableVideoList.js" activeArea={area} hoverTopOffset={60} left={ <CodeBlock onLineHover={onLineHover} isFromPackageImport={false} noShadow={true} noMargin={true}> <div meta={meta}>{`import { useState } from 'react'; function SearchableVideoList({ videos }) { const [searchText, setSearchText] = useState(''); const foundVideos = filterVideos(videos, searchText); return ( <> <SearchInput value={searchText} onChange={newText => setSearchText(newText)} /> <VideoList videos={foundVideos} emptyHeading={\`No matches for “\${searchText}”\`} /> </> ); }`}</div> </CodeBlock> } right={ <BrowserChrome domain="example.com" path={'videos.html'}> <ExamplePanel noShadow={false} noPadding={true} contentMarginTop="72px" height="30rem"> <h1 className="mx-4 mb-1 font-bold text-3xl text-primary"> React Videos </h1> <p className="mx-4 mb-0 leading-snug text-secondary text-xl"> A brief history of React </p> <div className="px-4 pb-4"> <SearchableVideoList videos={videos} /> </div> </ExamplePanel> </BrowserChrome> } /> ); } const example4Areas = new Map([ [6, {name: 'ConferenceLayout'}], [7, {name: 'Suspense'}], [8, {name: 'SearchableVideoList'}], [9, {name: 'Suspense'}], [10, {name: 'ConferenceLayout'}], [17, {name: 'SearchableVideoList'}], ]); function Example4() { const [area, meta, onLineHover] = useCodeHover(example4Areas); const [slug, setSlug] = useState('react-conf-2021'); const [animate, setAnimate] = useState(false); function navigate(newSlug) { setSlug(newSlug); setAnimate(true); } return ( <ExampleLayout filename="confs/[slug].js" activeArea={area} hoverTopOffset={60} left={ <CodeBlock onLineHover={onLineHover} isFromPackageImport={false} noShadow={true} noMargin={true}> <div meta={meta}>{`import { db } from './database.js'; import { Suspense } from 'react'; async function ConferencePage({ slug }) { const conf = await db.Confs.find({ slug }); return ( <ConferenceLayout conf={conf}> <Suspense fallback={<TalksLoading />}> <Talks confId={conf.id} /> </Suspense> </ConferenceLayout> ); } async function Talks({ confId }) { const talks = await db.Talks.findAll({ confId }); const videos = talks.map(talk => talk.video); return <SearchableVideoList videos={videos} />; }`}</div> </CodeBlock> } right={ <NavContext.Provider value={{slug, navigate}}> <BrowserChrome domain="example.com" path={'confs/' + slug} hasRefresh={true} hasPulse={true}> <ExamplePanel noPadding={true} noShadow={true} contentMarginTop="56px" height="35rem"> <Suspense fallback={null}> <div style={{animation: animate ? 'fadein 200ms' : null}}> <link rel="preload" href={reactConf2019Cover} as="image" /> <link rel="preload" href={reactConf2021Cover} as="image" /> <ConferencePage slug={slug} /> </div> </Suspense> </ExamplePanel> </BrowserChrome> </NavContext.Provider> } /> ); } function useNestedScrollLock(ref) { useEffect(() => { let node = ref.current; let isLocked = false; let lastScroll = performance.now(); function handleScroll() { if (!isLocked) { isLocked = true; node.style.pointerEvents = 'none'; } lastScroll = performance.now(); } function updateLock() { if (isLocked && performance.now() - lastScroll > 150) { isLocked = false; node.style.pointerEvents = ''; } } window.addEventListener('scroll', handleScroll); const interval = setInterval(updateLock, 60); return () => { window.removeEventListener('scroll', handleScroll); clearInterval(interval); }; }, [ref]); } function ExamplePanel({ children, noPadding, noShadow, height, contentMarginTop, }) { return ( <div className={cn( 'max-w-3xl rounded-2xl mx-auto text-secondary leading-normal bg-white overflow-hidden w-full overflow-y-auto', noShadow ? 'shadow-none' : 'shadow-nav dark:shadow-nav-dark' )} style={{height}}> <div className={noPadding ? 'p-0' : 'p-4'} style={{contentVisibility: 'auto', marginTop: contentMarginTop}}> {children} </div> </div> ); } const NavContext = createContext(null); function BrowserChrome({children, hasPulse, hasRefresh, domain, path}) { const [restartId, setRestartId] = useState(0); const isPulsing = hasPulse && restartId === 0; const [shouldAnimatePulse, setShouldAnimatePulse] = useState(false); const refreshRef = useRef(null); useEffect(() => { if (!isPulsing) { return; } const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { setShouldAnimatePulse(entry.isIntersecting); }); }, { root: null, rootMargin: `0px 0px`, } ); observer.observe(refreshRef.current); return () => observer.disconnect(); }, [isPulsing]); function handleRestart() { confCache = new Map(); talksCache = new Map(); setRestartId((i) => i + 1); } return ( <div className="mx-auto max-w-3xl shadow-nav dark:shadow-nav-dark relative overflow-hidden w-full dark:border-opacity-10 rounded-2xl"> <div className="w-full h-14 rounded-t-2xl shadow-outer-border backdrop-filter overflow-hidden backdrop-blur-lg backdrop-saturate-200 bg-white bg-opacity-90 z-10 absolute top-0 px-3 gap-2 flex flex-row items-center"> <div className="select-none h-8 relative bg-gray-30/20 text-sm text-tertiary text-center rounded-full w-full flex-row flex space-between items-center"> {hasRefresh && <div className="h-4 w-6" />} <div className="w-full leading-snug flex flex-row items-center justify-center"> <svg className="text-tertiary me-1 opacity-60" width="12" height="12" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" clipRule="evenodd" d="M22 4C17.0294 4 13 8.0294 13 13V16H12.3103C10.5296 16 8.8601 16.8343 8.2855 18.5198C7.6489 20.387 7 23.4148 7 28C7 32.5852 7.6489 35.613 8.2855 37.4802C8.8601 39.1657 10.5296 40 12.3102 40H31.6897C33.4704 40 35.1399 39.1657 35.7145 37.4802C36.3511 35.613 37 32.5852 37 28C37 23.4148 36.3511 20.387 35.7145 18.5198C35.1399 16.8343 33.4704 16 31.6897 16H31V13C31 8.0294 26.9706 4 22 4ZM25 16V13C25 11.3431 23.6569 10 22 10C20.3431 10 19 11.3431 19 13V16H25Z" fill="currentColor" /> </svg> <span className="text-gray-30"> {domain} {path != null && '/'} </span> {path} </div> {hasRefresh && ( <div ref={refreshRef} className={cn( 'relative rounded-full flex justify-center items-center ', isPulsing && shouldAnimatePulse && 'animation-pulse-button' )}> {isPulsing && shouldAnimatePulse && ( <div className="z-0 absolute shadow-[0_0_0_8px_rgba(0,0,0,0.5)] inset-0 rounded-full animation-pulse-shadow" /> )} <button aria-label="Reload" onClick={handleRestart} className={ 'z-10 flex items-center p-1.5 rounded-full cursor-pointer justify-center' + // bg-transparent hover:bg-gray-20/50, // but opaque to obscure the pulsing wave. ' bg-[#ebecef] hover:bg-[#d3d7de]' }> <IconRestart className="text-tertiary text-lg" /> </button> </div> )} </div> {restartId > 0 && ( <div key={restartId} className="z-10 loading h-0.5 bg-link transition-all duration-200 absolute bottom-0 start-0" style={{ animation: `progressbar ${loadTalksDelay + 100}ms ease-in-out`, }} /> )} </div> <div className="h-full flex flex-1" key={restartId}> {children} </div> </div> ); } function ConferencePage({slug}) { const conf = use(fetchConf(slug)); return ( <ConferenceLayout conf={conf}> <div data-hover="Suspense"> <Suspense fallback={<TalksLoading />}> <Talks confId={conf.id} /> </Suspense> </div> </ConferenceLayout> ); } function TalksLoading() { return ( <div className="flex flex-col items-center h-[25rem] overflow-hidden"> <div className="w-full"> <div className="relative overflow-hidden before:-skew-x-12 before:absolute before:inset-0 before:-translate-x-full before:animate-[shimmer_2.5s_infinite] before:bg-gradient-to-r before:from-transparent before:via-white/50 before:to-transparent"> <div className="space-y-4"> <div className="pt-4 pb-1"> <div className="h-10 w-full rounded-full bg-gray-10"></div> </div> <div className="pb-1"> <div className="h-5 w-20 rounded-lg bg-gray-10"></div> </div> <div className="flex flex-row items-center gap-3"> <div className="aspect-video w-32 xs:w-36 rounded-lg bg-gray-10"></div> <div className="flex flex-col gap-2"> <div className="h-3 w-40 rounded-lg bg-gray-10"></div> <div className="h-3 w-32 rounded-lg bg-gray-10"></div> <div className="h-3 w-24 rounded-lg bg-gray-10"></div> </div> </div> <div className="flex flex-row items-center gap-3"> <div className="aspect-video w-32 xs:w-36 rounded-lg bg-gray-10"></div> <div className="flex flex-col gap-2"> <div className="h-3 w-40 rounded-lg bg-gray-10"></div> <div className="h-3 w-32 rounded-lg bg-gray-10"></div> <div className="h-3 w-24 rounded-lg bg-gray-10"></div> </div> </div> <div className="flex flex-row items-center gap-3"> <div className="aspect-video w-32 xs:w-36 rounded-lg bg-gray-10"></div> <div className="flex flex-col gap-2"> <div className="h-3 w-40 rounded-lg bg-gray-10"></div> <div className="h-3 w-32 rounded-lg bg-gray-10"></div> <div className="h-3 w-24 rounded-lg bg-gray-10"></div> </div> </div> <div className="flex flex-row items-center gap-3"> <div className="aspect-video w-32 xs:w-36 rounded-lg bg-gray-10"></div> <div className="flex flex-col gap-2"> <div className="h-3 w-40 rounded-lg bg-gray-10"></div> <div className="h-3 w-32 rounded-lg bg-gray-10"></div> <div className="h-3 w-24 rounded-lg bg-gray-10"></div> </div> </div> </div> </div> </div> </div> ); } function Talks({confId}) { const videos = use(fetchTalks(confId)); return <SearchableVideoList videos={videos} />; } function SearchableVideoList({videos}) { const [searchText, setSearchText] = useState(''); const foundVideos = filterVideos(videos, searchText); return ( <div className="mt-3" data-hover="SearchableVideoList"> <SearchInput value={searchText} onChange={setSearchText} /> <VideoList videos={foundVideos} emptyHeading={`No matches for “${searchText}”`} /> </div> ); } function filterVideos(videos, query) { const keywords = query .toLowerCase() .split(' ') .filter((s) => s !== ''); if (keywords.length === 0) { return videos; } return videos.filter((video) => { const words = (video.title + ' ' + video.description) .toLowerCase() .split(' '); return keywords.every((kw) => words.some((w) => w.startsWith(kw))); }); } function VideoList({videos, emptyHeading}) { let heading = emptyHeading; const count = videos.length; if (count > 0) { const noun = count > 1 ? 'Videos' : 'Video'; heading = count + ' ' + noun; } return ( <section className="relative" data-hover="VideoList"> <h2 className="font-bold text-xl text-primary mb-4 leading-snug" data-hover="h2"> {heading} </h2> <div className="flex flex-col gap-4"> {videos.map((video) => ( <Video key={video.id} video={video} /> ))} </div> </section> ); } function SearchInput({value, onChange}) { const id = useId(); return ( <form className="mb-3 py-1" data-hover="SearchInput" onSubmit={(e) => e.preventDefault()}> <label htmlFor={id} className="sr-only"> Search </label> <div className="relative w-full"> <div className="absolute inset-y-0 start-0 flex items-center ps-4 pointer-events-none"> <IconSearch className="text-gray-30 w-4" /> </div> <input type="text" id={id} className="flex ps-11 py-4 h-10 w-full text-start bg-secondary-button outline-none betterhover:hover:bg-opacity-80 pointer items-center text-primary rounded-full align-middle text-base" placeholder="Search" value={value} onChange={(e) => onChange(e.target.value)} /> </div> </form> ); } function ConferenceLayout({conf, children}) { const {slug, navigate} = useContext(NavContext); const [isPending, startTransition] = useTransition(); return ( <div className={cn( 'transition-opacity delay-100', isPending ? 'opacity-90' : 'opacity-100' )} data-hover="ConferenceLayout"> <Cover background={conf.cover}> <select aria-label="Event" defaultValue={slug} onChange={(e) => { startTransition(() => { navigate(e.target.value); }); }} className="appearance-none pe-8 ps-2 bg-transparent text-primary-dark text-2xl font-bold mb-0.5" style={{ backgroundSize: '4px 4px, 4px 4px', backgroundRepeat: 'no-repeat', backgroundPosition: 'calc(100% - 20px) calc(1px + 50%),calc(100% - 16px) calc(1px + 50%)', backgroundImage: 'linear-gradient(45deg,transparent 50%,currentColor 50%),linear-gradient(135deg,currentColor 50%,transparent 50%)', }}> <option className="bg-wash dark:bg-wash-dark text-primary dark:text-primary-dark" value="react-conf-2021"> React Conf 2021 </option> <option className="bg-wash dark:bg-wash-dark text-primary dark:text-primary-dark" value="react-conf-2019"> React Conf 2019 </option> </select> </Cover> <div className="px-4 pb-4" key={conf.id}> {children} </div> </div> ); } function Cover({background, children}) { return ( <div className="h-40 overflow-hidden relative items-center flex"> <div className="absolute inset-0 px-4 py-2 flex items-end bg-gradient-to-t from-black/40 via-black/0"> {children} </div> <img src={background} width={500} height={263} alt="" className="w-full object-cover" /> </div> ); } function Video({video}) { return ( <div className="flex flex-row items-center gap-3" data-hover="Video"> <Thumbnail video={video} /> <a href={video.url} target="_blank" rel="noreferrer" className="outline-link dark:outline-link outline-offset-4 group flex flex-col flex-1 gap-0.5" data-hover="a"> <h3 className={cn( 'text-base leading-tight text-primary font-bold', video.url && 'group-hover:underline' )} data-hover="h3"> {video.title} </h3> <p className="text-tertiary text-sm leading-snug" data-hover="p"> {video.description} </p> </a> <LikeButton video={video} /> </div> ); } function Code({children}) { return ( <code dir="ltr" className="font-mono inline rounded-lg bg-gray-15/40 dark:bg-secondary-button-dark py-0.5 px-1 text-left"> {children} </code> ); } function Thumbnail({video}) { const {image} = video; return ( <a data-hover="Thumbnail" href={video.url} target="_blank" rel="noreferrer" aria-hidden="true" tabIndex={-1} className={cn( 'outline-link dark:outline-link outline-offset-2 aspect-video w-32 xs:w-36 select-none flex-col shadow-inner-border rounded-lg flex items-center overflow-hidden justify-center align-middle text-white/50 bg-cover bg-white bg-[conic-gradient(at_top_right,_var(--tw-gradient-stops))]', image === 'blue' && 'from-yellow-50 via-blue-50 to-purple-60', image === 'red' && 'from-yellow-50 via-red-50 to-purple-60', image === 'green' && 'from-yellow-50 via-green-50 to-purple-60', image === 'purple' && 'from-yellow-50 via-purple-50 to-purple-60', typeof image === 'object' && 'from-gray-80 via-gray-95 to-gray-70', video.url && 'hover:opacity-95 transition-opacity' )} style={{ backgroundImage: typeof image === 'string' && image.startsWith('/') ? 'url(' + image + ')' : null, }}> {typeof image !== 'string' ? ( <> <div className="transition-opacity mt-2.5 -space-x-2 flex flex-row w-full justify-center"> {image.speakers.map((src, i) => ( <img key={i} className="h-8 w-8 border-2 shadow-md border-gray-70 object-cover rounded-full" src={src} alt="" /> ))} </div> <div className="mt-1"> <span className="inline-flex text-xs font-normal items-center text-primary-dark py-1 whitespace-nowrap outline-link px-1.5 rounded-lg"> <Logo className="text-xs me-1 w-4 h-4 text-link-dark" /> React Conf </span> </div> </> ) : image.startsWith('/') ? null : ( <ThumbnailPlaceholder /> )} </a> ); } function ThumbnailPlaceholder() { return ( <svg className="drop-shadow-xl" width="36" height="36" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" clipRule="evenodd" d="M36 69C54.2254 69 69 54.2254 69 36C69 17.7746 54.2254 3 36 3C17.7746 3 3 17.7746 3 36C3 54.2254 17.7746 69 36 69ZM52.1716 38.6337L28.4366 51.5801C26.4374 52.6705 24 51.2235 24 48.9464V23.0536C24 20.7764 26.4374 19.3295 28.4366 20.4199L52.1716 33.3663C54.2562 34.5034 54.2562 37.4966 52.1716 38.6337Z" fill="currentColor" /> </svg> ); } // A hack since we don't actually have a backend. // Unlike local state, this survives videos being filtered. const likedVideos = new Set(); function LikeButton({video}) { const [isLiked, setIsLiked] = useState(() => likedVideos.has(video.id)); const [animate, setAnimate] = useState(false); return ( <button data-hover="LikeButton" className={cn( 'outline-none focus:bg-red-50/5 focus:text-red-50 relative flex items-center justify-center w-10 h-10 cursor-pointer rounded-full hover:bg-card active:scale-95 active:bg-red-50/5 active:text-red-50', isLiked ? 'text-red-50' : 'text-tertiary' )} aria-label={isLiked ? 'Unsave' : 'Save'} onClick={() => { const nextIsLiked = !isLiked; if (nextIsLiked) { likedVideos.add(video.id); } else { likedVideos.delete(video.id); } setAnimate(true); setIsLiked(nextIsLiked); }}> <svg className="absolute overflow-visible" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle className={cn( 'text-red-50/50 origin-center transition-all ease-in-out', isLiked && animate && 'animate-[circle_.3s_forwards]' )} cx="12" cy="12" r="11.5" fill="transparent" strokeWidth="0" stroke="currentColor" /> </svg> {isLiked ? ( <svg className={cn( 'w-6 h-6 origin-center transition-all ease-in-out', isLiked && animate && 'animate-[scale_.35s_ease-in-out_forwards]' )} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M12 23a.496.496 0 0 1-.26-.074C7.023 19.973 0 13.743 0 8.68c0-4.12 2.322-6.677 6.058-6.677 2.572 0 5.108 2.387 5.134 2.41l.808.771.808-.771C12.834 4.387 15.367 2 17.935 2 21.678 2 24 4.558 24 8.677c0 5.06-7.022 11.293-11.74 14.246a.496.496 0 0 1-.26.074V23z" fill="currentColor" /> </svg> ) : ( <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" clipRule="evenodd" d="m12 5.184-.808-.771-.004-.004C11.065 4.299 8.522 2.003 6 2.003c-3.736 0-6 2.558-6 6.677 0 4.47 5.471 9.848 10 13.079.602.43 1.187.82 1.74 1.167A.497.497 0 0 0 12 23v-.003c.09 0 .182-.026.26-.074C16.977 19.97 24 13.737 24 8.677 24 4.557 21.743 2 18 2c-2.569 0-5.166 2.387-5.192 2.413L12 5.184zm-.002 15.525c2.071-1.388 4.477-3.342 6.427-5.47C20.72 12.733 22 10.401 22 8.677c0-1.708-.466-2.855-1.087-3.55C20.316 4.459 19.392 4 18 4c-.726 0-1.63.364-2.5.9-.67.412-1.148.82-1.266.92-.03.025-.037.031-.019.014l-.013.013L12 7.949 9.832 5.88a10.08 10.08 0 0 0-1.33-.977C7.633 4.367 6.728 4.003 6 4.003c-1.388 0-2.312.459-2.91 1.128C2.466 5.826 2 6.974 2 8.68c0 1.726 1.28 4.058 3.575 6.563 1.948 2.127 4.352 4.078 6.423 5.466z" fill="currentColor" /> </svg> )} </button> ); } function SvgContainer({children}) { return ( <svg className="w-16 h-16 lg:w-20 lg:h-20 rounded-2xl lg:rounded-3xl shadow-nav bg-wash" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg"> {children} </svg> ); } function NativeIcons() { return ( <div className="flex items-center justify-center gap-5"> <SvgContainer> <path d="M89.9356 44.0658C89.4752 44.4231 81.3451 49.0042 81.3451 59.1906C81.3451 70.9729 91.6903 75.1411 91.9999 75.2443C91.9523 75.4984 90.3564 80.9529 86.5455 86.5105C83.1474 91.4013 79.5984 96.2841 74.1995 96.2841C68.8006 96.2841 67.4112 93.148 61.1787 93.148C55.105 93.148 52.9454 96.3873 48.007 96.3873C43.0686 96.3873 39.6229 91.8618 35.6611 86.3041C31.072 79.7778 27.3643 69.639 27.3643 60.0163C27.3643 44.5819 37.3998 36.3963 47.2766 36.3963C52.5246 36.3963 56.8993 39.842 60.1942 39.842C63.3303 39.842 68.221 36.1898 74.1916 36.1898C76.4543 36.1898 84.5844 36.3963 89.9356 44.0658ZM71.3572 29.6556C73.8264 26.7259 75.573 22.6609 75.573 18.5958C75.573 18.0321 75.5254 17.4605 75.4222 17C71.4048 17.1509 66.6252 19.6756 63.7432 23.0182C61.4804 25.5906 59.3685 29.6556 59.3685 33.7762C59.3685 34.3955 59.4717 35.0148 59.5193 35.2133C59.7734 35.2609 60.1863 35.3165 60.5991 35.3165C64.2036 35.3165 68.7371 32.9029 71.3572 29.6556Z" fill="black" /> </SvgContainer> <SvgContainer> <path d="M22.1378 84.6843C19.1119 84.6843 16 87.1151 16 91.363C16 95.259 18.7358 98 22.1378 98C24.9457 98 26.1963 96.1105 26.1963 96.1105V96.9286C26.2071 97.1436 26.2971 97.3469 26.4489 97.4991C26.6008 97.6513 26.8036 97.7416 27.018 97.7523H29.0473V84.9626H26.1963V86.5864C26.1963 86.5864 24.9346 84.6843 22.1378 84.6843ZM22.6458 87.3002C25.1359 87.3002 26.4434 89.4958 26.4434 91.3686C26.4434 93.4557 24.8916 95.4371 22.65 95.4371C20.7775 95.4371 18.9023 93.9163 18.9023 91.3422C18.9009 89.0102 20.5152 87.2932 22.6458 87.2932V87.3002Z" fill="black" /> <path d="M33.01 97.7636C32.9013 97.7667 32.793 97.7475 32.692 97.7072C32.5909 97.6669 32.4991 97.6063 32.4222 97.5292C32.3452 97.4521 32.2848 97.3601 32.2446 97.2587C32.2044 97.1574 32.1852 97.0489 32.1883 96.9399V84.9628H35.0407V86.5462C35.6861 85.5722 36.9478 84.6692 38.8855 84.6692C42.0529 84.6692 43.7435 87.1988 43.7435 89.5655V97.7636H41.7573C41.5268 97.7625 41.3061 97.6703 41.1431 97.5069C40.9801 97.3435 40.8881 97.1223 40.887 96.8912V90.2C40.887 88.8893 40.0861 87.2962 38.2317 87.2962C36.2316 87.2962 35.0393 89.1912 35.0393 90.975V97.7636H33.01Z" fill="black" /> <path d="M52.0506 84.6843C49.0248 84.6843 45.9128 87.1151 45.9128 91.363C45.9128 95.259 48.6486 98 52.0506 98C54.8641 98 56.1133 96.1105 56.1133 96.1105V96.9286C56.1241 97.1436 56.2141 97.3469 56.3659 97.4991C56.5178 97.6513 56.7206 97.7416 56.9351 97.7523H58.9643V78.5747H56.1133V86.5919C56.1133 86.5919 54.8475 84.6843 52.0506 84.6843ZM52.5586 87.3002C55.0487 87.3002 56.3562 89.4958 56.3562 91.3686C56.3562 93.4557 54.8045 95.4371 52.5628 95.4371C50.6904 95.4371 48.8152 93.9163 48.8152 91.3422C48.8138 89.0102 50.4225 87.2932 52.5586 87.2932V87.3002Z" fill="black" /> <path d="M62.9232 97.7634C62.8145 97.7665 62.7064 97.7473 62.6054 97.707C62.5044 97.6667 62.4126 97.6061 62.3358 97.5289C62.259 97.4518 62.1987 97.3598 62.1587 97.2584C62.1186 97.1571 62.0996 97.0487 62.1029 96.9397V84.9626H64.9539V87.0942C65.4438 85.9004 66.5029 84.8179 68.385 84.8179C68.7253 84.8211 69.0648 84.8532 69.3997 84.9139V87.8692C68.9654 87.7128 68.5078 87.631 68.0464 87.6271C66.0462 87.6271 64.9539 89.5222 64.9539 91.3073V97.7634H62.9232Z" fill="black" /> <path d="M86.6997 97.7635C86.591 97.7668 86.4826 97.7477 86.3815 97.7075C86.2803 97.6673 86.1884 97.6067 86.1114 97.5295C86.0345 97.4524 85.9741 97.3603 85.9339 97.2589C85.8938 97.1574 85.8748 97.0489 85.878 96.9398V84.9626H88.7318V97.7635H86.6997Z" fill="black" /> <path d="M97.089 84.6843C94.0632 84.6843 90.9526 87.1151 90.9526 91.363C90.9526 95.259 93.6884 98 97.089 98C99.897 98 101.149 96.1105 101.149 96.1105V96.9286C101.16 97.1436 101.25 97.3469 101.402 97.4991C101.553 97.6513 101.756 97.7416 101.971 97.7523H104V78.5747H101.149V86.5919C101.149 86.5919 99.8873 84.6843 97.089 84.6843ZM97.5971 87.3002C100.095 87.3002 101.395 89.4958 101.395 91.3686C101.395 93.4557 99.8429 95.4371 97.6026 95.4371C95.7288 95.4371 93.855 93.9163 93.855 91.3422C93.8536 89.0102 95.4678 87.2932 97.5971 87.2932V87.3002Z" fill="black" /> <path d="M87.2813 82.2103C88.3231 82.2103 89.1676 81.3637 89.1676 80.3194C89.1676 79.2751 88.3231 78.4285 87.2813 78.4285C86.2395 78.4285 85.395 79.2751 85.395 80.3194C85.395 81.3637 86.2395 82.2103 87.2813 82.2103Z" fill="black" /> <path d="M76.9184 84.6731C73.7496 84.6731 70.2712 87.0496 70.2712 91.3407C70.2712 95.2547 73.236 97.9999 76.9143 97.9999C81.4475 97.9999 83.66 94.3475 83.66 91.3643C83.66 87.705 80.8104 84.6731 76.9212 84.6731H76.9184ZM76.9282 87.3432C79.1198 87.3432 80.7549 89.1131 80.7549 91.3476C80.7549 93.6226 79.0199 95.3827 76.9351 95.3827C75.0002 95.3827 73.1194 93.8035 73.1194 91.3922C73.1194 88.9405 74.9086 87.3488 76.9282 87.3488V87.3432Z" fill="black" /> <path d="M81.4769 35.895L88.7723 23.2263C88.9677 22.8863 89.021 22.4826 88.9207 22.1034C88.8203 21.7241 88.5743 21.4 88.2365 21.2018C88.0696 21.1035 87.8848 21.0394 87.693 21.0133C87.5011 20.9871 87.306 20.9993 87.119 21.0493C86.9319 21.0992 86.7566 21.1859 86.6031 21.3043C86.4497 21.4227 86.3213 21.5704 86.2253 21.7389L78.8355 34.5704C73.196 31.988 66.85 30.5493 60.0237 30.5493C53.1975 30.5493 46.8501 31.988 41.212 34.5704L33.8208 21.7389C33.7265 21.565 33.5983 21.4118 33.4439 21.2884C33.2895 21.165 33.1119 21.0739 32.9217 21.0205C32.7316 20.9671 32.5326 20.9524 32.3367 20.9774C32.1408 21.0025 31.9519 21.0666 31.7811 21.1661C31.6104 21.2656 31.4613 21.3984 31.3427 21.5567C31.224 21.715 31.1383 21.8955 31.0904 22.0876C31.0426 22.2797 31.0337 22.4794 31.0643 22.675C31.0948 22.8706 31.1642 23.0581 31.2683 23.2263L38.5623 35.895C25.9827 42.7268 17.4645 55.4915 16.0557 70.4337H104C102.587 55.4915 94.0661 42.7268 81.4769 35.895ZM39.8365 58.053C39.1072 58.0533 38.3943 57.8368 37.7878 57.4308C37.1814 57.0248 36.7086 56.4477 36.4294 55.7723C36.1502 55.097 36.0771 54.3538 36.2193 53.6368C36.3615 52.9199 36.7126 52.2612 37.2283 51.7443C37.744 51.2274 38.401 50.8754 39.1162 50.7329C39.8315 50.5903 40.5728 50.6636 41.2465 50.9435C41.9202 51.2234 42.496 51.6973 42.9009 52.3052C43.3059 52.9131 43.5219 53.6278 43.5217 54.3589C43.5209 55.3389 43.132 56.2785 42.4405 56.9712C41.749 57.6639 40.8113 58.053 39.8337 58.053H39.8365ZM80.2068 58.053C79.4776 58.053 78.7648 57.8363 78.1585 57.4301C77.5523 57.024 77.0798 56.4467 76.8008 55.7714C76.5218 55.096 76.4488 54.3529 76.5912 53.636C76.7336 52.9191 77.0848 52.2606 77.6005 51.7438C78.1162 51.2271 78.7733 50.8752 79.4885 50.7328C80.2037 50.5903 80.945 50.6637 81.6186 50.9436C82.2922 51.2235 82.8679 51.6974 83.2728 52.3053C83.6777 52.9133 83.8937 53.6279 83.8934 54.3589C83.8932 54.8443 83.7976 55.3249 83.6121 55.7733C83.4266 56.2217 83.1548 56.629 82.8122 56.9721C82.4695 57.3152 82.0629 57.5872 81.6154 57.7727C81.1679 57.9581 80.6883 58.0534 80.2041 58.053H80.2068Z" fill="#32DE84" /> </SvgContainer> </div> ); } function WebIcons() { return ( <div className="flex items-center justify-center gap-3"> <SvgContainer> <g clipPath="url(#ee)"> <path d="m60 81.99c12.15 0 22-9.8497 22-22 0-12.15-9.8497-22-22-22s-22 9.8498-22 22c0 12.15 9.8497 22 22 22z" fill="#fff" /> <path d="m60 38h38.099c-3.8606-6.6892-9.4144-12.244-16.103-16.106-6.6884-3.862-14.276-5.8948-21.999-5.8943-7.7232 5e-4 -15.31 2.0345-21.998 5.8973-6.6879 3.8629-12.241 9.4184-16.101 16.108l19.05 32.995 0.017-0.0044c-1.9378-3.3417-2.9604-7.1352-2.9648-10.998-0.0043-3.8629 1.0098-7.6586 2.9401-11.005 1.9303-3.346 4.7086-6.124 8.0548-8.0539 3.3463-1.93 7.1422-2.9437 11.005-2.9389z" fill="url(#cc)" /> <path d="m60 77.417c9.619 0 17.417-7.7977 17.417-17.417 0-9.6189-7.7977-17.417-17.417-17.417-9.6189 0-17.417 7.7977-17.417 17.417 0 9.619 7.7977 17.417 17.417 17.417z" fill="#1A73E8" /> <path d="m79.05 71.006-19.05 32.994c7.7233 1e-3 15.311-2.031 21.999-5.8925 6.6886-3.8614 12.243-9.4158 16.104-16.105 3.8607-6.6888 5.8927-14.276 5.8917-22-1e-3 -7.7232-2.036-15.31-5.8996-21.997h-38.099l-0.0045 0.017c3.8629-0.0074 7.6595 1.0036 11.007 2.9313 3.3476 1.9277 6.1278 4.7038 8.0604 8.0485s2.9492 7.1398 2.9474 11.003c-0.0017 3.8629-1.0219 7.657-2.9575 11z" fill="url(#bb)" /> <path d="m40.949 71.006-19.049-32.995c-3.8626 6.688-5.8963 14.275-5.8966 21.998s2.0328 15.31 5.8949 21.999 9.4171 12.242 16.106 16.102c6.6893 3.8603 14.277 5.8913 22 5.8893l19.049-32.994-0.0123-0.0124c-1.925 3.349-4.699 6.1314-8.0422 8.0666s-7.1375 2.9549-11 2.9562-7.6579-1.0158-11.002-2.9488c-3.3445-1.9329-6.1203-4.7134-8.0476-8.0612z" fill="url(#aa)" /> </g> <defs> <linearGradient id="cc" x1="21.898" x2="98.099" y1="43.5" y2="43.5" gradientUnits="userSpaceOnUse"> <stop stopColor="#D93025" offset="0" /> <stop stopColor="#EA4335" offset="1" /> </linearGradient> <linearGradient id="bb" x1="53.99" x2="92.09" y1="103.41" y2="37.42" gradientUnits="userSpaceOnUse"> <stop stopColor="#FCC934" offset="0" /> <stop stopColor="#FBBC04" offset="1" /> </linearGradient> <linearGradient id="aa" x1="64.763" x2="26.663" y1="101.25" y2="35.261" gradientUnits="userSpaceOnUse"> <stop stopColor="#1E8E3E" offset="0" /> <stop stopColor="#34A853" offset="1" /> </linearGradient> <clipPath id="ee"> <rect transform="translate(16 16)" width="88" height="88" fill="#fff" /> </clipPath> </defs> </SvgContainer> <SvgContainer> <path d="m101.3 42.856c-1.9371-4.6598-5.8655-9.691-8.9417-11.282 2.1941 4.2494 3.7168 8.8131 4.5137 13.529l0.0081 0.0748c-5.0393-12.564-13.585-17.63-20.564-28.66-0.3605-0.5624-0.7106-1.1313-1.05-1.7066-0.175-0.3005-0.3388-0.6074-0.491-0.92-0.2895-0.5606-0.5126-1.153-0.6647-1.7653 2e-4 -0.0282-0.01-0.0556-0.0287-0.0768s-0.0445-0.0348-0.0725-0.0382c-0.0275-0.0075-0.0565-0.0075-0.084 0-0.0057 0-0.0149 0.0104-0.0218 0.0127s-0.0219 0.0126-0.0322 0.0172l0.0172-0.0299c-11.195 6.555-14.994 18.69-15.343 24.76-4.4708 0.3074-8.7453 1.9549-12.266 4.7277-0.3673-0.3111-0.7512-0.6021-1.15-0.8717-1.0156-3.5547-1.0588-7.3168-0.1253-10.894-4.1114 1.9917-7.7645 4.8151-10.728 8.2915h-0.0207c-1.7664-2.239-1.6422-9.622-1.541-11.164-0.5225 0.21-1.0214 0.4749-1.4881 0.7901-1.5593 1.1129-3.0171 2.3617-4.3562 3.7317-1.5259 1.5472-2.9196 3.2193-4.1664 4.9991v0.0069-0.0081c-2.8656 4.0625-4.898 8.6523-5.98 13.504l-0.0598 0.2944c-0.1644 0.9247-0.3105 1.8525-0.4382 2.783 0 0.0333-0.0069 0.0644-0.0103 0.0977-0.3902 2.0279-0.6319 4.0815-0.7234 6.1445v0.23c0.0098 11.16 4.2056 21.91 11.758 30.126 7.5526 8.216 17.912 13.3 29.032 14.247s22.19-2.312 31.023-9.132c8.8332-6.8204 14.786-16.706 16.683-27.704 0.075-0.575 0.136-1.1443 0.203-1.725 0.918-7.5875-0.076-15.284-2.891-22.389zm-51.371 34.889c0.2082 0.1001 0.4037 0.2082 0.6176 0.3036l0.031 0.0196c-0.2162-0.1035-0.4324-0.2112-0.6486-0.3232zm46.954-32.556v-0.0425l0.0081 0.0471-0.0081-0.0046z" fill="url(#l)" /> <path d="m101.3 42.856c-1.9371-4.6598-5.8655-9.691-8.9417-11.282 2.1941 4.2494 3.7168 8.8131 4.5137 13.529v0.0426l0.0081 0.0471c3.4349 9.8307 2.9384 20.609-1.3869 30.082-5.1083 10.961-17.473 22.195-36.828 21.649-20.913-0.5923-39.33-16.11-42.773-36.436-0.6268-3.205 0-4.83 0.3151-7.4347-0.4299 2.0233-0.6697 4.0823-0.7165 6.1502v0.23c0.0098 11.16 4.2056 21.91 11.758 30.126 7.5526 8.216 17.912 13.3 29.032 14.247s22.19-2.312 31.023-9.1321c8.8332-6.8204 14.786-16.706 16.683-27.704 0.075-0.575 0.136-1.1443 0.203-1.725 0.918-7.5875-0.076-15.284-2.891-22.389z" fill="url(#i)" /> <path d="m101.3 42.856c-1.9371-4.6598-5.8655-9.691-8.9417-11.282 2.1941 4.2494 3.7168 8.8131 4.5137 13.529v0.0426l0.0081 0.0471c3.4349 9.8307 2.9384 20.609-1.3869 30.082-5.1083 10.961-17.473 22.195-36.828 21.649-20.913-0.5923-39.33-16.11-42.773-36.436-0.6268-3.205 0-4.83 0.3151-7.4347-0.4299 2.0233-0.6697 4.0823-0.7165 6.1502v0.23c0.0098 11.16 4.2056 21.91 11.758 30.126 7.5526 8.216 17.912 13.3 29.032 14.247s22.19-2.312 31.023-9.1321c8.8332-6.8204 14.786-16.706 16.683-27.704 0.075-0.575 0.136-1.1443 0.203-1.725 0.918-7.5875-0.076-15.284-2.891-22.389z" fill="url(#h)" /> <path d="m79.644 48.095c0.0966 0.0678 0.1863 0.1357 0.2772 0.2035-1.1196-1.9852-2.5133-3.8028-4.14-5.3992-13.853-13.855-3.6306-30.042-1.9067-30.864l0.0172-0.0253c-11.195 6.555-14.994 18.69-15.343 24.76 0.5198-0.0357 1.035-0.0794 1.5663-0.0794 3.9723 0.0073 7.8719 1.0664 11.302 3.0696 3.4303 2.0031 6.2689 4.879 8.2272 8.335z" fill="url(#g)" /> <path d="m60.144 50.862c-0.0736 1.1086-3.9905 4.9323-5.3602 4.9323-12.674 0-14.732 7.6671-14.732 7.6671 0.5612 6.4561 5.06 11.774 10.498 14.587 0.2484 0.1288 0.5002 0.2449 0.7521 0.3588 0.4362 0.1932 0.8724 0.3718 1.3087 0.5359 1.8664 0.6605 3.8212 1.0377 5.7994 1.1189 22.215 1.0419 26.518-26.565 10.487-34.576 3.7818-0.492 7.6116 0.4378 10.747 2.6094-1.9583-3.4561-4.7969-6.3319-8.2272-8.3351-3.4302-2.0031-7.3298-3.0622-11.302-3.0695-0.529 0-1.0465 0.0437-1.5663 0.0794-4.4708 0.3073-8.7453 1.9548-12.266 4.7276 0.6797 0.575 1.4467 1.3432 3.0625 2.936 3.0245 2.9796 10.781 6.0662 10.798 6.4285z" fill="url(#f)" /> <path d="m60.144 50.862c-0.0736 1.1086-3.9905 4.9323-5.3602 4.9323-12.674 0-14.732 7.6671-14.732 7.6671 0.5612 6.4561 5.06 11.774 10.498 14.587 0.2484 0.1288 0.5002 0.2449 0.7521 0.3588 0.4362 0.1932 0.8724 0.3718 1.3087 0.5359 1.8664 0.6605 3.8212 1.0377 5.7994 1.1189 22.215 1.0419 26.518-26.565 10.487-34.576 3.7818-0.492 7.6116 0.4378 10.747 2.6094-1.9583-3.4561-4.7969-6.3319-8.2272-8.3351-3.4302-2.0031-7.3298-3.0622-11.302-3.0695-0.529 0-1.0465 0.0437-1.5663 0.0794-4.4708 0.3073-8.7453 1.9548-12.266 4.7276 0.6797 0.575 1.4467 1.3432 3.0625 2.936 3.0245 2.9796 10.781 6.0662 10.798 6.4285z" fill="url(#e)" /> <path d="m44.205 40.015c0.3611 0.23 0.6589 0.4301 0.92 0.6107-1.0156-3.5547-1.0589-7.3168-0.1254-10.894-4.1113 1.9917-7.7644 4.8151-10.728 8.2915 0.2173-0.0057 6.6826-0.1219 9.9337 1.9918z" fill="url(#d)" /> <path d="m15.902 60.487c3.4397 20.325 21.86 35.843 42.773 36.436 19.354 0.5474 31.719-10.688 36.828-21.649 4.3254-9.4729 4.8223-20.251 1.3869-30.082v-0.0425c0-0.0334-0.0069-0.0529 0-0.0426l0.0081 0.0748c1.5812 10.324-3.6697 20.325-11.878 27.088l-0.0253 0.0575c-15.994 13.026-31.301 7.8591-34.399 5.75-0.2162-0.1035-0.4324-0.2112-0.6486-0.3231-9.3253-4.4574-13.178-12.954-12.352-20.24-2.2137 0.0326-4.3893-0.5774-6.2632-1.7561-1.874-1.1788-3.3659-2.8757-4.295-4.8852 2.4479-1.4997 5.2391-2.3475 8.1075-2.4626 2.8685-0.1152 5.7186 0.5062 8.2789 1.8048 5.2783 2.3962 11.285 2.6323 16.735 0.6578-0.0173-0.3622-7.774-3.45-10.798-6.4285-1.6158-1.5927-2.3828-2.3598-3.0625-2.9359-0.3673-0.3112-0.7512-0.6022-1.15-0.8717-0.2645-0.1806-0.5623-0.3761-0.92-0.6107-3.251-2.1137-9.7163-1.9975-9.9302-1.9918h-0.0207c-1.7664-2.239-1.6422-9.622-1.541-11.164-0.5226 0.21-1.0214 0.4749-1.4881 0.7901-1.5594 1.1129-3.0171 2.3617-4.3562 3.7317-1.5314 1.5428-2.9309 3.2111-4.1837 4.9876v0.0069-0.0081c-2.8656 4.0624-4.898 8.6523-5.98 13.504-0.0219 0.0908-1.6054 7.0138-0.8246 10.604z" fill="url(#c)" /> <path d="m75.784 42.9c1.6271 1.5982 3.0208 3.4178 4.14 5.405 0.2449 0.1852 0.4738 0.3692 0.6681 0.5474 10.105 9.315 4.8105 22.482 4.416 23.42 8.2087-6.7632 13.455-16.765 11.878-27.088-5.0416-12.57-13.587-17.635-20.567-28.666-0.3605-0.5624-0.7106-1.1313-1.05-1.7066-0.175-0.3005-0.3388-0.6074-0.491-0.92-0.2895-0.5606-0.5126-1.153-0.6647-1.7653 2e-4 -0.0282-0.01-0.0556-0.0287-0.0768s-0.0445-0.0348-0.0725-0.0382c-0.0275-0.0075-0.0565-0.0075-0.084 0-0.0057 0-0.0149 0.0104-0.0218 0.0127s-0.0219 0.0126-0.0322 0.0172c-1.7239 0.8177-11.946 17.004 1.909 30.859z" fill="url(#b)" /> <path d="m80.585 48.846c-0.2142-0.1927-0.4371-0.3754-0.6682-0.5474-0.0908-0.0679-0.1805-0.1357-0.2771-0.2036-3.1351-2.1715-6.965-3.1014-10.747-2.6093 16.031 8.0155 11.73 35.618-10.487 34.576-1.9781-0.0812-3.933-0.4584-5.7994-1.119-0.4362-0.1633-0.8725-0.3419-1.3087-0.5359-0.2519-0.115-0.5037-0.23-0.7521-0.3588l0.031 0.0196c3.0981 2.1148 18.4 7.2818 34.399-5.75l0.0253-0.0575c0.399-0.9315 5.6936-14.102-4.416-23.414z" fill="url(#a)" /> <path d="m40.052 63.462s2.0573-7.667 14.732-7.667c1.3696 0 5.29-3.8238 5.3601-4.9324-5.4501 1.9745-11.456 1.7384-16.735-0.6578-2.5602-1.2986-5.4104-1.9199-8.2788-1.8048-2.8684 0.1152-5.6596 0.963-8.1075 2.4626 0.9291 2.0095 2.421 3.7064 4.2949 4.8852 1.874 1.1788 4.0496 1.7888 6.2632 1.7561-0.8257 7.2875 3.0268 15.784 12.352 20.24 0.2081 0.1 0.4036 0.2081 0.6175 0.3036-5.4429-2.8118-9.9371-8.1294-10.498-14.586z" fill="url(#k)" /> <path d="m101.3 42.856c-1.9371-4.6598-5.8655-9.691-8.9417-11.282 2.1941 4.2494 3.7168 8.8131 4.5137 13.529l0.0081 0.0748c-5.0393-12.564-13.585-17.63-20.564-28.66-0.3605-0.5624-0.7106-1.1313-1.05-1.7066-0.175-0.3005-0.3388-0.6074-0.491-0.92-0.2895-0.5606-0.5126-1.153-0.6647-1.7653 2e-4 -0.0282-0.01-0.0556-0.0287-0.0768s-0.0445-0.0348-0.0725-0.0382c-0.0275-0.0075-0.0565-0.0075-0.084 0-0.0057 0-0.0149 0.0104-0.0218 0.0127s-0.0219 0.0126-0.0322 0.0172l0.0172-0.0299c-11.195 6.555-14.994 18.69-15.343 24.76 0.5198-0.0356 1.035-0.0793 1.5663-0.0793 3.9723 0.0073 7.8719 1.0663 11.302 3.0695 3.4303 2.0032 6.2689 4.879 8.2272 8.335-3.1351-2.1715-6.9649-3.1014-10.747-2.6093 16.031 8.0155 11.73 35.618-10.487 34.576-1.9782-0.0813-3.933-0.4584-5.7994-1.119-0.4363-0.1633-0.8725-0.3419-1.3087-0.5359-0.2519-0.115-0.5037-0.23-0.7521-0.3588l0.031 0.0196c-0.2162-0.1035-0.4324-0.2112-0.6486-0.3232 0.2082 0.1001 0.4037 0.2082 0.6176 0.3036-5.443-2.8129-9.9372-8.1305-10.498-14.587 0 0 2.0574-7.667 14.732-7.667 1.3697 0 5.29-3.8238 5.3602-4.9324-0.0173-0.3622-7.774-3.45-10.798-6.4285-1.6158-1.5927-2.3828-2.3598-3.0625-2.9359-0.3673-0.3111-0.7512-0.6021-1.15-0.8717-1.0156-3.5547-1.0588-7.3168-0.1253-10.894-4.1114 1.9917-7.7645 4.8151-10.728 8.2915h-0.0207c-1.7664-2.239-1.6422-9.622-1.541-11.164-0.5225 0.21-1.0214 0.4749-1.4881 0.7901-1.5593 1.1129-3.0171 2.3617-4.3562 3.7317-1.5259 1.5472-2.9196 3.2193-4.1664 4.9991v0.0069-0.0081c-2.8656 4.0625-4.898 8.6523-5.98 13.504l-0.0598 0.2944c-0.084 0.3921-0.46 2.3839-0.5141 2.8117v0c-0.3439 2.0561-0.5636 4.131-0.6578 6.2135v0.23c0.0098 11.16 4.2056 21.91 11.758 30.126 7.5526 8.216 17.912 13.3 29.032 14.247s22.19-2.312 31.023-9.132c8.8332-6.8204 14.786-16.706 16.683-27.704 0.075-0.575 0.136-1.1443 0.203-1.725 0.918-7.5875-0.076-15.284-2.891-22.389z" fill="url(#j)" /> <defs> <linearGradient id="l" x1="95.404" x2="21.414" y1="26.252" y2="97.638" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFF44F" offset=".048" /> <stop stopColor="#FFE847" offset=".111" /> <stop stopColor="#FFC830" offset=".225" /> <stop stopColor="#FF980E" offset=".368" /> <stop stopColor="#FF8B16" offset=".401" /> <stop stopColor="#FF672A" offset=".462" /> <stop stopColor="#FF3647" offset=".534" /> <stop stopColor="#E31587" offset=".705" /> </linearGradient> <radialGradient id="i" cx="0" cy="0" r="1" gradientTransform="translate(91.985 22.211) scale(92.916 92.917)" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFBD4F" offset=".129" /> <stop stopColor="#FFAC31" offset=".186" /> <stop stopColor="#FF9D17" offset=".247" /> <stop stopColor="#FF980E" offset=".283" /> <stop stopColor="#FF563B" offset=".403" /> <stop stopColor="#FF3750" offset=".467" /> <stop stopColor="#F5156C" offset=".71" /> <stop stopColor="#EB0878" offset=".782" /> <stop stopColor="#E50080" offset=".86" /> </radialGradient> <radialGradient id="h" cx="0" cy="0" r="1" gradientTransform="translate(58.032 60.198) scale(92.916 92.917)" gradientUnits="userSpaceOnUse"> <stop stopColor="#960E18" offset=".3" /> <stop stopColor="#B11927" stopOpacity=".74" offset=".351" /> <stop stopColor="#DB293D" stopOpacity=".343" offset=".435" /> <stop stopColor="#F5334B" stopOpacity=".094" offset=".497" /> <stop stopColor="#FF3750" stopOpacity="0" offset=".53" /> </radialGradient> <radialGradient id="g" cx="0" cy="0" r="1" gradientTransform="translate(69.234 1.1246) scale(67.314)" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFF44F" offset=".132" /> <stop stopColor="#FFDC3E" offset=".252" /> <stop stopColor="#FF9D12" offset=".506" /> <stop stopColor="#FF980E" offset=".526" /> </radialGradient> <radialGradient id="f" cx="0" cy="0" r="1" gradientTransform="translate(47.755 84.468) scale(44.242 44.242)" gradientUnits="userSpaceOnUse"> <stop stopColor="#3A8EE6" offset=".353" /> <stop stopColor="#5C79F0" offset=".472" /> <stop stopColor="#9059FF" offset=".669" /> <stop stopColor="#C139E6" offset="1" /> </radialGradient> <radialGradient id="e" cx="0" cy="0" r="1" gradientTransform="translate(63.11 52.583) rotate(-13.592) scale(23.457 27.462)" gradientUnits="userSpaceOnUse"> <stop stopColor="#9059FF" stopOpacity="0" offset=".206" /> <stop stopColor="#8C4FF3" stopOpacity=".064" offset=".278" /> <stop stopColor="#7716A8" stopOpacity=".45" offset=".747" /> <stop stopColor="#6E008B" stopOpacity=".6" offset=".975" /> </radialGradient> <radialGradient id="d" cx="0" cy="0" r="1" gradientTransform="translate(56.859 18.409) scale(31.827)" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFE226" offset="0" /> <stop stopColor="#FFDB27" offset=".121" /> <stop stopColor="#FFC82A" offset=".295" /> <stop stopColor="#FFA930" offset=".502" /> <stop stopColor="#FF7E37" offset=".732" /> <stop stopColor="#FF7139" offset=".792" /> </radialGradient> <radialGradient id="c" cx="0" cy="0" r="1" gradientTransform="translate(81.876 -1.7782) scale(135.79)" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFF44F" offset=".113" /> <stop stopColor="#FF980E" offset=".456" /> <stop stopColor="#FF5634" offset=".622" /> <stop stopColor="#FF3647" offset=".716" /> <stop stopColor="#E31587" offset=".904" /> </radialGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="translate(70.431 5.7724) rotate(83.976) scale(99.526 65.318)" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFF44F" offset="0" /> <stop stopColor="#FFE847" offset=".06" /> <stop stopColor="#FFC830" offset=".168" /> <stop stopColor="#FF980E" offset=".304" /> <stop stopColor="#FF8B16" offset=".356" /> <stop stopColor="#FF672A" offset=".455" /> <stop stopColor="#FF3647" offset=".57" /> <stop stopColor="#E31587" offset=".737" /> </radialGradient> <radialGradient id="a" cx="0" cy="0" r="1" gradientTransform="translate(56.11 30.198) scale(84.778)" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFF44F" offset=".137" /> <stop stopColor="#FF980E" offset=".48" /> <stop stopColor="#FF5634" offset=".592" /> <stop stopColor="#FF3647" offset=".655" /> <stop stopColor="#E31587" offset=".904" /> </radialGradient> <radialGradient id="k" cx="0" cy="0" r="1" gradientTransform="translate(78.488 35.16) scale(92.789)" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFF44F" offset=".094" /> <stop stopColor="#FFE141" offset=".231" /> <stop stopColor="#FFAF1E" offset=".509" /> <stop stopColor="#FF980E" offset=".626" /> </radialGradient> <linearGradient id="j" x1="94.515" x2="31.557" y1="25.87" y2="88.827" gradientUnits="userSpaceOnUse"> <stop stopColor="#FFF44F" stopOpacity=".8" offset=".167" /> <stop stopColor="#FFF44F" stopOpacity=".634" offset=".266" /> <stop stopColor="#FFF44F" stopOpacity=".217" offset=".489" /> <stop stopColor="#FFF44F" stopOpacity="0" offset=".6" /> </linearGradient> </defs> </SvgContainer> <SvgContainer> <path d="m60 104c24.3 0 44-19.7 44-44s-19.7-44-44-44-44 19.7-44 44 19.7 44 44 44z" fill="url(#aaa)" /> <path d="m60.002 100.1v-6.756" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m60.002 26.624v-6.7563" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m53.018 99.512 1.1732-6.6536m11.585-65.704 1.1732-6.6536" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m46.278 97.689 2.3108-6.3488m22.819-62.694 2.3108-6.3488" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m39.91 94.765 3.3781-5.851m33.359-57.779 3.3782-5.8511" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m34.252 90.737 4.3428-5.1756m42.885-51.109 4.3429-5.1756" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m29.227 85.774 5.1756-4.3428m51.109-42.885 5.1756-4.3428" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m25.244 80.033 5.8511-3.3781m57.779-33.359 5.8511-3.3781" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m22.238 73.725 6.3488-2.3108m62.694-22.819 6.3488-2.3108" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m20.469 67.009 6.6535-1.1733m65.704-11.585 6.6536-1.1732" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m19.9 60.002h6.7563m66.718 0h6.7558" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m20.488 53.062 6.6536 1.1732m65.704 11.585 6.6536 1.1732" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m22.309 46.295 6.3488 2.3108m62.694 22.819 6.3488 2.3108" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m25.229 39.99 5.8511 3.3781m57.779 33.359 5.851 3.3781" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m29.24 34.19 5.1756 4.3428m51.109 42.885 5.1756 4.3429" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m34.166 29.281 4.3428 5.1756m42.885 51.109 4.3428 5.1755" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m39.918 25.256 3.3781 5.8511m33.359 57.779 3.3781 5.8511" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m46.28 22.3 2.3108 6.3487m22.819 62.694 2.3107 6.3488" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m52.992 20.554 1.1733 6.6536m11.585 65.704 1.1732 6.6536" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m56.484 99.953 0.2945-3.3653m6.4037-73.194 0.2944-3.3653" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m49.629 98.788 0.8743-3.263m19.016-70.97 0.8743-3.263" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m43.024 96.33 1.4276-3.0616m31.052-66.59 1.4277-3.0616" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m36.978 92.875 1.9376-2.7672m42.143-60.186 1.9376-2.7672" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m31.658 88.369 2.3887-2.3886m51.954-51.954 2.3887-2.3886" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m27.141 83.051 2.7672-1.9376m60.186-42.143 2.7672-1.9376" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m23.653 76.966 3.0616-1.4277m66.59-31.052 3.0617-1.4276" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m21.24 70.41 3.263-0.8744m70.97-19.016 3.263-0.8743" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m20 63.507 3.3653-0.2944m73.194-6.4037 3.3652-0.2944" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m20.03 56.514 3.3653 0.2944m73.194 6.4037 3.3653 0.2944" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m21.19 49.657 3.2631 0.8743m70.97 19.016 3.263 0.8744" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m23.624 43.042 3.0616 1.4276m66.59 31.052 3.0616 1.4277" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m27.127 37.029 2.7671 1.9376m60.186 42.143 2.7672 1.9376" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m31.654 31.661 2.3887 2.3887m51.954 51.954 2.3887 2.3887" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m36.935 27.134 1.9376 2.7672m42.143 60.186 1.9376 2.7672" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m43.044 23.676 1.4276 3.0616m31.052 66.59 1.4277 3.0616" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m49.59 21.297 0.8743 3.263m19.016 70.97 0.8743 3.263" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m56.449 20.063 0.2944 3.3653m6.4037 73.194 0.2944 3.3652" stroke="#fff" strokeLinecap="square" strokeWidth=".84706" /> <path d="m91.222 33.87-34.71 22.211-27.785 30.15 34.879-21.704 27.616-30.656z" clipRule="evenodd" fill="#fff" fillRule="evenodd" /> <path d="m91.222 33.87-34.71 22.211 7.094 8.4453 27.616-30.656z" clipRule="evenodd" fill="#FF3B30" fillRule="evenodd" /> <defs> <linearGradient id="aaa" x1="59.999" x2="59.999" y1="104.01" y2="15.992" gradientUnits="userSpaceOnUse"> <stop stopColor="#1E6FF1" offset="0" /> <stop stopColor="#28CEFB" offset="1" /> </linearGradient> </defs> </SvgContainer> </div> ); } // TODO: upgrade React and use the built-in version. function use(promise) { if (promise.status === 'fulfilled') { return promise.value; } else if (promise.status === 'rejected') { throw promise.reason; } else if (promise.status === 'pending') { throw promise; } else { promise.status = 'pending'; promise.then( (result) => { promise.status = 'fulfilled'; promise.value = result; }, (reason) => { promise.status = 'rejected'; promise.reason = reason; } ); throw promise; } } let confCache = new Map(); let talksCache = new Map(); const loadConfDelay = 250; const loadTalksDelay = 1000; function fetchConf(slug) { if (confCache.has(slug)) { return confCache.get(slug); } const promise = new Promise((resolve) => { setTimeout(() => { if (slug === 'react-conf-2021') { resolve({ id: 0, cover: reactConf2021Cover, name: 'React Conf 2021', }); } else if (slug === 'react-conf-2019') { resolve({ id: 1, cover: reactConf2019Cover, name: 'React Conf 2019', }); } }, loadConfDelay); }); confCache.set(slug, promise); return promise; } function fetchTalks(confId) { if (talksCache.has(confId)) { return talksCache.get(confId); } const promise = new Promise((resolve) => { setTimeout(() => { if (confId === 0) { resolve([ { id: 'conf-2021-0', title: 'React 18 Keynote', description: 'The React Team', url: 'https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=1', image: { speakers: [ '/images/home/conf2021/andrew.jpg', '/images/home/conf2021/lauren.jpg', '/images/home/conf2021/juan.jpg', '/images/home/conf2021/rick.jpg', ], }, }, { id: 'conf-2021-1', title: 'React 18 for App Developers', description: 'Shruti Kapoor', url: 'https://www.youtube.com/watch?v=ytudH8je5ko&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=2', image: { speakers: ['/images/home/conf2021/shruti.jpg'], }, }, { id: 'conf-2021-2', title: 'Streaming Server Rendering with Suspense', description: 'Shaundai Person', url: 'https://www.youtube.com/watch?v=pj5N-Khihgc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=3', image: { speakers: ['/images/home/conf2021/shaundai.jpg'], }, }, { id: 'conf-2021-3', title: 'The First React Working Group', description: 'Aakansha Doshi', url: 'https://www.youtube.com/watch?v=qn7gRClrC9U&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=4', image: { speakers: ['/images/home/conf2021/aakansha.jpg'], }, }, { id: 'conf-2021-4', title: 'React Developer Tooling', description: 'Brian Vaughn', url: 'https://www.youtube.com/watch?v=oxDfrke8rZg&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=5', image: { speakers: ['/images/home/conf2021/brian.jpg'], }, }, { id: 'conf-2021-5', title: 'React without memo', description: 'Xuan Huang (黄玄)', url: 'https://www.youtube.com/watch?v=lGEMwh32soc&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=6', image: { speakers: ['/images/home/conf2021/xuan.jpg'], }, }, { id: 'conf-2021-6', title: 'React Docs Keynote', description: 'Rachel Nabors', url: 'https://www.youtube.com/watch?v=mneDaMYOKP8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=7', image: { speakers: ['/images/home/conf2021/rachel.jpg'], }, }, { id: 'conf-2021-7', title: 'Things I Learnt from the New React Docs', description: "Debbie O'Brien", url: 'https://www.youtube.com/watch?v=-7odLW_hG7s&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=8', image: { speakers: ['/images/home/conf2021/debbie.jpg'], }, }, { id: 'conf-2021-8', title: 'Learning in the Browser', description: 'Sarah Rainsberger', url: 'https://www.youtube.com/watch?v=5X-WEQflCL0&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=9', image: { speakers: ['/images/home/conf2021/sarah.jpg'], }, }, { id: 'conf-2021-9', title: 'The ROI of Designing with React', description: 'Linton Ye', url: 'https://www.youtube.com/watch?v=7cPWmID5XAk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=10', image: { speakers: ['/images/home/conf2021/linton.jpg'], }, }, { id: 'conf-2021-10', title: 'Interactive Playgrounds with React', description: 'Delba de Oliveira', url: 'https://www.youtube.com/watch?v=zL8cz2W0z34&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=11', image: { speakers: ['/images/home/conf2021/delba.jpg'], }, }, { id: 'conf-2021-11', title: 'Re-introducing Relay', description: 'Robert Balicki', url: 'https://www.youtube.com/watch?v=lhVGdErZuN4&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=12', image: { speakers: ['/images/home/conf2021/robert.jpg'], }, }, { id: 'conf-2021-12', title: 'React Native Desktop', description: 'Eric Rozell and Steven Moyes', url: 'https://www.youtube.com/watch?v=9L4FFrvwJwY&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=13', image: { speakers: [ '/images/home/conf2021/eric.jpg', '/images/home/conf2021/steven.jpg', ], }, }, { id: 'conf-2021-13', title: 'On-device Machine Learning for React Native', description: 'Roman Rädle', url: 'https://www.youtube.com/watch?v=NLj73vrc2I8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=14', image: { speakers: ['/images/home/conf2021/roman.jpg'], }, }, { id: 'conf-2021-14', title: 'React 18 for External Store Libraries', description: 'Daishi Kato', url: 'https://www.youtube.com/watch?v=oPfSC5bQPR8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=15', image: { speakers: ['/images/home/conf2021/daishi.jpg'], }, }, { id: 'conf-2021-15', title: 'Building Accessible Components with React 18', description: 'Diego Haz', url: 'https://www.youtube.com/watch?v=dcm8fjBfro8&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=16', image: { speakers: ['/images/home/conf2021/diego.jpg'], }, }, { id: 'conf-2021-16', title: 'Accessible Japanese Form Components with React', description: 'Tafu Nakazaki', url: 'https://www.youtube.com/watch?v=S4a0QlsH0pU&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=17', image: { speakers: ['/images/home/conf2021/tafu.jpg'], }, }, { id: 'conf-2021-17', title: 'UI Tools for Artists', description: 'Lyle Troxell', url: 'https://www.youtube.com/watch?v=b3l4WxipFsE&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=18', image: { speakers: ['/images/home/conf2021/lyle.jpg'], }, }, { id: 'conf-2021-18', title: 'Hydrogen + React 18', description: 'Helen Lin', url: 'https://www.youtube.com/watch?v=HS6vIYkSNks&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa&index=19', image: { speakers: ['/images/home/conf2021/helen.jpg'], }, }, ]); } else if (confId === 1) { resolve([ { id: 'conf-2019-0', title: 'Keynote (Part 1)', description: 'Tom Occhino', url: 'https://www.youtube.com/watch?v=QnZHO7QvjaM&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh', image: { speakers: ['/images/home/conf2019/tom.jpg'], }, }, { id: 'conf-2019-1', title: 'Keynote (Part 2)', description: 'Yuzhi Zheng', url: 'https://www.youtube.com/watch?v=uXEEL9mrkAQ&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=2', image: { speakers: ['https://conf2019.reactjs.org/img/speakers/yuzhi.jpg'], }, }, { id: 'conf-2019-2', title: 'Building The New Facebook With React and Relay (Part 1)', description: 'Frank Yan', url: 'https://www.youtube.com/watch?v=9JZHodNR184&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=3', image: { speakers: ['/images/home/conf2019/frank.jpg'], }, }, { id: 'conf-2019-3', title: 'Building The New Facebook With React and Relay (Part 2)', description: 'Ashley Watkins', url: 'https://www.youtube.com/watch?v=KT3XKDBZW7M&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=4', image: { speakers: ['/images/home/conf2019/ashley.jpg'], }, }, { id: 'conf-2019-4', title: 'How Our Team Is Using React Native to Save The World', description: 'Tania Papazafeiropoulou', url: 'https://www.youtube.com/watch?v=zVHWugBPGBE&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=5', image: { speakers: ['/images/home/conf2019/tania.jpg'], }, }, { id: 'conf-2019-5', title: 'Using Hooks and Codegen to Bring the Benefits of GraphQL to REST APIs', description: 'Tejas Kumar', url: 'https://www.youtube.com/watch?v=cdsnzfJUqm0&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=6', image: { speakers: ['/images/home/conf2019/tejas.jpg'], }, }, { id: 'conf-2019-6', title: 'Building a Custom React Renderer', description: 'Sophie Alpert', url: 'https://www.youtube.com/watch?v=CGpMlWVcHok&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=7', image: { speakers: ['/images/home/conf2019/sophie.jpg'], }, }, { id: 'conf-2019-7', title: 'Is React Translated Yet?', description: 'Nat Alison', url: 'https://www.youtube.com/watch?v=lLE4Jqaek5k&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=12', image: { speakers: ['/images/home/conf2019/nat.jpg'], }, }, { id: 'conf-2019-8', title: 'Building (And Re-Building) the Airbnb Design System', description: 'Maja Wichrowska and Tae Kim', url: 'https://www.youtube.com/watch?v=fHQ1WSx41CA&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=13', image: { speakers: [ '/images/home/conf2019/maja.jpg', '/images/home/conf2019/tae.jpg', ], }, }, { id: 'conf-2019-9', title: 'Accessibility Is a Marathon, Not a Sprint', description: 'Brittany Feenstra', url: 'https://www.youtube.com/watch?v=ONSD-t4gBb8&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=14', image: { speakers: ['/images/home/conf2019/brittany.jpg'], }, }, { id: 'conf-2019-10', title: 'The State of React State in 2019', description: 'Becca Bailey', url: 'https://www.youtube.com/watch?v=wUMMUyQtMSg&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=15', image: { speakers: ['/images/home/conf2019/becca.jpg'], }, }, { id: 'conf-2019-11', title: 'Let’s Program Like It’s 1999', description: 'Lee Byron', url: 'https://www.youtube.com/watch?v=vG8WpLr6y_U&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=16', image: { speakers: ['/images/home/conf2019/lee.jpg'], }, }, { id: 'conf-2019-12', title: 'React Developer Tooling', description: 'Brian Vaughn', url: 'https://www.youtube.com/watch?v=Mjrfb1r3XEM&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=17', image: { speakers: ['/images/home/conf2019/brian.jpg'], }, }, { id: 'conf-2019-13', title: 'Data Fetching With Suspense In Relay', description: 'Joe Savona', url: 'https://www.youtube.com/watch?v=Tl0S7QkxFE4&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=18', image: { speakers: ['/images/home/conf2019/joe.jpg'], }, }, { id: 'conf-2019-14', title: 'Automatic Visualizations of the Frontend', description: 'Cameron Yick', url: 'https://www.youtube.com/watch?v=SbreAPNmZOk&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=19', image: { speakers: ['/images/home/conf2019/cameron.jpg'], }, }, { id: 'conf-2019-15', title: 'React Is Fiction', description: 'Jenn Creighton', url: 'https://www.youtube.com/watch?v=kqh4lz2Lkzs&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=20', image: { speakers: ['/images/home/conf2019/jenn.jpg'], }, }, { id: 'conf-2019-16', title: 'Progressive Web Animations', description: 'Alexandra Holachek', url: 'https://www.youtube.com/watch?v=laPsceJ4tTY&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=21', image: { speakers: ['/images/home/conf2019/alexandra.jpg'], }, }, { id: 'conf-2019-17', title: 'Creating Games, Animations and Interactions with the Wick Editor', description: 'Luca Damasco', url: 'https://www.youtube.com/watch?v=laPsceJ4tTY&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=21', image: { speakers: ['/images/home/conf2019/luca.jpg'], }, }, { id: 'conf-2019-18', title: 'Building React-Select', description: 'Jed Watson', url: 'https://www.youtube.com/watch?v=yS0jUnmBujE&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=25', image: { speakers: ['/images/home/conf2019/jed.jpg'], }, }, { id: 'conf-2019-19', title: 'Promoting Transparency in Government Spending with React', description: 'Lizzie Salita', url: 'https://www.youtube.com/watch?v=CVfXICcNfHE&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=26', image: { speakers: ['/images/home/conf2019/lizzie.jpg'], }, }, { id: 'conf-2019-20', title: 'Wonder-driven Development: Using React to Make a Spaceship', description: 'Alex Anderson', url: 'https://www.youtube.com/watch?v=aV0uOPWHKt4&list=PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh&index=27', image: { speakers: ['/images/home/conf2019/alex.jpg'], }, }, ]); } }, loadTalksDelay); }); talksCache.set(confId, promise); return promise; }
42.427541
2,031
0.564221
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type ClientManifest = null; // eslint-disable-next-line no-unused-vars export type ServerReference<T> = string; // eslint-disable-next-line no-unused-vars export type ClientReference<T> = { getModuleId(): ClientReferenceKey, }; const requestedClientReferencesKeys = new Set<ClientReferenceKey>(); export type ClientReferenceKey = string; export type ClientReferenceMetadata = { moduleId: ClientReferenceKey, exportName: string, }; export type ServerReferenceId = string; let checkIsClientReference: (clientReference: mixed) => boolean; export function setCheckIsClientReference( impl: (clientReference: mixed) => boolean, ): void { checkIsClientReference = impl; } export function registerClientReference<T>( clientReference: ClientReference<T>, ): void {} export function isClientReference(reference: mixed): boolean { if (checkIsClientReference == null) { throw new Error('Expected implementation for checkIsClientReference.'); } return checkIsClientReference(reference); } export function getClientReferenceKey<T>( clientReference: ClientReference<T>, ): ClientReferenceKey { const moduleId = clientReference.getModuleId(); requestedClientReferencesKeys.add(moduleId); return clientReference.getModuleId(); } export function resolveClientReferenceMetadata<T>( config: ClientManifest, clientReference: ClientReference<T>, ): ClientReferenceMetadata { return {moduleId: clientReference.getModuleId(), exportName: 'default'}; } export function registerServerReference<T>( serverReference: ServerReference<T>, id: string, exportName: null | string, ): ServerReference<T> { throw new Error('registerServerReference: Not Implemented.'); } export function isServerReference<T>(reference: T): boolean { throw new Error('isServerReference: Not Implemented.'); } export function getServerReferenceId<T>( config: ClientManifest, serverReference: ServerReference<T>, ): ServerReferenceId { throw new Error('getServerReferenceId: Not Implemented.'); } export function getRequestedClientReferencesKeys(): $ReadOnlyArray<ClientReferenceKey> { return Array.from(requestedClientReferencesKeys); } export function clearRequestedClientReferencesKeysSet(): void { requestedClientReferencesKeys.clear(); }
26.175824
88
0.773058
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 */ // Renderers that don't support mutation // can re-export everything from this module. function shim(...args: any): any { throw new Error( 'The current renderer does not support Singletons. ' + 'This error is likely caused by a bug in React. ' + 'Please file an issue.', ); } // Resources (when unsupported) export const supportsSingletons = false; export const resolveSingletonInstance = shim; export const clearSingleton = shim; export const acquireSingletonInstance = shim; export const releaseSingletonInstance = shim; export const isHostSingletonType = shim;
27.25
66
0.727848
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Request} from 'react-server/src/ReactFizzServer'; export * from 'react-dom-bindings/src/server/ReactFizzConfigDOM'; export const supportsRequestStorage = false; export const requestStorage: AsyncLocalStorage<Request> = (null: any);
29.066667
70
0.748889
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireDefault(require("react")); var _useTheme = _interopRequireDefault(require("./useTheme")); var _jsxFileName = ""; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Component() { const theme = (0, _useTheme.default)(); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 10 } }, "theme: ", theme); } //# sourceMappingURL=ComponentWithExternalCustomHooks.js.map?foo=bar&param=some_value
25.423077
95
0.670554
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 * as React from 'react'; import {isInternalFacebookBuild} from 'react-devtools-feature-flags'; import styles from './TimelineNotSupported.css'; export default function TimelineNotSupported(): React.Node { return ( <div className={styles.Column}> <div className={styles.Header}>Timeline profiling not supported.</div> <p className={styles.Paragraph}> <span> Timeline profiler requires a development or profiling build of{' '} <code className={styles.Code}>react-dom@^18</code>. </span> </p> <div className={styles.LearnMoreRow}> Click{' '} <a className={styles.Link} href="https://fb.me/react-devtools-profiling" rel="noopener noreferrer" target="_blank"> here </a>{' '} to learn more about profiling. </div> {isInternalFacebookBuild && ( <div className={styles.MetaGKRow}> <strong>Meta only</strong>: Enable the{' '} <a className={styles.Link} href="https://fburl.com/react-devtools-scheduling-profiler-gk" rel="noopener noreferrer" target="_blank"> react_enable_scheduling_profiler GK </a> . </div> )} </div> ); }
27.641509
77
0.589321
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 {ReactPortal, ReactNodeList} from 'shared/ReactTypes'; import type {ElementRef, Element, ElementType} from 'react'; import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import './ReactFabricInjection'; import { batchedUpdates as batchedUpdatesImpl, discreteUpdates, createContainer, updateContainer, injectIntoDevTools, getPublicRootInstance, } from 'react-reconciler/src/ReactFiberReconciler'; import {createPortal as createPortalImpl} from 'react-reconciler/src/ReactPortal'; import {setBatchingImplementation} from './legacy-events/ReactGenericBatching'; import ReactVersion from 'shared/ReactVersion'; import {getClosestInstanceFromNode} from './ReactFabricComponentTree'; import { getInspectorDataForViewTag, getInspectorDataForViewAtPoint, getInspectorDataForInstance, } from './ReactNativeFiberInspector'; import {LegacyRoot, ConcurrentRoot} from 'react-reconciler/src/ReactRootTags'; import { findHostInstance_DEPRECATED, findNodeHandle, dispatchCommand, sendAccessibilityEvent, getNodeFromInternalInstanceHandle, isChildPublicInstance, } from './ReactNativePublicCompat'; import {getPublicInstanceFromInternalInstanceHandle} from './ReactFiberConfigFabric'; // $FlowFixMe[missing-local-annot] function onRecoverableError(error) { // TODO: Expose onRecoverableError option to userspace // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args console.error(error); } function render( element: Element<ElementType>, containerTag: number, callback: ?() => void, concurrentRoot: ?boolean, ): ?ElementRef<ElementType> { let root = roots.get(containerTag); if (!root) { // TODO (bvaughn): If we decide to keep the wrapper component, // We could create a wrapper for containerTag as well to reduce special casing. root = createContainer( containerTag, concurrentRoot ? ConcurrentRoot : LegacyRoot, null, false, null, '', onRecoverableError, null, ); roots.set(containerTag, root); } updateContainer(element, root, null, callback); return getPublicRootInstance(root); } // $FlowFixMe[missing-this-annot] function unmountComponentAtNode(containerTag: number) { this.stopSurface(containerTag); } function stopSurface(containerTag: number) { const root = roots.get(containerTag); if (root) { // TODO: Is it safe to reset this now or should I wait since this unmount could be deferred? updateContainer(null, root, null, () => { roots.delete(containerTag); }); } } function createPortal( children: ReactNodeList, containerTag: number, key: ?string = null, ): ReactPortal { return createPortalImpl(children, containerTag, null, key); } setBatchingImplementation(batchedUpdatesImpl, discreteUpdates); const roots = new Map<number, FiberRoot>(); export { // This is needed for implementation details of TouchableNativeFeedback // Remove this once TouchableNativeFeedback doesn't use cloneElement findHostInstance_DEPRECATED, findNodeHandle, dispatchCommand, sendAccessibilityEvent, render, // Deprecated - this function is being renamed to stopSurface, use that instead. // TODO (T47576999): Delete this once it's no longer called from native code. unmountComponentAtNode, stopSurface, createPortal, // This export is typically undefined in production builds. // See the "enableGetInspectorDataForInstanceInProduction" flag. getInspectorDataForInstance, // The public instance has a reference to the internal instance handle. // This method allows it to acess the most recent shadow node for // the instance (it's only accessible through it). getNodeFromInternalInstanceHandle, // Fabric native methods to traverse the host tree return the same internal // instance handles we use to dispatch events. This provides a way to access // the public instances we created from them (potentially created lazily). getPublicInstanceFromInternalInstanceHandle, // DEV-only: isChildPublicInstance, }; injectIntoDevTools({ // $FlowExpectedError[incompatible-call] The type of `Instance` in `getClosestInstanceFromNode` does not match in Fabric and the legacy renderer, so it fails to typecheck here. findFiberByHostInstance: getClosestInstanceFromNode, bundleType: __DEV__ ? 1 : 0, version: ReactVersion, rendererPackageName: 'react-native-renderer', rendererConfig: { getInspectorDataForInstance, getInspectorDataForViewTag: getInspectorDataForViewTag, getInspectorDataForViewAtPoint: getInspectorDataForViewAtPoint.bind( null, findNodeHandle, ), }, });
31.264901
178
0.759187
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; let ReactDOM; let ReactDOMClient; let Scheduler; let act; let container; let waitForAll; let assertLog; let fakeModuleCache; describe('ReactSuspenseEffectsSemanticsDOM', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; container = document.createElement('div'); document.body.appendChild(container); fakeModuleCache = new Map(); }); afterEach(() => { document.body.removeChild(container); }); async function fakeImport(Component) { const record = fakeModuleCache.get(Component); if (record === undefined) { const newRecord = { status: 'pending', value: {default: Component}, pings: [], then(ping) { switch (newRecord.status) { case 'pending': { newRecord.pings.push(ping); return; } case 'resolved': { ping(newRecord.value); return; } case 'rejected': { throw newRecord.value; } } }, }; fakeModuleCache.set(Component, newRecord); return newRecord; } return record; } function resolveFakeImport(moduleName) { const record = fakeModuleCache.get(moduleName); if (record === undefined) { throw new Error('Module not found'); } if (record.status !== 'pending') { throw new Error('Module already resolved'); } record.status = 'resolved'; record.pings.forEach(ping => ping(record.value)); } function Text(props) { Scheduler.log(props.text); return props.text; } it('should not cause a cycle when combined with a render phase update', async () => { let scheduleSuspendingUpdate; function App() { const [value, setValue] = React.useState(true); scheduleSuspendingUpdate = () => setValue(!value); return ( <> <React.Suspense fallback="Loading..."> <ComponentThatCausesBug value={value} /> <ComponentThatSuspendsOnUpdate shouldSuspend={!value} /> </React.Suspense> </> ); } function ComponentThatCausesBug({value}) { const [mirroredValue, setMirroredValue] = React.useState(value); if (mirroredValue !== value) { setMirroredValue(value); } // eslint-disable-next-line no-unused-vars const [_, setRef] = React.useState(null); return <div ref={setRef} />; } const neverResolves = {then() {}}; function ComponentThatSuspendsOnUpdate({shouldSuspend}) { if (shouldSuspend) { // Fake Suspend throw neverResolves; } return null; } await act(() => { const root = ReactDOMClient.createRoot(container); root.render(<App />); }); await act(() => { scheduleSuspendingUpdate(); }); }); it('does not destroy ref cleanup twice when hidden child is removed', async () => { function ChildA({label}) { return ( <span ref={node => { if (node) { Scheduler.log('Ref mount: ' + label); } else { Scheduler.log('Ref unmount: ' + label); } }}> <Text text={label} /> </span> ); } function ChildB({label}) { return ( <span ref={node => { if (node) { Scheduler.log('Ref mount: ' + label); } else { Scheduler.log('Ref unmount: ' + label); } }}> <Text text={label} /> </span> ); } const LazyChildA = React.lazy(() => fakeImport(ChildA)); const LazyChildB = React.lazy(() => fakeImport(ChildB)); function Parent({swap}) { return ( <React.Suspense fallback={<Text text="Loading..." />}> {swap ? <LazyChildB label="B" /> : <LazyChildA label="A" />} </React.Suspense> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Parent swap={false} />); }); assertLog(['Loading...']); await act(() => resolveFakeImport(ChildA)); assertLog(['A', 'Ref mount: A']); expect(container.innerHTML).toBe('<span>A</span>'); // Swap the position of A and B ReactDOM.flushSync(() => { root.render(<Parent swap={true} />); }); assertLog(['Loading...', 'Ref unmount: A']); expect(container.innerHTML).toBe( '<span style="display: none;">A</span>Loading...', ); await act(() => resolveFakeImport(ChildB)); assertLog(['B', 'Ref mount: B']); expect(container.innerHTML).toBe('<span>B</span>'); }); it('does not call componentWillUnmount twice when hidden child is removed', async () => { class ChildA extends React.Component { componentDidMount() { Scheduler.log('Did mount: ' + this.props.label); } componentWillUnmount() { Scheduler.log('Will unmount: ' + this.props.label); } render() { return <Text text={this.props.label} />; } } class ChildB extends React.Component { componentDidMount() { Scheduler.log('Did mount: ' + this.props.label); } componentWillUnmount() { Scheduler.log('Will unmount: ' + this.props.label); } render() { return <Text text={this.props.label} />; } } const LazyChildA = React.lazy(() => fakeImport(ChildA)); const LazyChildB = React.lazy(() => fakeImport(ChildB)); function Parent({swap}) { return ( <React.Suspense fallback={<Text text="Loading..." />}> {swap ? <LazyChildB label="B" /> : <LazyChildA label="A" />} </React.Suspense> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Parent swap={false} />); }); assertLog(['Loading...']); await act(() => resolveFakeImport(ChildA)); assertLog(['A', 'Did mount: A']); expect(container.innerHTML).toBe('A'); // Swap the position of A and B ReactDOM.flushSync(() => { root.render(<Parent swap={true} />); }); assertLog(['Loading...', 'Will unmount: A']); expect(container.innerHTML).toBe('Loading...'); await act(() => resolveFakeImport(ChildB)); assertLog(['B', 'Did mount: B']); expect(container.innerHTML).toBe('B'); }); it('does not destroy layout effects twice when parent suspense is removed', async () => { function ChildA({label}) { React.useLayoutEffect(() => { Scheduler.log('Did mount: ' + label); return () => { Scheduler.log('Will unmount: ' + label); }; }, []); return <Text text={label} />; } function ChildB({label}) { React.useLayoutEffect(() => { Scheduler.log('Did mount: ' + label); return () => { Scheduler.log('Will unmount: ' + label); }; }, []); return <Text text={label} />; } const LazyChildA = React.lazy(() => fakeImport(ChildA)); const LazyChildB = React.lazy(() => fakeImport(ChildB)); function Parent({swap}) { return ( <React.Suspense fallback={<Text text="Loading..." />}> {swap ? <LazyChildB label="B" /> : <LazyChildA label="A" />} </React.Suspense> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Parent swap={false} />); }); assertLog(['Loading...']); await act(() => resolveFakeImport(ChildA)); assertLog(['A', 'Did mount: A']); expect(container.innerHTML).toBe('A'); // Swap the position of A and B ReactDOM.flushSync(() => { root.render(<Parent swap={true} />); }); assertLog(['Loading...', 'Will unmount: A']); expect(container.innerHTML).toBe('Loading...'); // Destroy the whole tree, including the hidden A ReactDOM.flushSync(() => { root.render(<h1>Hello</h1>); }); await waitForAll([]); expect(container.innerHTML).toBe('<h1>Hello</h1>'); }); it('does not destroy ref cleanup twice when parent suspense is removed', async () => { function ChildA({label}) { return ( <span ref={node => { if (node) { Scheduler.log('Ref mount: ' + label); } else { Scheduler.log('Ref unmount: ' + label); } }}> <Text text={label} /> </span> ); } function ChildB({label}) { return ( <span ref={node => { if (node) { Scheduler.log('Ref mount: ' + label); } else { Scheduler.log('Ref unmount: ' + label); } }}> <Text text={label} /> </span> ); } const LazyChildA = React.lazy(() => fakeImport(ChildA)); const LazyChildB = React.lazy(() => fakeImport(ChildB)); function Parent({swap}) { return ( <React.Suspense fallback={<Text text="Loading..." />}> {swap ? <LazyChildB label="B" /> : <LazyChildA label="A" />} </React.Suspense> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Parent swap={false} />); }); assertLog(['Loading...']); await act(() => resolveFakeImport(ChildA)); assertLog(['A', 'Ref mount: A']); expect(container.innerHTML).toBe('<span>A</span>'); // Swap the position of A and B ReactDOM.flushSync(() => { root.render(<Parent swap={true} />); }); assertLog(['Loading...', 'Ref unmount: A']); expect(container.innerHTML).toBe( '<span style="display: none;">A</span>Loading...', ); // Destroy the whole tree, including the hidden A ReactDOM.flushSync(() => { root.render(<h1>Hello</h1>); }); await waitForAll([]); expect(container.innerHTML).toBe('<h1>Hello</h1>'); }); it('does not call componentWillUnmount twice when parent suspense is removed', async () => { class ChildA extends React.Component { componentDidMount() { Scheduler.log('Did mount: ' + this.props.label); } componentWillUnmount() { Scheduler.log('Will unmount: ' + this.props.label); } render() { return <Text text={this.props.label} />; } } class ChildB extends React.Component { componentDidMount() { Scheduler.log('Did mount: ' + this.props.label); } componentWillUnmount() { Scheduler.log('Will unmount: ' + this.props.label); } render() { return <Text text={this.props.label} />; } } const LazyChildA = React.lazy(() => fakeImport(ChildA)); const LazyChildB = React.lazy(() => fakeImport(ChildB)); function Parent({swap}) { return ( <React.Suspense fallback={<Text text="Loading..." />}> {swap ? <LazyChildB label="B" /> : <LazyChildA label="A" />} </React.Suspense> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Parent swap={false} />); }); assertLog(['Loading...']); await act(() => resolveFakeImport(ChildA)); assertLog(['A', 'Did mount: A']); expect(container.innerHTML).toBe('A'); // Swap the position of A and B ReactDOM.flushSync(() => { root.render(<Parent swap={true} />); }); assertLog(['Loading...', 'Will unmount: A']); expect(container.innerHTML).toBe('Loading...'); // Destroy the whole tree, including the hidden A ReactDOM.flushSync(() => { root.render(<h1>Hello</h1>); }); await waitForAll([]); expect(container.innerHTML).toBe('<h1>Hello</h1>'); }); it('regression: unmount hidden tree, in legacy mode', async () => { // In legacy mode, when a tree suspends and switches to a fallback, the // effects are not unmounted. So we have to unmount them during a deletion. function Child() { React.useLayoutEffect(() => { Scheduler.log('Mount'); return () => { Scheduler.log('Unmount'); }; }, []); return <Text text="Child" />; } function Sibling() { return <Text text="Sibling" />; } const LazySibling = React.lazy(() => fakeImport(Sibling)); function App({showMore}) { return ( <React.Suspense fallback={<Text text="Loading..." />}> <Child /> {showMore ? <LazySibling /> : null} </React.Suspense> ); } // Initial render ReactDOM.render(<App showMore={false} />, container); assertLog(['Child', 'Mount']); // Update that suspends, causing the existing tree to switches it to // a fallback. ReactDOM.render(<App showMore={true} />, container); assertLog([ 'Child', 'Loading...', // In a concurrent root, the effect would unmount here. But this is legacy // mode, so it doesn't. // Unmount ]); // Delete the tree and unmount the effect ReactDOM.render(null, container); assertLog(['Unmount']); }); it('does not call cleanup effects twice after a bailout', async () => { const never = new Promise(resolve => {}); function Never() { throw never; } let setSuspended; let setLetter; function App() { const [suspended, _setSuspended] = React.useState(false); setSuspended = _setSuspended; const [letter, _setLetter] = React.useState('A'); setLetter = _setLetter; return ( <React.Suspense fallback="Loading..."> <Child letter={letter} /> {suspended && <Never />} </React.Suspense> ); } let nextId = 0; const freed = new Set(); let setStep; function Child({letter}) { const [, _setStep] = React.useState(0); setStep = _setStep; React.useLayoutEffect(() => { const localId = nextId++; Scheduler.log('Did mount: ' + letter + localId); return () => { if (freed.has(localId)) { throw Error('Double free: ' + letter + localId); } freed.add(localId); Scheduler.log('Will unmount: ' + letter + localId); }; }, [letter]); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); assertLog(['Did mount: A0']); await act(() => { setStep(1); setSuspended(false); }); assertLog([]); await act(() => { setStep(1); }); assertLog([]); await act(() => { setSuspended(true); }); assertLog(['Will unmount: A0']); await act(() => { setSuspended(false); setLetter('B'); }); assertLog(['Did mount: B1']); await act(() => { root.unmount(); }); assertLog(['Will unmount: B1']); }); });
25.749135
94
0.54903
owtf
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; const React = window.React; const ReactDOM = window.ReactDOM; function BadRender(props) { props.doThrow(); } class BadDidMount extends React.Component { componentDidMount() { this.props.doThrow(); } render() { return null; } } class ErrorBoundary extends React.Component { static defaultProps = { buttonText: 'Trigger error', badChildType: BadRender, }; state = { shouldThrow: false, didThrow: false, error: null, }; componentDidCatch(error) { this.setState({error, didThrow: true}); } triggerError = () => { this.setState({ shouldThrow: true, }); }; render() { if (this.state.didThrow) { if (this.state.error) { return <p>Captured an error: {this.state.error.message}</p>; } else { return <p>Captured an error: {String(this.state.error)}</p>; } } if (this.state.shouldThrow) { const BadChild = this.props.badChildType; return <BadChild doThrow={this.props.doThrow} />; } return <button onClick={this.triggerError}>{this.props.buttonText}</button>; } } class Example extends React.Component { state = {key: 0}; restart = () => { this.setState(state => ({key: state.key + 1})); }; render() { return ( <div> <button onClick={this.restart}>Reset</button> <ErrorBoundary buttonText={this.props.buttonText} doThrow={this.props.doThrow} key={this.state.key} /> </div> ); } } class TriggerErrorAndCatch extends React.Component { container = document.createElement('div'); triggerErrorAndCatch = () => { try { ReactDOM.flushSync(() => { ReactDOM.render( <BadRender doThrow={() => { throw new Error('Caught error'); }} />, this.container ); }); } catch (e) {} }; render() { return ( <button onClick={this.triggerErrorAndCatch}> Trigger error and catch </button> ); } } function silenceWindowError(event) { event.preventDefault(); } class SilenceErrors extends React.Component { state = { silenceErrors: false, }; componentDidMount() { if (this.state.silenceErrors) { window.addEventListener('error', silenceWindowError); } } componentDidUpdate(prevProps, prevState) { if (!prevState.silenceErrors && this.state.silenceErrors) { window.addEventListener('error', silenceWindowError); } else if (prevState.silenceErrors && !this.state.silenceErrors) { window.removeEventListener('error', silenceWindowError); } } componentWillUnmount() { if (this.state.silenceErrors) { window.removeEventListener('error', silenceWindowError); } } render() { return ( <div> <label> <input type="checkbox" value={this.state.silenceErrors} onChange={() => this.setState(state => ({ silenceErrors: !state.silenceErrors, })) } /> Silence errors </label> {this.state.silenceErrors && ( <div> {this.props.children} <br /> <hr /> <b style={{color: 'red'}}> Don't forget to uncheck "Silence errors" when you're done with this test! </b> </div> )} </div> ); } } class GetEventTypeDuringUpdate extends React.Component { state = {}; onClick = () => { this.expectUpdate = true; this.forceUpdate(); }; componentDidUpdate() { if (this.expectUpdate) { this.expectUpdate = false; this.setState({eventType: window.event.type}); setTimeout(() => { this.setState({cleared: !window.event}); }); } } render() { return ( <div className="test-fixture"> <button onClick={this.onClick}>Trigger callback in event.</button> {this.state.eventType ? ( <p> Got <b>{this.state.eventType}</b> event. </p> ) : ( <p>Got no event</p> )} {this.state.cleared ? ( <p>Event cleared correctly.</p> ) : ( <p>Event failed to clear.</p> )} </div> ); } } class SilenceRecoverableError extends React.Component { render() { return ( <SilenceErrors> <ErrorBoundary badChildType={BadRender} buttonText={'Throw (render phase)'} doThrow={() => { throw new Error('Silenced error (render phase)'); }} /> <ErrorBoundary badChildType={BadDidMount} buttonText={'Throw (commit phase)'} doThrow={() => { throw new Error('Silenced error (commit phase)'); }} /> </SilenceErrors> ); } } class TrySilenceFatalError extends React.Component { container = document.createElement('div'); triggerErrorAndCatch = () => { try { ReactDOM.flushSync(() => { ReactDOM.render( <BadRender doThrow={() => { throw new Error('Caught error'); }} />, this.container ); }); } catch (e) {} }; render() { return ( <SilenceErrors> <button onClick={this.triggerErrorAndCatch}>Throw fatal error</button> </SilenceErrors> ); } } function naiveMemoize(fn) { let memoizedEntry; return function () { if (!memoizedEntry) { memoizedEntry = {result: null}; memoizedEntry.result = fn(); } return memoizedEntry.result; }; } let memoizedFunction = naiveMemoize(function () { throw new Error('Passed'); }); export default class ErrorHandlingTestCases extends React.Component { render() { return ( <FixtureSet title="Error handling"> <TestCase title="Break on uncaught exceptions" description="In DEV, errors should be treated as uncaught, even though React catches them internally"> <TestCase.Steps> <li>Open the browser DevTools</li> <li>Make sure "Pause on exceptions" is enabled</li> <li>Make sure "Pause on caught exceptions" is disabled</li> <li>Click the "Trigger error" button</li> <li>Click the reset button</li> </TestCase.Steps> <TestCase.ExpectedResult> The DevTools should pause at the line where the error was thrown, in the BadRender component. After resuming, the "Trigger error" button should be replaced with "Captured an error: Oops!" Clicking reset should reset the test case. <br /> <br /> In the console, you should see <b>two</b> messages: the actual error ("Oops") printed natively by the browser with its JavaScript stack, and our addendum ("The above error occurred in BadRender component") with a React component stack. </TestCase.ExpectedResult> <Example doThrow={() => { throw new Error('Oops!'); }} /> </TestCase> <TestCase title="Throwing null" description=""> <TestCase.Steps> <li>Click the "Trigger error" button</li> <li>Click the reset button</li> </TestCase.Steps> <TestCase.ExpectedResult> The "Trigger error" button should be replaced with "Captured an error: null". Clicking reset should reset the test case. </TestCase.ExpectedResult> <Example doThrow={() => { throw null; // eslint-disable-line no-throw-literal }} /> </TestCase> <TestCase title="Throwing memoized result" description=""> <TestCase.Steps> <li>Click the "Trigger error" button</li> <li>Click the reset button</li> </TestCase.Steps> <TestCase.ExpectedResult> The "Trigger error" button should be replaced with "Captured an error: Passed". Clicking reset should reset the test case. </TestCase.ExpectedResult> <Example doThrow={() => { memoizedFunction().value; }} /> </TestCase> <TestCase title="Cross-origin errors (development mode only)" description=""> <TestCase.Steps> <li>Click the "Trigger cross-origin error" button</li> <li>Click the reset button</li> </TestCase.Steps> <TestCase.ExpectedResult> The "Trigger error" button should be replaced with "Captured an error: A cross-origin error was thrown [...]". The actual error message should be logged to the console: "Uncaught Error: Expected true to be false". </TestCase.ExpectedResult> <Example buttonText="Trigger cross-origin error" doThrow={() => { // The `expect` module is loaded via unpkg, so that this assertion // triggers a cross-origin error window.expect(true).toBe(false); }} /> </TestCase> <TestCase title="Errors are logged even if they're caught (development mode only)" description=""> <TestCase.Steps> <li>Click the "Trigger render error and catch" button</li> </TestCase.Steps> <TestCase.ExpectedResult> Open the console. "Uncaught Error: Caught error" should have been logged by the browser. You should also see our addendum ("The above error..."). </TestCase.ExpectedResult> <TriggerErrorAndCatch /> </TestCase> <TestCase title="Recoverable errors can be silenced with preventDefault (development mode only)" description=""> <TestCase.Steps> <li>Check the "Silence errors" checkbox below</li> <li>Click the "Throw (render phase)" button</li> <li>Click the "Throw (commit phase)" button</li> <li>Uncheck the "Silence errors" checkbox</li> </TestCase.Steps> <TestCase.ExpectedResult> Open the console. You shouldn't see <b>any</b> messages in the console: neither the browser error, nor our "The above error" addendum, from either of the buttons. The buttons themselves should get replaced by two labels: "Captured an error: Silenced error (render phase)" and "Captured an error: Silenced error (commit phase)". </TestCase.ExpectedResult> <SilenceRecoverableError /> </TestCase> <TestCase title="Fatal errors cannot be silenced with preventDefault (development mode only)" description=""> <TestCase.Steps> <li>Check the "Silence errors" checkbox below</li> <li>Click the "Throw fatal error" button</li> <li>Uncheck the "Silence errors" checkbox</li> </TestCase.Steps> <TestCase.ExpectedResult> Open the console. "Error: Caught error" should have been logged by React. You should also see our addendum ("The above error..."). </TestCase.ExpectedResult> <TrySilenceFatalError /> </TestCase> {window.hasOwnProperty('event') ? ( <TestCase title="Error handling does not interfere with window.event" description=""> <TestCase.Steps> <li>Click the "Trigger callback in event" button</li> </TestCase.Steps> <TestCase.ExpectedResult> You should see "Got <b>click</b> event" and "Event cleared successfully" below. </TestCase.ExpectedResult> <GetEventTypeDuringUpdate /> </TestCase> ) : null} </FixtureSet> ); } }
28.945946
112
0.560187
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-esm-client.browser.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-esm-client.browser.development.js'); }
30.375
90
0.704
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 {TEXT_NODE} from './HTMLNodeType'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node: ?(Node | Element)) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node: ?(Node | Element)) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root: Element, offset: number): ?Object { let node = getLeafNode(root); let nodeStart = 0; let nodeEnd = 0; while (node) { if (node.nodeType === TEXT_NODE) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart, }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } export default getNodeForCharacterOffset;
21.388889
76
0.651769
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 {ViewState} from './types'; import * as React from 'react'; import { Suspense, useContext, useDeferredValue, useLayoutEffect, useRef, useState, } from 'react'; import {SettingsContext} from 'react-devtools-shared/src/devtools/views/Settings/SettingsContext'; import {ProfilerContext} from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext'; import NoProfilingData from 'react-devtools-shared/src/devtools/views/Profiler/NoProfilingData'; import RecordingInProgress from 'react-devtools-shared/src/devtools/views/Profiler/RecordingInProgress'; import {updateColorsToMatchTheme} from './content-views/constants'; import {TimelineContext} from './TimelineContext'; import CanvasPage from './CanvasPage'; import {importFile} from './timelineCache'; import TimelineSearchInput from './TimelineSearchInput'; import TimelineNotSupported from './TimelineNotSupported'; import {TimelineSearchContextController} from './TimelineSearchContext'; import styles from './Timeline.css'; export function Timeline(_: {}): React.Node { const {file, inMemoryTimelineData, isTimelineSupported, setFile, viewState} = useContext(TimelineContext); const {didRecordCommits, isProfiling} = useContext(ProfilerContext); const ref = useRef(null); // HACK: Canvas rendering uses an imperative API, // but DevTools colors are stored in CSS variables (see root.css and SettingsContext). // When the theme changes, we need to trigger update the imperative colors and re-draw the Canvas. const {theme} = useContext(SettingsContext); // HACK: SettingsContext also uses a useLayoutEffect to update styles; // make sure the theme context in SettingsContext updates before this code. const deferredTheme = useDeferredValue(theme); // HACK: Schedule a re-render of the Canvas once colors have been updated. // The easiest way to guarangee this happens is to recreate the inner Canvas component. const [key, setKey] = useState<string>(theme); useLayoutEffect(() => { const pollForTheme = () => { if (updateColorsToMatchTheme(((ref.current: any): HTMLDivElement))) { clearInterval(intervalID); setKey(deferredTheme); } }; const intervalID = setInterval(pollForTheme, 50); return () => { clearInterval(intervalID); }; }, [deferredTheme]); let content = null; if (isProfiling) { content = <RecordingInProgress />; } else if (inMemoryTimelineData && inMemoryTimelineData.length > 0) { // TODO (timeline) Support multiple renderers. const timelineData = inMemoryTimelineData[0]; content = ( <TimelineSearchContextController profilerData={timelineData} viewState={viewState}> <TimelineSearchInput /> <CanvasPage profilerData={timelineData} viewState={viewState} /> </TimelineSearchContextController> ); } else if (file) { content = ( <Suspense fallback={<ProcessingData />}> <FileLoader file={file} key={key} onFileSelect={setFile} viewState={viewState} /> </Suspense> ); } else if (didRecordCommits) { content = <NoTimelineData />; } else if (isTimelineSupported) { content = <NoProfilingData />; } else { content = <TimelineNotSupported />; } return ( <div className={styles.Content} ref={ref}> {content} </div> ); } const ProcessingData = () => ( <div className={styles.EmptyStateContainer}> <div className={styles.Header}>Processing data...</div> <div className={styles.Row}>This should only take a minute.</div> </div> ); // $FlowFixMe[missing-local-annot] const CouldNotLoadProfile = ({error, onFileSelect}) => ( <div className={styles.EmptyStateContainer}> <div className={styles.Header}>Could not load profile</div> {error.message && ( <div className={styles.Row}> <div className={styles.ErrorMessage}>{error.message}</div> </div> )} <div className={styles.Row}> Try importing another Chrome performance profile. </div> </div> ); const NoTimelineData = () => ( <div className={styles.EmptyStateContainer}> <div className={styles.Row}> This current profile does not contain timeline data. </div> </div> ); const FileLoader = ({ file, onFileSelect, viewState, }: { file: File | null, onFileSelect: (file: File) => void, viewState: ViewState, }) => { if (file === null) { return null; } const dataOrError = importFile(file); if (dataOrError instanceof Error) { return ( <CouldNotLoadProfile error={dataOrError} onFileSelect={onFileSelect} /> ); } return ( <TimelineSearchContextController profilerData={dataOrError} viewState={viewState}> <TimelineSearchInput /> <CanvasPage profilerData={dataOrError} viewState={viewState} /> </TimelineSearchContextController> ); };
29.658683
104
0.689783
Python-Penetration-Testing-Cookbook
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "ComponentUsingHooksIndirectly", { enumerable: true, get: function () { return _ComponentUsingHooksIndirectly.Component; } }); Object.defineProperty(exports, "ComponentWithCustomHook", { enumerable: true, get: function () { return _ComponentWithCustomHook.Component; } }); Object.defineProperty(exports, "ComponentWithExternalCustomHooks", { enumerable: true, get: function () { return _ComponentWithExternalCustomHooks.Component; } }); Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", { enumerable: true, get: function () { return _ComponentWithMultipleHooksPerLine.Component; } }); Object.defineProperty(exports, "ComponentWithNestedHooks", { enumerable: true, get: function () { return _ComponentWithNestedHooks.Component; } }); Object.defineProperty(exports, "ContainingStringSourceMappingURL", { enumerable: true, get: function () { return _ContainingStringSourceMappingURL.Component; } }); Object.defineProperty(exports, "Example", { enumerable: true, get: function () { return _Example.Component; } }); Object.defineProperty(exports, "InlineRequire", { enumerable: true, get: function () { return _InlineRequire.Component; } }); Object.defineProperty(exports, "useTheme", { enumerable: true, get: function () { return _useTheme.default; } }); exports.ToDoList = void 0; var _ComponentUsingHooksIndirectly = require("./ComponentUsingHooksIndirectly"); var _ComponentWithCustomHook = require("./ComponentWithCustomHook"); var _ComponentWithExternalCustomHooks = require("./ComponentWithExternalCustomHooks"); var _ComponentWithMultipleHooksPerLine = require("./ComponentWithMultipleHooksPerLine"); var _ComponentWithNestedHooks = require("./ComponentWithNestedHooks"); var _ContainingStringSourceMappingURL = require("./ContainingStringSourceMappingURL"); var _Example = require("./Example"); var _InlineRequire = require("./InlineRequire"); var ToDoList = _interopRequireWildcard(require("./ToDoList")); exports.ToDoList = ToDoList; var _useTheme = _interopRequireDefault(require("./useTheme")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFTQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7OztBQUVBIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5fSBmcm9tICcuL0NvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5JztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhDdXN0b21Ib29rfSBmcm9tICcuL0NvbXBvbmVudFdpdGhDdXN0b21Ib29rJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZX0gZnJvbSAnLi9Db21wb25lbnRXaXRoTXVsdGlwbGVIb29rc1BlckxpbmUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgQ29tcG9uZW50V2l0aE5lc3RlZEhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhOZXN0ZWRIb29rcyc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBDb250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTH0gZnJvbSAnLi9Db250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTCc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBFeGFtcGxlfSBmcm9tICcuL0V4YW1wbGUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgSW5saW5lUmVxdWlyZX0gZnJvbSAnLi9JbmxpbmVSZXF1aXJlJztcbmltcG9ydCAqIGFzIFRvRG9MaXN0IGZyb20gJy4vVG9Eb0xpc3QnO1xuZXhwb3J0IHtUb0RvTGlzdH07XG5leHBvcnQge2RlZmF1bHQgYXMgdXNlVGhlbWV9IGZyb20gJy4vdXNlVGhlbWUnO1xuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiJdLCJtYXBwaW5ncyI6IkNBQUQifV1dfQ==
55.224719
1,740
0.818909
owtf
"use client"; // CJS-ESM async module module.exports = import('../Counter.js').then(m => { return m.Counter });
18.166667
52
0.640351
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/scheduler-unstable_mock.production.min.js'); } else { module.exports = require('./cjs/scheduler-unstable_mock.development.js'); }
27.375
78
0.699115
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=ToDoList.js.map?foo=bar&param=some_value
30.425
743
0.603939
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 {SuspenseEvent, TimelineData} from '../types'; import type { Interaction, IntrinsicSize, MouseMoveInteraction, Rect, ViewRefs, } from '../view-base'; import { durationToWidth, positioningScaleFactor, positionToTimestamp, timestampToPosition, widthToDuration, } from './utils/positioning'; import {drawText} from './utils/text'; import {formatDuration} from '../utils/formatting'; import { View, Surface, rectContainsPoint, rectIntersectsRect, intersectionOfRects, } from '../view-base'; import { BORDER_SIZE, COLORS, PENDING_SUSPENSE_EVENT_SIZE, SUSPENSE_EVENT_HEIGHT, } from './constants'; const ROW_WITH_BORDER_HEIGHT = SUSPENSE_EVENT_HEIGHT + BORDER_SIZE; const MAX_ROWS_TO_SHOW_INITIALLY = 3; export class SuspenseEventsView extends View { _depthToSuspenseEvent: Map<number, SuspenseEvent[]>; _hoveredEvent: SuspenseEvent | null = null; _intrinsicSize: IntrinsicSize; _maxDepth: number = 0; _profilerData: TimelineData; onHover: ((event: SuspenseEvent | null) => void) | null = null; constructor(surface: Surface, frame: Rect, profilerData: TimelineData) { super(surface, frame); this._profilerData = profilerData; this._performPreflightComputations(); } _performPreflightComputations() { this._depthToSuspenseEvent = new Map(); const {duration, suspenseEvents} = this._profilerData; suspenseEvents.forEach(event => { const depth = event.depth; this._maxDepth = Math.max(this._maxDepth, depth); if (!this._depthToSuspenseEvent.has(depth)) { this._depthToSuspenseEvent.set(depth, [event]); } else { // $FlowFixMe[incompatible-use] This is unnecessary. this._depthToSuspenseEvent.get(depth).push(event); } }); this._intrinsicSize = { width: duration, height: (this._maxDepth + 1) * ROW_WITH_BORDER_HEIGHT, hideScrollBarIfLessThanHeight: ROW_WITH_BORDER_HEIGHT, maxInitialHeight: ROW_WITH_BORDER_HEIGHT * MAX_ROWS_TO_SHOW_INITIALLY, }; } desiredSize(): IntrinsicSize { return this._intrinsicSize; } setHoveredEvent(hoveredEvent: SuspenseEvent | null) { if (this._hoveredEvent === hoveredEvent) { return; } this._hoveredEvent = hoveredEvent; this.setNeedsDisplay(); } /** * Draw a single `SuspenseEvent` as a box/span with text inside of it. */ _drawSingleSuspenseEvent( context: CanvasRenderingContext2D, rect: Rect, event: SuspenseEvent, baseY: number, scaleFactor: number, showHoverHighlight: boolean, ) { const {frame} = this; const { componentName, depth, duration, phase, promiseName, resolution, timestamp, warning, } = event; baseY += depth * ROW_WITH_BORDER_HEIGHT; let fillStyle = ((null: any): string); if (warning !== null) { fillStyle = showHoverHighlight ? COLORS.WARNING_BACKGROUND_HOVER : COLORS.WARNING_BACKGROUND; } else { switch (resolution) { case 'rejected': fillStyle = showHoverHighlight ? COLORS.REACT_SUSPENSE_REJECTED_EVENT_HOVER : COLORS.REACT_SUSPENSE_REJECTED_EVENT; break; case 'resolved': fillStyle = showHoverHighlight ? COLORS.REACT_SUSPENSE_RESOLVED_EVENT_HOVER : COLORS.REACT_SUSPENSE_RESOLVED_EVENT; break; case 'unresolved': fillStyle = showHoverHighlight ? COLORS.REACT_SUSPENSE_UNRESOLVED_EVENT_HOVER : COLORS.REACT_SUSPENSE_UNRESOLVED_EVENT; break; } } const xStart = timestampToPosition(timestamp, scaleFactor, frame); // Pending suspense events (ones that never resolved) won't have durations. // So instead we draw them as diamonds. if (duration === null) { const size = PENDING_SUSPENSE_EVENT_SIZE; const halfSize = size / 2; baseY += (SUSPENSE_EVENT_HEIGHT - PENDING_SUSPENSE_EVENT_SIZE) / 2; const y = baseY + halfSize; const suspenseRect: Rect = { origin: { x: xStart - halfSize, y: baseY, }, size: {width: size, height: size}, }; if (!rectIntersectsRect(suspenseRect, rect)) { return; // Not in view } context.beginPath(); context.fillStyle = fillStyle; context.moveTo(xStart, y - halfSize); context.lineTo(xStart + halfSize, y); context.lineTo(xStart, y + halfSize); context.lineTo(xStart - halfSize, y); context.fill(); } else { const xStop = timestampToPosition( timestamp + duration, scaleFactor, frame, ); const eventRect: Rect = { origin: { x: xStart, y: baseY, }, size: {width: xStop - xStart, height: SUSPENSE_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(); context.fillStyle = fillStyle; context.fillRect( drawableRect.origin.x, drawableRect.origin.y, drawableRect.size.width, drawableRect.size.height, ); let label = 'suspended'; if (promiseName != null) { label = promiseName; } else if (componentName != null) { label = `${componentName} ${label}`; } if (phase !== null) { label += ` during ${phase}`; } if (resolution !== 'unresolved') { label += ` - ${formatDuration(duration)}`; } drawText(label, context, eventRect, drawableRect); } } draw(context: CanvasRenderingContext2D) { const { frame, _profilerData: {suspenseEvents}, _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, ); suspenseEvents.forEach(event => { this._drawSingleSuspenseEvent( 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 + (i + 1) * ROW_WITH_BORDER_HEIGHT - BORDER_SIZE, }, size: { width: frame.size.width, height: BORDER_SIZE, }, }; if (rectIntersectsRect(borderFrame, visibleArea)) { const borderDrawableRect = intersectionOfRects( borderFrame, visibleArea, ); context.fillStyle = COLORS.REACT_WORK_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 suspenseEventsAtDepth = this._depthToSuspenseEvent.get(depth); if (suspenseEventsAtDepth) { // Find the event being hovered over. for (let index = suspenseEventsAtDepth.length - 1; index >= 0; index--) { const suspenseEvent = suspenseEventsAtDepth[index]; const {duration, timestamp} = suspenseEvent; if (duration === null) { const timestampAllowance = widthToDuration( PENDING_SUSPENSE_EVENT_SIZE / 2, scaleFactor, ); if ( timestamp - timestampAllowance <= hoverTimestamp && hoverTimestamp <= timestamp + timestampAllowance ) { this.currentCursor = 'context-menu'; viewRefs.hoveredView = this; onHover(suspenseEvent); return; } } else if ( hoverTimestamp >= timestamp && hoverTimestamp <= timestamp + duration ) { this.currentCursor = 'context-menu'; viewRefs.hoveredView = this; onHover(suspenseEvent); return; } } } onHover(null); } handleInteraction(interaction: Interaction, viewRefs: ViewRefs) { switch (interaction.type) { case 'mousemove': this._handleMouseMove(interaction, viewRefs); break; } } }
25.502778
79
0.609958
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable no-for-of-loops/no-for-of-loops */ 'use strict'; export default { meta: { type: 'suggestion', docs: { description: 'verifies the list of dependencies for Hooks like useEffect and similar', recommended: true, url: 'https://github.com/facebook/react/issues/14920', }, fixable: 'code', hasSuggestions: true, schema: [ { type: 'object', additionalProperties: false, enableDangerousAutofixThisMayCauseInfiniteLoops: false, properties: { additionalHooks: { type: 'string', }, enableDangerousAutofixThisMayCauseInfiniteLoops: { type: 'boolean', }, }, }, ], }, create(context) { // Parse the `additionalHooks` regex. const additionalHooks = context.options && context.options[0] && context.options[0].additionalHooks ? new RegExp(context.options[0].additionalHooks) : undefined; const enableDangerousAutofixThisMayCauseInfiniteLoops = (context.options && context.options[0] && context.options[0].enableDangerousAutofixThisMayCauseInfiniteLoops) || false; const options = { additionalHooks, enableDangerousAutofixThisMayCauseInfiniteLoops, }; function reportProblem(problem) { if (enableDangerousAutofixThisMayCauseInfiniteLoops) { // Used to enable legacy behavior. Dangerous. // Keep this as an option until major IDEs upgrade (including VSCode FB ESLint extension). if (Array.isArray(problem.suggest) && problem.suggest.length > 0) { problem.fix = problem.suggest[0].fix; } } context.report(problem); } const scopeManager = context.getSourceCode().scopeManager; // Should be shared between visitors. const setStateCallSites = new WeakMap(); const stateVariables = new WeakSet(); const stableKnownValueCache = new WeakMap(); const functionWithoutCapturedValueCache = new WeakMap(); const useEffectEventVariables = new WeakSet(); function memoizeWithWeakMap(fn, map) { return function (arg) { if (map.has(arg)) { // to verify cache hits: // console.log(arg.name) return map.get(arg); } const result = fn(arg); map.set(arg, result); return result; }; } /** * Visitor for both function expressions and arrow function expressions. */ function visitFunctionWithDependencies( node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, ) { if (isEffect && node.async) { reportProblem({ node: node, message: `Effect callbacks are synchronous to prevent race conditions. ` + `Put the async function inside:\n\n` + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + `}, [someId]); // Or [] if effect doesn't need props or state\n\n` + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching', }); } // Get the current scope. const scope = scopeManager.acquire(node); // Find all our "pure scopes". On every re-render of a component these // pure scopes may have changes to the variables declared within. So all // variables used in our reactive hook callback but declared in a pure // scope need to be listed as dependencies of our reactive hook callback. // // According to the rules of React you can't read a mutable value in pure // scope. We can't enforce this in a lint so we trust that all variables // declared outside of pure scope are indeed frozen. const pureScopes = new Set(); let componentScope = null; { let currentScope = scope.upper; while (currentScope) { pureScopes.add(currentScope); if (currentScope.type === 'function') { break; } currentScope = currentScope.upper; } // If there is no parent function scope then there are no pure scopes. // The ones we've collected so far are incorrect. So don't continue with // the lint. if (!currentScope) { return; } componentScope = currentScope; } const isArray = Array.isArray; // Next we'll define a few helpers that helps us // tell if some values don't have to be declared as deps. // Some are known to be stable based on Hook calls. // const [state, setState] = useState() / React.useState() // ^^^ true for this reference // const [state, dispatch] = useReducer() / React.useReducer() // ^^^ true for this reference // const ref = useRef() // ^^^ true for this reference // const onStuff = useEffectEvent(() => {}) // ^^^ true for this reference // False for everything else. function isStableKnownHookValue(resolved) { if (!isArray(resolved.defs)) { return false; } const def = resolved.defs[0]; if (def == null) { return false; } // Look for `let stuff = ...` if (def.node.type !== 'VariableDeclarator') { return false; } let init = def.node.init; if (init == null) { return false; } while (init.type === 'TSAsExpression' || init.type === 'AsExpression') { init = init.expression; } // Detect primitive constants // const foo = 42 let declaration = def.node.parent; if (declaration == null) { // This might happen if variable is declared after the callback. // In that case ESLint won't set up .parent refs. // So we'll set them up manually. fastFindReferenceWithParent(componentScope.block, def.node.id); declaration = def.node.parent; if (declaration == null) { return false; } } if ( declaration.kind === 'const' && init.type === 'Literal' && (typeof init.value === 'string' || typeof init.value === 'number' || init.value === null) ) { // Definitely stable return true; } // Detect known Hook calls // const [_, setState] = useState() if (init.type !== 'CallExpression') { return false; } let callee = init.callee; // Step into `= React.something` initializer. if ( callee.type === 'MemberExpression' && callee.object.name === 'React' && callee.property != null && !callee.computed ) { callee = callee.property; } if (callee.type !== 'Identifier') { return false; } const id = def.node.id; const {name} = callee; if (name === 'useRef' && id.type === 'Identifier') { // useRef() return value is stable. return true; } else if ( isUseEffectEventIdentifier(callee) && id.type === 'Identifier' ) { for (const ref of resolved.references) { if (ref !== id) { useEffectEventVariables.add(ref.identifier); } } // useEffectEvent() return value is always unstable. return true; } else if (name === 'useState' || name === 'useReducer') { // Only consider second value in initializing tuple stable. if ( id.type === 'ArrayPattern' && id.elements.length === 2 && isArray(resolved.identifiers) ) { // Is second tuple value the same reference we're checking? if (id.elements[1] === resolved.identifiers[0]) { if (name === 'useState') { const references = resolved.references; let writeCount = 0; for (let i = 0; i < references.length; i++) { if (references[i].isWrite()) { writeCount++; } if (writeCount > 1) { return false; } setStateCallSites.set( references[i].identifier, id.elements[0], ); } } // Setter is stable. return true; } else if (id.elements[0] === resolved.identifiers[0]) { if (name === 'useState') { const references = resolved.references; for (let i = 0; i < references.length; i++) { stateVariables.add(references[i].identifier); } } // State variable itself is dynamic. return false; } } } else if (name === 'useTransition') { // Only consider second value in initializing tuple stable. if ( id.type === 'ArrayPattern' && id.elements.length === 2 && Array.isArray(resolved.identifiers) ) { // Is second tuple value the same reference we're checking? if (id.elements[1] === resolved.identifiers[0]) { // Setter is stable. return true; } } } // By default assume it's dynamic. return false; } // Some are just functions that don't reference anything dynamic. function isFunctionWithoutCapturedValues(resolved) { if (!isArray(resolved.defs)) { return false; } const def = resolved.defs[0]; if (def == null) { return false; } if (def.node == null || def.node.id == null) { return false; } // Search the direct component subscopes for // top-level function definitions matching this reference. const fnNode = def.node; const childScopes = componentScope.childScopes; let fnScope = null; let i; for (i = 0; i < childScopes.length; i++) { const childScope = childScopes[i]; const childScopeBlock = childScope.block; if ( // function handleChange() {} (fnNode.type === 'FunctionDeclaration' && childScopeBlock === fnNode) || // const handleChange = () => {} // const handleChange = function() {} (fnNode.type === 'VariableDeclarator' && childScopeBlock.parent === fnNode) ) { // Found it! fnScope = childScope; break; } } if (fnScope == null) { return false; } // Does this function capture any values // that are in pure scopes (aka render)? for (i = 0; i < fnScope.through.length; i++) { const ref = fnScope.through[i]; if (ref.resolved == null) { continue; } if ( pureScopes.has(ref.resolved.scope) && // Stable values are fine though, // although we won't check functions deeper. !memoizedIsStableKnownHookValue(ref.resolved) ) { return false; } } // If we got here, this function doesn't capture anything // from render--or everything it captures is known stable. return true; } // Remember such values. Avoid re-running extra checks on them. const memoizedIsStableKnownHookValue = memoizeWithWeakMap( isStableKnownHookValue, stableKnownValueCache, ); const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap( isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache, ); // These are usually mistaken. Collect them. const currentRefsInEffectCleanup = new Map(); // Is this reference inside a cleanup function for this effect node? // We can check by traversing scopes upwards from the reference, and checking // if the last "return () => " we encounter is located directly inside the effect. function isInsideEffectCleanup(reference) { let curScope = reference.from; let isInReturnedFunction = false; while (curScope.block !== node) { if (curScope.type === 'function') { isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === 'ReturnStatement'; } curScope = curScope.upper; } return isInReturnedFunction; } // Get dependencies from all our resolved references in pure scopes. // Key is dependency string, value is whether it's stable. const dependencies = new Map(); const optionalChains = new Map(); gatherDependenciesRecursively(scope); function gatherDependenciesRecursively(currentScope) { for (const reference of currentScope.references) { // If this reference is not resolved or it is not declared in a pure // scope then we don't care about this reference. if (!reference.resolved) { continue; } if (!pureScopes.has(reference.resolved.scope)) { continue; } // Narrow the scope of a dependency if it is, say, a member expression. // Then normalize the narrowed dependency. const referenceNode = fastFindReferenceWithParent( node, reference.identifier, ); const dependencyNode = getDependency(referenceNode); const dependency = analyzePropertyChain( dependencyNode, optionalChains, ); // Accessing ref.current inside effect cleanup is bad. if ( // We're in an effect... isEffect && // ... and this look like accessing .current... dependencyNode.type === 'Identifier' && (dependencyNode.parent.type === 'MemberExpression' || dependencyNode.parent.type === 'OptionalMemberExpression') && !dependencyNode.parent.computed && dependencyNode.parent.property.type === 'Identifier' && dependencyNode.parent.property.name === 'current' && // ...in a cleanup function or below... isInsideEffectCleanup(reference) ) { currentRefsInEffectCleanup.set(dependency, { reference, dependencyNode, }); } if ( dependencyNode.parent.type === 'TSTypeQuery' || dependencyNode.parent.type === 'TSTypeReference' ) { continue; } const def = reference.resolved.defs[0]; if (def == null) { continue; } // Ignore references to the function itself as it's not defined yet. if (def.node != null && def.node.init === node.parent) { continue; } // Ignore Flow type parameters if (def.type === 'TypeParameter') { continue; } // Add the dependency to a map so we can make sure it is referenced // again in our dependencies array. Remember whether it's stable. if (!dependencies.has(dependency)) { const resolved = reference.resolved; const isStable = memoizedIsStableKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved); dependencies.set(dependency, { isStable, references: [reference], }); } else { dependencies.get(dependency).references.push(reference); } } for (const childScope of currentScope.childScopes) { gatherDependenciesRecursively(childScope); } } // Warn about accessing .current in cleanup effects. currentRefsInEffectCleanup.forEach( ({reference, dependencyNode}, dependency) => { const references = reference.resolved.references; // Is React managing this ref or us? // Let's see if we can find a .current assignment. let foundCurrentAssignment = false; for (let i = 0; i < references.length; i++) { const {identifier} = references[i]; const {parent} = identifier; if ( parent != null && // ref.current // Note: no need to handle OptionalMemberExpression because it can't be LHS. parent.type === 'MemberExpression' && !parent.computed && parent.property.type === 'Identifier' && parent.property.name === 'current' && // ref.current = <something> parent.parent.type === 'AssignmentExpression' && parent.parent.left === parent ) { foundCurrentAssignment = true; break; } } // We only want to warn about React-managed refs. if (foundCurrentAssignment) { return; } reportProblem({ node: dependencyNode.parent.property, message: `The ref value '${dependency}.current' will likely have ` + `changed by the time this effect cleanup function runs. If ` + `this ref points to a node rendered by React, copy ` + `'${dependency}.current' to a variable inside the effect, and ` + `use that variable in the cleanup function.`, }); }, ); // Warn about assigning to variables in the outer scope. // Those are usually bugs. const staleAssignments = new Set(); function reportStaleAssignment(writeExpr, key) { if (staleAssignments.has(key)) { return; } staleAssignments.add(key); reportProblem({ node: writeExpr, message: `Assignments to the '${key}' variable from inside React Hook ` + `${context.getSource(reactiveHook)} will be lost after each ` + `render. To preserve the value over time, store it in a useRef ` + `Hook and keep the mutable value in the '.current' property. ` + `Otherwise, you can move this variable directly inside ` + `${context.getSource(reactiveHook)}.`, }); } // Remember which deps are stable and report bad usage first. const stableDependencies = new Set(); dependencies.forEach(({isStable, references}, key) => { if (isStable) { stableDependencies.add(key); } references.forEach(reference => { if (reference.writeExpr) { reportStaleAssignment(reference.writeExpr, key); } }); }); if (staleAssignments.size > 0) { // The intent isn't clear so we'll wait until you fix those first. return; } if (!declaredDependenciesNode) { // Check if there are any top-level setState() calls. // Those tend to lead to infinite loops. let setStateInsideEffectWithoutDeps = null; dependencies.forEach(({isStable, references}, key) => { if (setStateInsideEffectWithoutDeps) { return; } references.forEach(reference => { if (setStateInsideEffectWithoutDeps) { return; } const id = reference.identifier; const isSetState = setStateCallSites.has(id); if (!isSetState) { return; } let fnScope = reference.from; while (fnScope.type !== 'function') { fnScope = fnScope.upper; } const isDirectlyInsideEffect = fnScope.block === node; if (isDirectlyInsideEffect) { // TODO: we could potentially ignore early returns. setStateInsideEffectWithoutDeps = key; } }); }); if (setStateInsideEffectWithoutDeps) { const {suggestedDependencies} = collectRecommendations({ dependencies, declaredDependencies: [], stableDependencies, externalDependencies: new Set(), isEffect: true, }); reportProblem({ node: reactiveHook, message: `React Hook ${reactiveHookName} contains a call to '${setStateInsideEffectWithoutDeps}'. ` + `Without a list of dependencies, this can lead to an infinite chain of updates. ` + `To fix this, pass [` + suggestedDependencies.join(', ') + `] as a second argument to the ${reactiveHookName} Hook.`, suggest: [ { desc: `Add dependencies array: [${suggestedDependencies.join( ', ', )}]`, fix(fixer) { return fixer.insertTextAfter( node, `, [${suggestedDependencies.join(', ')}]`, ); }, }, ], }); } return; } const declaredDependencies = []; const externalDependencies = new Set(); if (declaredDependenciesNode.type !== 'ArrayExpression') { // If the declared dependencies are not an array expression then we // can't verify that the user provided the correct dependencies. Tell // the user this in an error. reportProblem({ node: declaredDependenciesNode, message: `React Hook ${context.getSource(reactiveHook)} was passed a ` + 'dependency list that is not an array literal. This means we ' + "can't statically verify whether you've passed the correct " + 'dependencies.', }); } else { declaredDependenciesNode.elements.forEach(declaredDependencyNode => { // Skip elided elements. if (declaredDependencyNode === null) { return; } // If we see a spread element then add a special warning. if (declaredDependencyNode.type === 'SpreadElement') { reportProblem({ node: declaredDependencyNode, message: `React Hook ${context.getSource(reactiveHook)} has a spread ` + "element in its dependency array. This means we can't " + "statically verify whether you've passed the " + 'correct dependencies.', }); return; } if (useEffectEventVariables.has(declaredDependencyNode)) { reportProblem({ node: declaredDependencyNode, message: 'Functions returned from `useEffectEvent` must not be included in the dependency array. ' + `Remove \`${context.getSource( declaredDependencyNode, )}\` from the list.`, suggest: [ { desc: `Remove the dependency \`${context.getSource( declaredDependencyNode, )}\``, fix(fixer) { return fixer.removeRange(declaredDependencyNode.range); }, }, ], }); } // Try to normalize the declared dependency. If we can't then an error // will be thrown. We will catch that error and report an error. let declaredDependency; try { declaredDependency = analyzePropertyChain( declaredDependencyNode, null, ); } catch (error) { if (/Unsupported node type/.test(error.message)) { if (declaredDependencyNode.type === 'Literal') { if (dependencies.has(declaredDependencyNode.value)) { reportProblem({ node: declaredDependencyNode, message: `The ${declaredDependencyNode.raw} literal is not a valid dependency ` + `because it never changes. ` + `Did you mean to include ${declaredDependencyNode.value} in the array instead?`, }); } else { reportProblem({ node: declaredDependencyNode, message: `The ${declaredDependencyNode.raw} literal is not a valid dependency ` + 'because it never changes. You can safely remove it.', }); } } else { reportProblem({ node: declaredDependencyNode, message: `React Hook ${context.getSource(reactiveHook)} has a ` + `complex expression in the dependency array. ` + 'Extract it to a separate variable so it can be statically checked.', }); } return; } else { throw error; } } let maybeID = declaredDependencyNode; while ( maybeID.type === 'MemberExpression' || maybeID.type === 'OptionalMemberExpression' || maybeID.type === 'ChainExpression' ) { maybeID = maybeID.object || maybeID.expression.object; } const isDeclaredInComponent = !componentScope.through.some( ref => ref.identifier === maybeID, ); // Add the dependency to our declared dependency map. declaredDependencies.push({ key: declaredDependency, node: declaredDependencyNode, }); if (!isDeclaredInComponent) { externalDependencies.add(declaredDependency); } }); } const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies, } = collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect, }); let suggestedDeps = suggestedDependencies; const problemCount = duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size; if (problemCount === 0) { // If nothing else to report, check if some dependencies would // invalidate on every render. const constructions = scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope, }); constructions.forEach( ({construction, isUsedOutsideOfHook, depType}) => { const wrapperHook = depType === 'function' ? 'useCallback' : 'useMemo'; const constructionType = depType === 'function' ? 'definition' : 'initialization'; const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`; const advice = isUsedOutsideOfHook ? `To fix this, ${defaultAdvice}` : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`; const causation = depType === 'conditional' || depType === 'logical expression' ? 'could make' : 'makes'; const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ` + `${reactiveHookName} Hook (at line ${declaredDependenciesNode.loc.start.line}) ` + `change on every render. ${advice}`; let suggest; // Only handle the simple case of variable assignments. // Wrapping function declarations can mess up hoisting. if ( isUsedOutsideOfHook && construction.type === 'Variable' && // Objects may be mutated after construction, which would make this // fix unsafe. Functions _probably_ won't be mutated, so we'll // allow this fix for them. depType === 'function' ) { suggest = [ { desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`, fix(fixer) { const [before, after] = wrapperHook === 'useMemo' ? [`useMemo(() => { return `, '; })'] : ['useCallback(', ')']; return [ // TODO: also add an import? fixer.insertTextBefore(construction.node.init, before), // TODO: ideally we'd gather deps here but it would require // restructuring the rule code. This will cause a new lint // error to appear immediately for useCallback. Note we're // not adding [] because would that changes semantics. fixer.insertTextAfter(construction.node.init, after), ]; }, }, ]; } // TODO: What if the function needs to change on every render anyway? // Should we suggest removing effect deps as an appropriate fix too? reportProblem({ // TODO: Why not report this at the dependency site? node: construction.node, message, suggest, }); }, ); return; } // If we're going to report a missing dependency, // we might as well recalculate the list ignoring // the currently specified deps. This can result // in some extra deduplication. We can't do this // for effects though because those have legit // use cases for over-specifying deps. if (!isEffect && missingDependencies.size > 0) { suggestedDeps = collectRecommendations({ dependencies, declaredDependencies: [], // Pretend we don't know stableDependencies, externalDependencies, isEffect, }).suggestedDependencies; } // Alphabetize the suggestions, but only if deps were already alphabetized. function areDeclaredDepsAlphabetized() { if (declaredDependencies.length === 0) { return true; } const declaredDepKeys = declaredDependencies.map(dep => dep.key); const sortedDeclaredDepKeys = declaredDepKeys.slice().sort(); return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(','); } if (areDeclaredDepsAlphabetized()) { suggestedDeps.sort(); } // Most of our algorithm deals with dependency paths with optional chaining stripped. // This function is the last step before printing a dependency, so now is a good time to // check whether any members in our path are always used as optional-only. In that case, // we will use ?. instead of . to concatenate those parts of the path. function formatDependency(path) { const members = path.split('.'); let finalPath = ''; for (let i = 0; i < members.length; i++) { if (i !== 0) { const pathSoFar = members.slice(0, i + 1).join('.'); const isOptional = optionalChains.get(pathSoFar) === true; finalPath += isOptional ? '?.' : '.'; } finalPath += members[i]; } return finalPath; } function getWarningMessage(deps, singlePrefix, label, fixVerb) { if (deps.size === 0) { return null; } return ( (deps.size > 1 ? '' : singlePrefix + ' ') + label + ' ' + (deps.size > 1 ? 'dependencies' : 'dependency') + ': ' + joinEnglish( Array.from(deps) .sort() .map(name => "'" + formatDependency(name) + "'"), ) + `. Either ${fixVerb} ${ deps.size > 1 ? 'them' : 'it' } or remove the dependency array.` ); } let extraWarning = ''; if (unnecessaryDependencies.size > 0) { let badRef = null; Array.from(unnecessaryDependencies.keys()).forEach(key => { if (badRef !== null) { return; } if (key.endsWith('.current')) { badRef = key; } }); if (badRef !== null) { extraWarning = ` Mutable values like '${badRef}' aren't valid dependencies ` + "because mutating them doesn't re-render the component."; } else if (externalDependencies.size > 0) { const dep = Array.from(externalDependencies)[0]; // Don't show this warning for things that likely just got moved *inside* the callback // because in that case they're clearly not referring to globals. if (!scope.set.has(dep)) { extraWarning = ` Outer scope values like '${dep}' aren't valid dependencies ` + `because mutating them doesn't re-render the component.`; } } } // `props.foo()` marks `props` as a dependency because it has // a `this` value. This warning can be confusing. // So if we're going to show it, append a clarification. if (!extraWarning && missingDependencies.has('props')) { const propDep = dependencies.get('props'); if (propDep == null) { return; } const refs = propDep.references; if (!Array.isArray(refs)) { return; } let isPropsOnlyUsedInMembers = true; for (let i = 0; i < refs.length; i++) { const ref = refs[i]; const id = fastFindReferenceWithParent( componentScope.block, ref.identifier, ); if (!id) { isPropsOnlyUsedInMembers = false; break; } const parent = id.parent; if (parent == null) { isPropsOnlyUsedInMembers = false; break; } if ( parent.type !== 'MemberExpression' && parent.type !== 'OptionalMemberExpression' ) { isPropsOnlyUsedInMembers = false; break; } } if (isPropsOnlyUsedInMembers) { extraWarning = ` However, 'props' will change when *any* prop changes, so the ` + `preferred fix is to destructure the 'props' object outside of ` + `the ${reactiveHookName} call and refer to those specific props ` + `inside ${context.getSource(reactiveHook)}.`; } } if (!extraWarning && missingDependencies.size > 0) { // See if the user is trying to avoid specifying a callable prop. // This usually means they're unaware of useCallback. let missingCallbackDep = null; missingDependencies.forEach(missingDep => { if (missingCallbackDep) { return; } // Is this a variable from top scope? const topScopeRef = componentScope.set.get(missingDep); const usedDep = dependencies.get(missingDep); if (usedDep.references[0].resolved !== topScopeRef) { return; } // Is this a destructured prop? const def = topScopeRef.defs[0]; if (def == null || def.name == null || def.type !== 'Parameter') { return; } // Was it called in at least one case? Then it's a function. let isFunctionCall = false; let id; for (let i = 0; i < usedDep.references.length; i++) { id = usedDep.references[i].identifier; if ( id != null && id.parent != null && (id.parent.type === 'CallExpression' || id.parent.type === 'OptionalCallExpression') && id.parent.callee === id ) { isFunctionCall = true; break; } } if (!isFunctionCall) { return; } // If it's missing (i.e. in component scope) *and* it's a parameter // then it is definitely coming from props destructuring. // (It could also be props itself but we wouldn't be calling it then.) missingCallbackDep = missingDep; }); if (missingCallbackDep !== null) { extraWarning = ` If '${missingCallbackDep}' changes too often, ` + `find the parent component that defines it ` + `and wrap that definition in useCallback.`; } } if (!extraWarning && missingDependencies.size > 0) { let setStateRecommendation = null; missingDependencies.forEach(missingDep => { if (setStateRecommendation !== null) { return; } const usedDep = dependencies.get(missingDep); const references = usedDep.references; let id; let maybeCall; for (let i = 0; i < references.length; i++) { id = references[i].identifier; maybeCall = id.parent; // Try to see if we have setState(someExpr(missingDep)). while (maybeCall != null && maybeCall !== componentScope.block) { if (maybeCall.type === 'CallExpression') { const correspondingStateVariable = setStateCallSites.get( maybeCall.callee, ); if (correspondingStateVariable != null) { if (correspondingStateVariable.name === missingDep) { // setCount(count + 1) setStateRecommendation = { missingDep, setter: maybeCall.callee.name, form: 'updater', }; } else if (stateVariables.has(id)) { // setCount(count + increment) setStateRecommendation = { missingDep, setter: maybeCall.callee.name, form: 'reducer', }; } else { const resolved = references[i].resolved; if (resolved != null) { // If it's a parameter *and* a missing dep, // it must be a prop or something inside a prop. // Therefore, recommend an inline reducer. const def = resolved.defs[0]; if (def != null && def.type === 'Parameter') { setStateRecommendation = { missingDep, setter: maybeCall.callee.name, form: 'inlineReducer', }; } } } break; } } maybeCall = maybeCall.parent; } if (setStateRecommendation !== null) { break; } } }); if (setStateRecommendation !== null) { switch (setStateRecommendation.form) { case 'reducer': extraWarning = ` You can also replace multiple useState variables with useReducer ` + `if '${setStateRecommendation.setter}' needs the ` + `current value of '${setStateRecommendation.missingDep}'.`; break; case 'inlineReducer': extraWarning = ` If '${setStateRecommendation.setter}' needs the ` + `current value of '${setStateRecommendation.missingDep}', ` + `you can also switch to useReducer instead of useState and ` + `read '${setStateRecommendation.missingDep}' in the reducer.`; break; case 'updater': extraWarning = ` You can also do a functional update '${ setStateRecommendation.setter }(${setStateRecommendation.missingDep.slice( 0, 1, )} => ...)' if you only need '${ setStateRecommendation.missingDep }'` + ` in the '${setStateRecommendation.setter}' call.`; break; default: throw new Error('Unknown case.'); } } } reportProblem({ node: declaredDependenciesNode, message: `React Hook ${context.getSource(reactiveHook)} has ` + // To avoid a long message, show the next actionable item. (getWarningMessage(missingDependencies, 'a', 'missing', 'include') || getWarningMessage( unnecessaryDependencies, 'an', 'unnecessary', 'exclude', ) || getWarningMessage( duplicateDependencies, 'a', 'duplicate', 'omit', )) + extraWarning, suggest: [ { desc: `Update the dependencies array to be: [${suggestedDeps .map(formatDependency) .join(', ')}]`, fix(fixer) { // TODO: consider preserving the comments or formatting? return fixer.replaceText( declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(', ')}]`, ); }, }, ], }); } function visitCallExpression(node) { const callbackIndex = getReactiveHookCallbackIndex(node.callee, options); if (callbackIndex === -1) { // Not a React Hook call that needs deps. return; } const callback = node.arguments[callbackIndex]; const reactiveHook = node.callee; const reactiveHookName = getNodeWithoutReactNamespace(reactiveHook).name; const maybeNode = node.arguments[callbackIndex + 1]; const declaredDependenciesNode = maybeNode && !(maybeNode.type === 'Identifier' && maybeNode.name === 'undefined') ? maybeNode : undefined; const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); // Check whether a callback is supplied. If there is no callback supplied // then the hook will not work and React will throw a TypeError. // So no need to check for dependency inclusion. if (!callback) { reportProblem({ node: reactiveHook, message: `React Hook ${reactiveHookName} requires an effect callback. ` + `Did you forget to pass a callback to the hook?`, }); return; } // Check the declared dependencies for this reactive hook. If there is no // second argument then the reactive callback will re-run on every render. // So no need to check for dependency inclusion. if (!declaredDependenciesNode && !isEffect) { // These are only used for optimization. if ( reactiveHookName === 'useMemo' || reactiveHookName === 'useCallback' ) { // TODO: Can this have a suggestion? reportProblem({ node: reactiveHook, message: `React Hook ${reactiveHookName} does nothing when called with ` + `only one argument. Did you forget to pass an array of ` + `dependencies?`, }); } return; } switch (callback.type) { case 'FunctionExpression': case 'ArrowFunctionExpression': visitFunctionWithDependencies( callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, ); return; // Handled case 'Identifier': if (!declaredDependenciesNode) { // No deps, no problems. return; // Handled } // The function passed as a callback is not written inline. // But perhaps it's in the dependencies array? if ( declaredDependenciesNode.elements && declaredDependenciesNode.elements.some( el => el && el.type === 'Identifier' && el.name === callback.name, ) ) { // If it's already in the list of deps, we don't care because // this is valid regardless. return; // Handled } // We'll do our best effort to find it, complain otherwise. const variable = context.getScope().set.get(callback.name); if (variable == null || variable.defs == null) { // If it's not in scope, we don't care. return; // Handled } // The function passed as a callback is not written inline. // But it's defined somewhere in the render scope. // We'll do our best effort to find and check it, complain otherwise. const def = variable.defs[0]; if (!def || !def.node) { break; // Unhandled } if (def.type !== 'Variable' && def.type !== 'FunctionName') { // Parameter or an unusual pattern. Bail out. break; // Unhandled } switch (def.node.type) { case 'FunctionDeclaration': // useEffect(() => { ... }, []); visitFunctionWithDependencies( def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, ); return; // Handled case 'VariableDeclarator': const init = def.node.init; if (!init) { break; // Unhandled } switch (init.type) { // const effectBody = () => {...}; // useEffect(effectBody, []); case 'ArrowFunctionExpression': case 'FunctionExpression': // We can inspect this function as if it were inline. visitFunctionWithDependencies( init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, ); return; // Handled } break; // Unhandled } break; // Unhandled default: // useEffect(generateEffectBody(), []); reportProblem({ node: reactiveHook, message: `React Hook ${reactiveHookName} received a function whose dependencies ` + `are unknown. Pass an inline function instead.`, }); return; // Handled } // Something unusual. Fall back to suggesting to add the body itself as a dep. reportProblem({ node: reactiveHook, message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. ` + `Either include it or remove the dependency array.`, suggest: [ { desc: `Update the dependencies array to be: [${callback.name}]`, fix(fixer) { return fixer.replaceText( declaredDependenciesNode, `[${callback.name}]`, ); }, }, ], }); } return { CallExpression: visitCallExpression, }; }, }; // The meat of the logic. function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect, }) { // Our primary data structure. // It is a logical representation of property chains: // `props` -> `props.foo` -> `props.foo.bar` -> `props.foo.bar.baz` // -> `props.lol` // -> `props.huh` -> `props.huh.okay` // -> `props.wow` // We'll use it to mark nodes that are *used* by the programmer, // and the nodes that were *declared* as deps. Then we will // traverse it to learn which deps are missing or unnecessary. const depTree = createDepTree(); function createDepTree() { return { isUsed: false, // True if used in code isSatisfiedRecursively: false, // True if specified in deps isSubtreeUsed: false, // True if something deeper is used by code children: new Map(), // Nodes for properties }; } // Mark all required nodes first. // Imagine exclamation marks next to each used deep property. dependencies.forEach((_, key) => { const node = getOrCreateNodeByPath(depTree, key); node.isUsed = true; markAllParentsByPath(depTree, key, parent => { parent.isSubtreeUsed = true; }); }); // Mark all satisfied nodes. // Imagine checkmarks next to each declared dependency. declaredDependencies.forEach(({key}) => { const node = getOrCreateNodeByPath(depTree, key); node.isSatisfiedRecursively = true; }); stableDependencies.forEach(key => { const node = getOrCreateNodeByPath(depTree, key); node.isSatisfiedRecursively = true; }); // Tree manipulation helpers. function getOrCreateNodeByPath(rootNode, path) { const keys = path.split('.'); let node = rootNode; for (const key of keys) { let child = node.children.get(key); if (!child) { child = createDepTree(); node.children.set(key, child); } node = child; } return node; } function markAllParentsByPath(rootNode, path, fn) { const keys = path.split('.'); let node = rootNode; for (const key of keys) { const child = node.children.get(key); if (!child) { return; } fn(child); node = child; } } // Now we can learn which dependencies are missing or necessary. const missingDependencies = new Set(); const satisfyingDependencies = new Set(); scanTreeRecursively( depTree, missingDependencies, satisfyingDependencies, key => key, ); function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) { node.children.forEach((child, key) => { const path = keyToPath(key); if (child.isSatisfiedRecursively) { if (child.isSubtreeUsed) { // Remember this dep actually satisfied something. satisfyingPaths.add(path); } // It doesn't matter if there's something deeper. // It would be transitively satisfied since we assume immutability. // `props.foo` is enough if you read `props.foo.id`. return; } if (child.isUsed) { // Remember that no declared deps satisfied this node. missingPaths.add(path); // If we got here, nothing in its subtree was satisfied. // No need to search further. return; } scanTreeRecursively( child, missingPaths, satisfyingPaths, childKey => path + '.' + childKey, ); }); } // Collect suggestions in the order they were originally specified. const suggestedDependencies = []; const unnecessaryDependencies = new Set(); const duplicateDependencies = new Set(); declaredDependencies.forEach(({key}) => { // Does this declared dep satisfy a real need? if (satisfyingDependencies.has(key)) { if (suggestedDependencies.indexOf(key) === -1) { // Good one. suggestedDependencies.push(key); } else { // Duplicate. duplicateDependencies.add(key); } } else { if ( isEffect && !key.endsWith('.current') && !externalDependencies.has(key) ) { // Effects are allowed extra "unnecessary" deps. // Such as resetting scroll when ID changes. // Consider them legit. // The exception is ref.current which is always wrong. if (suggestedDependencies.indexOf(key) === -1) { suggestedDependencies.push(key); } } else { // It's definitely not needed. unnecessaryDependencies.add(key); } } }); // Then add the missing ones at the end. missingDependencies.forEach(key => { suggestedDependencies.push(key); }); return { suggestedDependencies, unnecessaryDependencies, duplicateDependencies, missingDependencies, }; } // If the node will result in constructing a referentially unique value, return // its human readable type name, else return null. function getConstructionExpressionType(node) { switch (node.type) { case 'ObjectExpression': return 'object'; case 'ArrayExpression': return 'array'; case 'ArrowFunctionExpression': case 'FunctionExpression': return 'function'; case 'ClassExpression': return 'class'; case 'ConditionalExpression': if ( getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null ) { return 'conditional'; } return null; case 'LogicalExpression': if ( getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null ) { return 'logical expression'; } return null; case 'JSXFragment': return 'JSX fragment'; case 'JSXElement': return 'JSX element'; case 'AssignmentExpression': if (getConstructionExpressionType(node.right) != null) { return 'assignment expression'; } return null; case 'NewExpression': return 'object construction'; case 'Literal': if (node.value instanceof RegExp) { return 'regular expression'; } return null; case 'TypeCastExpression': case 'AsExpression': case 'TSAsExpression': return getConstructionExpressionType(node.expression); } return null; } // Finds variables declared as dependencies // that would invalidate on every render. function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope, }) { const constructions = declaredDependencies .map(({key}) => { const ref = componentScope.variables.find(v => v.name === key); if (ref == null) { return null; } const node = ref.defs[0]; if (node == null) { return null; } // const handleChange = function () {} // const handleChange = () => {} // const foo = {} // const foo = [] // etc. if ( node.type === 'Variable' && node.node.type === 'VariableDeclarator' && node.node.id.type === 'Identifier' && // Ensure this is not destructed assignment node.node.init != null ) { const constantExpressionType = getConstructionExpressionType( node.node.init, ); if (constantExpressionType != null) { return [ref, constantExpressionType]; } } // function handleChange() {} if ( node.type === 'FunctionName' && node.node.type === 'FunctionDeclaration' ) { return [ref, 'function']; } // class Foo {} if (node.type === 'ClassName' && node.node.type === 'ClassDeclaration') { return [ref, 'class']; } return null; }) .filter(Boolean); function isUsedOutsideOfHook(ref) { let foundWriteExpr = false; for (let i = 0; i < ref.references.length; i++) { const reference = ref.references[i]; if (reference.writeExpr) { if (foundWriteExpr) { // Two writes to the same function. return true; } else { // Ignore first write as it's not usage. foundWriteExpr = true; continue; } } let currentScope = reference.from; while (currentScope !== scope && currentScope != null) { currentScope = currentScope.upper; } if (currentScope !== scope) { // This reference is outside the Hook callback. // It can only be legit if it's the deps array. if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) { return true; } } } return false; } return constructions.map(([ref, depType]) => ({ construction: ref.defs[0], depType, isUsedOutsideOfHook: isUsedOutsideOfHook(ref), })); } /** * Assuming () means the passed/returned node: * (props) => (props) * props.(foo) => (props.foo) * props.foo.(bar) => (props).foo.bar * props.foo.bar.(baz) => (props).foo.bar.baz */ function getDependency(node) { if ( (node.parent.type === 'MemberExpression' || node.parent.type === 'OptionalMemberExpression') && node.parent.object === node && node.parent.property.name !== 'current' && !node.parent.computed && !( node.parent.parent != null && (node.parent.parent.type === 'CallExpression' || node.parent.parent.type === 'OptionalCallExpression') && node.parent.parent.callee === node.parent ) ) { return getDependency(node.parent); } else if ( // Note: we don't check OptionalMemberExpression because it can't be LHS. node.type === 'MemberExpression' && node.parent && node.parent.type === 'AssignmentExpression' && node.parent.left === node ) { return node.object; } else { return node; } } /** * Mark a node as either optional or required. * Note: If the node argument is an OptionalMemberExpression, it doesn't necessarily mean it is optional. * It just means there is an optional member somewhere inside. * This particular node might still represent a required member, so check .optional field. */ function markNode(node, optionalChains, result) { if (optionalChains) { if (node.optional) { // We only want to consider it optional if *all* usages were optional. if (!optionalChains.has(result)) { // Mark as (maybe) optional. If there's a required usage, this will be overridden. optionalChains.set(result, true); } } else { // Mark as required. optionalChains.set(result, false); } } } /** * Assuming () means the passed node. * (foo) -> 'foo' * foo(.)bar -> 'foo.bar' * foo.bar(.)baz -> 'foo.bar.baz' * Otherwise throw. */ function analyzePropertyChain(node, optionalChains) { if (node.type === 'Identifier' || node.type === 'JSXIdentifier') { const result = node.name; if (optionalChains) { // Mark as required. optionalChains.set(result, false); } return result; } else if (node.type === 'MemberExpression' && !node.computed) { const object = analyzePropertyChain(node.object, optionalChains); const property = analyzePropertyChain(node.property, null); const result = `${object}.${property}`; markNode(node, optionalChains, result); return result; } else if (node.type === 'OptionalMemberExpression' && !node.computed) { const object = analyzePropertyChain(node.object, optionalChains); const property = analyzePropertyChain(node.property, null); const result = `${object}.${property}`; markNode(node, optionalChains, result); return result; } else if (node.type === 'ChainExpression' && !node.computed) { const expression = node.expression; if (expression.type === 'CallExpression') { throw new Error(`Unsupported node type: ${expression.type}`); } const object = analyzePropertyChain(expression.object, optionalChains); const property = analyzePropertyChain(expression.property, null); const result = `${object}.${property}`; markNode(expression, optionalChains, result); return result; } else { throw new Error(`Unsupported node type: ${node.type}`); } } function getNodeWithoutReactNamespace(node, options) { if ( node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === 'React' && node.property.type === 'Identifier' && !node.computed ) { return node.property; } return node; } // What's the index of callback that needs to be analyzed for a given Hook? // -1 if it's not a Hook we care about (e.g. useState). // 0 for useEffect/useMemo/useCallback(fn). // 1 for useImperativeHandle(ref, fn). // For additionally configured Hooks, assume that they're like useEffect (0). function getReactiveHookCallbackIndex(calleeNode, options) { const node = getNodeWithoutReactNamespace(calleeNode); if (node.type !== 'Identifier') { return -1; } switch (node.name) { case 'useEffect': case 'useLayoutEffect': case 'useCallback': case 'useMemo': // useEffect(fn) return 0; case 'useImperativeHandle': // useImperativeHandle(ref, fn) return 1; default: if (node === calleeNode && options && options.additionalHooks) { // Allow the user to provide a regular expression which enables the lint to // target custom reactive hooks. let name; try { name = analyzePropertyChain(node, null); } catch (error) { if (/Unsupported node type/.test(error.message)) { return 0; } else { throw error; } } return options.additionalHooks.test(name) ? 0 : -1; } else { return -1; } } } /** * ESLint won't assign node.parent to references from context.getScope() * * So instead we search for the node from an ancestor assigning node.parent * as we go. This mutates the AST. * * This traversal is: * - optimized by only searching nodes with a range surrounding our target node * - agnostic to AST node types, it looks for `{ type: string, ... }` */ function fastFindReferenceWithParent(start, target) { const queue = [start]; let item = null; while (queue.length) { item = queue.shift(); if (isSameIdentifier(item, target)) { return item; } if (!isAncestorNodeOf(item, target)) { continue; } for (const [key, value] of Object.entries(item)) { if (key === 'parent') { continue; } if (isNodeLike(value)) { value.parent = item; queue.push(value); } else if (Array.isArray(value)) { value.forEach(val => { if (isNodeLike(val)) { val.parent = item; queue.push(val); } }); } } } return null; } function joinEnglish(arr) { let s = ''; for (let i = 0; i < arr.length; i++) { s += arr[i]; if (i === 0 && arr.length === 2) { s += ' and '; } else if (i === arr.length - 2 && arr.length > 2) { s += ', and '; } else if (i < arr.length - 1) { s += ', '; } } return s; } function isNodeLike(val) { return ( typeof val === 'object' && val !== null && !Array.isArray(val) && typeof val.type === 'string' ); } function isSameIdentifier(a, b) { return ( (a.type === 'Identifier' || a.type === 'JSXIdentifier') && a.type === b.type && a.name === b.name && a.range[0] === b.range[0] && a.range[1] === b.range[1] ); } function isAncestorNodeOf(a, b) { return a.range[0] <= b.range[0] && a.range[1] >= b.range[1]; } function isUseEffectEventIdentifier(node) { if (__EXPERIMENTAL__) { return node.type === 'Identifier' && node.name === 'useEffectEvent'; } return false; }
33.65257
130
0.5463
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 act; let React; let ReactDOMClient; let ReactTestUtils; describe('ReactElement', () => { let ComponentClass; beforeEach(() => { jest.resetModules(); act = require('internal-test-utils').act; React = require('react'); ReactDOMClient = require('react-dom/client'); ReactTestUtils = require('react-dom/test-utils'); // NOTE: We're explicitly not using JSX here. This is intended to test // classic JS without JSX. ComponentClass = class extends React.Component { render() { return React.createElement('div'); } }; }); it('returns a complete element according to spec', () => { const element = React.createElement(ComponentClass); expect(element.type).toBe(ComponentClass); expect(element.key).toBe(null); expect(element.ref).toBe(null); if (__DEV__) { expect(Object.isFrozen(element)).toBe(true); expect(Object.isFrozen(element.props)).toBe(true); } expect(element.props).toEqual({}); }); it('should warn when `key` is being accessed on composite element', async () => { class Child extends React.Component { render() { return <div>{this.props.key}</div>; } } class Parent extends React.Component { render() { return ( <div> <Child key="0" /> <Child key="1" /> <Child key="2" /> </div> ); } } const root = ReactDOMClient.createRoot(document.createElement('div')); await expect(async () => { await act(() => { root.render(<Parent />); }); }).toErrorDev( 'Child: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', ); }); it('should warn when `key` is being accessed on a host element', () => { const element = <div key="3" />; expect(() => void element.props.key).toErrorDev( 'div: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', {withoutStack: true}, ); }); it('should warn when `ref` is being accessed', async () => { class Child extends React.Component { render() { return <div> {this.props.ref} </div>; } } class Parent extends React.Component { render() { return ( <div> <Child ref={React.createRef()} /> </div> ); } } const root = ReactDOMClient.createRoot(document.createElement('div')); await expect(async () => { await act(() => { root.render(<Parent />); }); }).toErrorDev( 'Child: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', ); }); it('allows a string to be passed as the type', () => { const element = React.createElement('div'); expect(element.type).toBe('div'); expect(element.key).toBe(null); expect(element.ref).toBe(null); if (__DEV__) { expect(Object.isFrozen(element)).toBe(true); expect(Object.isFrozen(element.props)).toBe(true); } expect(element.props).toEqual({}); }); it('returns an immutable element', () => { const element = React.createElement(ComponentClass); if (__DEV__) { expect(() => (element.type = 'div')).toThrow(); } else { expect(() => (element.type = 'div')).not.toThrow(); } }); it('does not reuse the original config object', () => { const config = {foo: 1}; const element = React.createElement(ComponentClass, config); expect(element.props.foo).toBe(1); config.foo = 2; expect(element.props.foo).toBe(1); }); it('does not fail if config has no prototype', () => { const config = Object.create(null, {foo: {value: 1, enumerable: true}}); const element = React.createElement(ComponentClass, config); expect(element.props.foo).toBe(1); }); it('extracts key and ref from the config', () => { const element = React.createElement(ComponentClass, { key: '12', ref: '34', foo: '56', }); expect(element.type).toBe(ComponentClass); expect(element.key).toBe('12'); expect(element.ref).toBe('34'); if (__DEV__) { expect(Object.isFrozen(element)).toBe(true); expect(Object.isFrozen(element.props)).toBe(true); } expect(element.props).toEqual({foo: '56'}); }); it('extracts null key and ref', () => { const element = React.createElement(ComponentClass, { key: null, ref: null, foo: '12', }); expect(element.type).toBe(ComponentClass); expect(element.key).toBe('null'); expect(element.ref).toBe(null); if (__DEV__) { expect(Object.isFrozen(element)).toBe(true); expect(Object.isFrozen(element.props)).toBe(true); } expect(element.props).toEqual({foo: '12'}); }); it('ignores undefined key and ref', () => { const props = { foo: '56', key: undefined, ref: undefined, }; const element = React.createElement(ComponentClass, props); expect(element.type).toBe(ComponentClass); expect(element.key).toBe(null); expect(element.ref).toBe(null); if (__DEV__) { expect(Object.isFrozen(element)).toBe(true); expect(Object.isFrozen(element.props)).toBe(true); } expect(element.props).toEqual({foo: '56'}); }); it('ignores key and ref warning getters', () => { const elementA = React.createElement('div'); const elementB = React.createElement('div', elementA.props); expect(elementB.key).toBe(null); expect(elementB.ref).toBe(null); }); it('coerces the key to a string', () => { const element = React.createElement(ComponentClass, { key: 12, foo: '56', }); expect(element.type).toBe(ComponentClass); expect(element.key).toBe('12'); expect(element.ref).toBe(null); if (__DEV__) { expect(Object.isFrozen(element)).toBe(true); expect(Object.isFrozen(element.props)).toBe(true); } expect(element.props).toEqual({foo: '56'}); }); it('preserves the owner on the element', () => { let element; class Wrapper extends React.Component { render() { element = React.createElement(ComponentClass); return element; } } const instance = ReactTestUtils.renderIntoDocument( React.createElement(Wrapper), ); expect(element._owner.stateNode).toBe(instance); }); it('merges an additional argument onto the children prop', () => { const a = 1; const element = React.createElement( ComponentClass, { children: 'text', }, a, ); expect(element.props.children).toBe(a); }); it('does not override children if no rest args are provided', () => { const element = React.createElement(ComponentClass, { children: 'text', }); expect(element.props.children).toBe('text'); }); it('overrides children if null is provided as an argument', () => { const element = React.createElement( ComponentClass, { children: 'text', }, null, ); expect(element.props.children).toBe(null); }); it('merges rest arguments onto the children prop in an array', () => { const a = 1; const b = 2; const c = 3; const element = React.createElement(ComponentClass, null, a, b, c); expect(element.props.children).toEqual([1, 2, 3]); }); // NOTE: We're explicitly not using JSX here. This is intended to test // classic JS without JSX. it('allows static methods to be called using the type property', () => { class StaticMethodComponentClass extends React.Component { render() { return React.createElement('div'); } } StaticMethodComponentClass.someStaticMethod = () => 'someReturnValue'; const element = React.createElement(StaticMethodComponentClass); expect(element.type.someStaticMethod()).toBe('someReturnValue'); }); // NOTE: We're explicitly not using JSX here. This is intended to test // classic JS without JSX. it('is indistinguishable from a plain object', () => { const element = React.createElement('div', {className: 'foo'}); const object = {}; expect(element.constructor).toBe(object.constructor); }); // NOTE: We're explicitly not using JSX here. This is intended to test // classic JS without JSX. it('should use default prop value when removing a prop', async () => { class Component extends React.Component { render() { return React.createElement('span'); } } Component.defaultProps = {fruit: 'persimmon'}; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); const ref = React.createRef(); await act(() => { root.render(React.createElement(Component, {ref, fruit: 'mango'})); }); const instance = ref.current; expect(instance.props.fruit).toBe('mango'); await act(() => { root.render(React.createElement(Component)); }); expect(instance.props.fruit).toBe('persimmon'); }); // NOTE: We're explicitly not using JSX here. This is intended to test // classic JS without JSX. it('should normalize props with default values', () => { class Component extends React.Component { render() { return React.createElement('span', null, this.props.prop); } } Component.defaultProps = {prop: 'testKey'}; const instance = ReactTestUtils.renderIntoDocument( React.createElement(Component), ); expect(instance.props.prop).toBe('testKey'); const inst2 = ReactTestUtils.renderIntoDocument( React.createElement(Component, {prop: null}), ); expect(inst2.props.prop).toBe(null); }); it('throws when changing a prop (in dev) after element creation', async () => { class Outer extends React.Component { render() { const el = <div className="moo" />; if (__DEV__) { expect(function () { el.props.className = 'quack'; }).toThrow(); expect(el.props.className).toBe('moo'); } else { el.props.className = 'quack'; expect(el.props.className).toBe('quack'); } return el; } } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Outer color="orange" />); }); if (__DEV__) { expect(container.firstChild.className).toBe('moo'); } else { expect(container.firstChild.className).toBe('quack'); } }); it('throws when adding a prop (in dev) after element creation', async () => { const container = document.createElement('div'); class Outer extends React.Component { render() { const el = <div>{this.props.sound}</div>; if (__DEV__) { expect(function () { el.props.className = 'quack'; }).toThrow(); expect(el.props.className).toBe(undefined); } else { el.props.className = 'quack'; expect(el.props.className).toBe('quack'); } return el; } } Outer.defaultProps = {sound: 'meow'}; const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Outer />); }); expect(container.firstChild.textContent).toBe('meow'); if (__DEV__) { expect(container.firstChild.className).toBe(''); } else { expect(container.firstChild.className).toBe('quack'); } }); it('does not warn for NaN props', () => { class Test extends React.Component { render() { return <div />; } } const test = ReactTestUtils.renderIntoDocument(<Test value={+undefined} />); expect(test.props.value).toBeNaN(); }); });
28.725768
83
0.601527
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } // ?sourceMappingURL=([^\s'"]+)/gm function Component() { const [count, setCount] = (0, _react.useState)(0); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 18, columnNumber: 5 } }, /*#__PURE__*/_react.default.createElement("p", { __source: { fileName: _jsxFileName, lineNumber: 19, columnNumber: 7 } }, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", { onClick: () => setCount(count + 1), __source: { fileName: _jsxFileName, lineNumber: 20, columnNumber: 7 } }, "Click me")); } //# sourceMappingURL=ContainingStringSourceMappingURL.js.map?foo=bar&param=some_value
45.975
743
0.651225
null
'use strict'; const semver = require('semver'); const NODE_MODULES_DIR = process.env.RELEASE_CHANNEL === 'stable' ? 'oss-stable' : 'oss-experimental'; const REACT_VERSION = process.env.REACT_VERSION; const moduleNameMapper = {}; const setupFiles = []; // We only want to add these if we are in a regression test, IE if there // is a REACT_VERSION specified if (REACT_VERSION) { // React version 16.5 has a schedule package instead of a scheduler // package, so we need to rename them accordingly if (semver.satisfies(REACT_VERSION, '16.5')) { moduleNameMapper[ `^schedule$` ] = `<rootDir>/build/${NODE_MODULES_DIR}/schedule`; moduleNameMapper[ '^schedule/tracing$' ] = `<rootDir>/build/${NODE_MODULES_DIR}/schedule/tracing-profiling`; } // react-dom/client is only in v18.0.0 and up, so we // map it to react-dom instead if (semver.satisfies(REACT_VERSION, '<18.0')) { moduleNameMapper[ '^react-dom/client$' ] = `<rootDir>/build/${NODE_MODULES_DIR}/react-dom`; } setupFiles.push(require.resolve('./setupTests.build-devtools-regression')); } module.exports = { moduleNameMapper, setupFiles, };
26.809524
79
0.675236
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 {ReactClientValue} from 'react-server/src/ReactFlightServer'; import type {ServerContextJSONValue, Thenable} from 'shared/ReactTypes'; import type {ClientManifest} from './ReactFlightServerConfigWebpackBundler'; import type {ServerManifest} from 'react-client/src/ReactFlightClientConfig'; import { createRequest, startWork, startFlowing, stopFlowing, abort, } from 'react-server/src/ReactFlightServer'; import { createResponse, close, getRoot, } from 'react-server/src/ReactFlightReplyServer'; import { decodeAction, decodeFormState, } from 'react-server/src/ReactFlightActionServer'; export { registerServerReference, registerClientReference, createClientModuleProxy, } from './ReactFlightWebpackReferences'; type Options = { identifierPrefix?: string, signal?: AbortSignal, context?: Array<[string, ServerContextJSONValue]>, onError?: (error: mixed) => void, onPostpone?: (reason: string) => void, }; function renderToReadableStream( model: ReactClientValue, webpackMap: ClientManifest, options?: Options, ): ReadableStream { const request = createRequest( model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined, ); if (options && options.signal) { const signal = options.signal; if (signal.aborted) { abort(request, (signal: any).reason); } else { const listener = () => { abort(request, (signal: any).reason); signal.removeEventListener('abort', listener); }; signal.addEventListener('abort', listener); } } const stream = new ReadableStream( { type: 'bytes', start: (controller): ?Promise<void> => { startWork(request); }, pull: (controller): ?Promise<void> => { startFlowing(request, controller); }, cancel: (reason): ?Promise<void> => { stopFlowing(request); abort(request, reason); }, }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. {highWaterMark: 0}, ); return stream; } function decodeReply<T>( body: string | FormData, webpackMap: ServerManifest, ): Thenable<T> { if (typeof body === 'string') { const form = new FormData(); form.append('0', body); body = form; } const response = createResponse(webpackMap, '', body); const root = getRoot<T>(response); close(response); return root; } export {renderToReadableStream, decodeReply, decodeAction, decodeFormState};
24.844037
79
0.679688
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. * * @jest-environment node */ 'use strict'; class MockMessageChannel { constructor() { this.port1 = jest.fn(); this.port2 = jest.fn(); } } describe('Scheduling UMD bundle', () => { beforeEach(() => { // Fool SECRET_INTERNALS object into including UMD forwarding methods. global.__UMD__ = true; jest.resetModules(); jest.unmock('scheduler'); global.MessageChannel = MockMessageChannel; }); afterEach(() => { global.MessageChannel = undefined; }); function validateForwardedAPIs(api, forwardedAPIs) { const apiKeys = Object.keys(api).sort(); forwardedAPIs.forEach(forwardedAPI => { expect(Object.keys(forwardedAPI).sort()).toEqual(apiKeys); }); } it('should define the same scheduling API', () => { const api = require('../../index'); const umdAPIDev = require('../../npm/umd/scheduler.development'); const umdAPIProd = require('../../npm/umd/scheduler.production.min'); const umdAPIProfiling = require('../../npm/umd/scheduler.profiling.min'); const secretAPI = require('react/src/forks/ReactSharedInternalsClient.umd').default; validateForwardedAPIs(api, [ umdAPIDev, umdAPIProd, umdAPIProfiling, secretAPI.Scheduler, ]); }); });
25.472727
77
0.652921
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'; export { isValidElementType, typeOf, ContextConsumer, ContextProvider, Element, ForwardRef, Fragment, Lazy, Memo, Portal, Profiler, StrictMode, Suspense, SuspenseList, isAsyncMode, isConcurrentMode, isContextConsumer, isContextProvider, isElement, isForwardRef, isFragment, isLazy, isMemo, isPortal, isProfiler, isStrictMode, isSuspense, isSuspenseList, } from './src/ReactIs';
14.571429
66
0.701378
owtf
/* eslint-disable react/jsx-pascal-case */ import React from 'react'; import ReactDOM from 'react-dom'; import ThemeContext from './shared/ThemeContext'; // Note: this is a semi-private API, but it's ok to use it // if we never inspect the values, and only pass them through. import {__RouterContext} from 'react-router'; import {Provider} from 'react-redux'; // Pass through every context required by this tree. // The context object is populated in src/modern/withLegacyRoot. function Bridge({children, context}) { return ( <ThemeContext.Provider value={context.theme}> <__RouterContext.Provider value={context.router}> {/* If we used the newer [email protected] in the legacy/package.json, we woud instead import {ReactReduxContext} from 'react-redux' and render <ReactReduxContext.Provider value={context.reactRedux}>. */} <Provider store={context.reactRedux.store}>{children}</Provider> </__RouterContext.Provider> </ThemeContext.Provider> ); } export default function createLegacyRoot(container) { return { render(Component, props, context) { ReactDOM.render( <Bridge context={context}> <Component {...props} /> </Bridge>, container ); }, unmount() { ReactDOM.unmountComponentAtNode(container); }, }; }
29.954545
77
0.665687
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'; describe('ReactDOMConsoleErrorReporting', () => { let act; let React; let ReactDOM; let ReactDOMClient; let ErrorBoundary; let NoError; let container; let windowOnError; let waitForThrow; beforeEach(() => { jest.resetModules(); act = require('internal-test-utils').act; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); const InternalTestUtils = require('internal-test-utils'); waitForThrow = InternalTestUtils.waitForThrow; ErrorBoundary = class extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return <h1>Caught: {this.state.error.message}</h1>; } return this.props.children; } }; NoError = function () { return <h1>OK</h1>; }; container = document.createElement('div'); document.body.appendChild(container); windowOnError = jest.fn(); window.addEventListener('error', windowOnError); }); afterEach(() => { document.body.removeChild(container); window.removeEventListener('error', windowOnError); jest.restoreAllMocks(); }); describe('ReactDOMClient.createRoot', () => { it('logs errors during event handlers', async () => { spyOnDevAndProd(console, 'error'); function Foo() { return ( <button onClick={() => { throw Error('Boom'); }}> click me </button> ); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Foo />); }); await act(() => { container.firstChild.dispatchEvent( new MouseEvent('click', { bubbles: true, }), ); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported because we're in a browser click event: expect.objectContaining({ message: 'Boom', }), ], [ // This one is jsdom-only. Real browser deduplicates it. // (In DEV, we have a nested event due to guarded callback.) expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported because we're in a browser click event: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // This one is jsdom-only. Real browser deduplicates it. // (In DEV, we have a nested event due to guarded callback.) expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], ]); } else { expect(windowOnError.mock.calls).toEqual([ [ // Reported because we're in a browser click event: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported because we're in a browser click event: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { root.render(<NoError />); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([]); } }); it('logs render errors without an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { throw Error('Boom'); } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render(<Foo />); await waitForThrow('Boom'); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], [ // This is only duplicated with createRoot // because it retries once with a sync render. expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // This is only duplicated with createRoot // because it retries once with a sync render. expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { root.render(<NoError />); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([]); } }); it('logs render errors with an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { throw Error('Boom'); } const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <ErrorBoundary> <Foo /> </ErrorBoundary>, ); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], [ // This is only duplicated with createRoot // because it retries once with a sync render. expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported by jsdom due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // This is only duplicated with createRoot // because it retries once with a sync render. expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { root.render(<NoError />); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([]); } }); it('logs layout effect errors without an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useLayoutEffect(() => { throw Error('Boom'); }, []); return null; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render(<Foo />); await waitForThrow('Boom'); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { root.render(<NoError />); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([]); } }); it('logs layout effect errors with an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useLayoutEffect(() => { throw Error('Boom'); }, []); return null; } const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <ErrorBoundary> <Foo /> </ErrorBoundary>, ); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported by jsdom due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { root.render(<NoError />); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([]); } }); it('logs passive effect errors without an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useEffect(() => { throw Error('Boom'); }, []); return null; } const root = ReactDOMClient.createRoot(container); await act(async () => { root.render(<Foo />); await waitForThrow('Boom'); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { root.render(<NoError />); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([]); } }); it('logs passive effect errors with an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useEffect(() => { throw Error('Boom'); }, []); return null; } const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <ErrorBoundary> <Foo /> </ErrorBoundary>, ); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported by jsdom due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { root.render(<NoError />); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([]); } }); }); describe('ReactDOM.render', () => { it('logs errors during event handlers', async () => { spyOnDevAndProd(console, 'error'); function Foo() { return ( <button onClick={() => { throw Error('Boom'); }}> click me </button> ); } await act(() => { ReactDOM.render(<Foo />, container); }); await act(() => { container.firstChild.dispatchEvent( new MouseEvent('click', { bubbles: true, }), ); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported because we're in a browser click event: expect.objectContaining({ message: 'Boom', }), ], [ // This one is jsdom-only. Real browser deduplicates it. // (In DEV, we have a nested event due to guarded callback.) expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], [ // Reported because we're in a browser click event: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // This one is jsdom-only. Real browser deduplicates it. // (In DEV, we have a nested event due to guarded callback.) expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], ]); } else { expect(windowOnError.mock.calls).toEqual([ [ // Reported because we're in a browser click event: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [ // Reported because we're in a browser click event: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { ReactDOM.render(<NoError />, container); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], ]); } }); it('logs render errors without an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { throw Error('Boom'); } expect(() => { ReactDOM.render(<Foo />, container); }).toThrow('Boom'); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], [ // Reported due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { ReactDOM.render(<NoError />, container); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], ]); } }); it('logs render errors with an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { throw Error('Boom'); } await act(() => { ReactDOM.render( <ErrorBoundary> <Foo /> </ErrorBoundary>, container, ); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], [ // Reported by jsdom due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { ReactDOM.render(<NoError />, container); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], ]); } }); it('logs layout effect errors without an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useLayoutEffect(() => { throw Error('Boom'); }, []); return null; } expect(() => { ReactDOM.render(<Foo />, container); }).toThrow('Boom'); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], [ // Reported due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { ReactDOM.render(<NoError />, container); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], ]); } }); it('logs layout effect errors with an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useLayoutEffect(() => { throw Error('Boom'); }, []); return null; } await act(() => { ReactDOM.render( <ErrorBoundary> <Foo /> </ErrorBoundary>, container, ); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], [ // Reported by jsdom due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { ReactDOM.render(<NoError />, container); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], ]); } }); it('logs passive effect errors without an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useEffect(() => { throw Error('Boom'); }, []); return null; } await act(async () => { ReactDOM.render(<Foo />, container); await waitForThrow('Boom'); }); if (__DEV__) { expect(windowOnError.mock.calls).toEqual([ [ // Reported due to guarded callback: expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], [ // Reported due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { ReactDOM.render(<NoError />, container); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], ]); } }); it('logs passive effect errors with an error boundary', async () => { spyOnDevAndProd(console, 'error'); function Foo() { React.useEffect(() => { throw Error('Boom'); }, []); return null; } await act(() => { ReactDOM.render( <ErrorBoundary> <Foo /> </ErrorBoundary>, container, ); }); if (__DEV__) { // Reported due to guarded callback: expect(windowOnError.mock.calls).toEqual([ [ expect.objectContaining({ message: 'Boom', }), ], ]); expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], [ // Reported by jsdom due to the guarded callback: expect.objectContaining({ detail: expect.objectContaining({ message: 'Boom', }), type: 'unhandled exception', }), ], [ // Addendum by React: expect.stringContaining( 'The above error occurred in the <Foo> component', ), ], ]); } else { // The top-level error was caught with try/catch, and there's no guarded callback, // so in production we don't see an error event. expect(windowOnError.mock.calls).toEqual([]); expect(console.error.mock.calls).toEqual([ [ // Reported by React with no extra message: expect.objectContaining({ message: 'Boom', }), ], ]); } // Check next render doesn't throw. windowOnError.mockReset(); console.error.mockReset(); await act(() => { ReactDOM.render(<NoError />, container); }); expect(container.textContent).toBe('OK'); expect(windowOnError.mock.calls).toEqual([]); if (__DEV__) { expect(console.error.mock.calls).toEqual([ [expect.stringContaining('ReactDOM.render is no longer supported')], ]); } }); }); });
27.913462
90
0.493953
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // This file is only used for tests. // It lazily loads the implementation so that we get the correct set of host configs. import ReactVersion from 'shared/ReactVersion'; export {ReactVersion as version}; export function renderToString() { return require('./src/server/ReactDOMLegacyServerNode').renderToString.apply( this, arguments, ); } export function renderToStaticMarkup() { return require('./src/server/ReactDOMLegacyServerNode').renderToStaticMarkup.apply( this, arguments, ); } export function renderToNodeStream() { return require('./src/server/ReactDOMLegacyServerNode').renderToNodeStream.apply( this, arguments, ); } export function renderToStaticNodeStream() { return require('./src/server/ReactDOMLegacyServerNode').renderToStaticNodeStream.apply( this, arguments, ); } export function renderToPipeableStream() { return require('./src/server/react-dom-server.node').renderToPipeableStream.apply( this, arguments, ); } export function resumeToPipeableStream() { return require('./src/server/react-dom-server.node').resumeToPipeableStream.apply( this, arguments, ); }
24.961538
89
0.73536
PenetrationTestingScripts
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-debug-tools.production.min.js'); } else { module.exports = require('./cjs/react-debug-tools.development.js'); }
25.875
72
0.682243
owtf
import PropTypes from 'prop-types'; const React = window.React; const propTypes = { children: PropTypes.node.isRequired, }; class Fixture extends React.Component { render() { const {children} = this.props; return <div className="test-fixture">{children}</div>; } } Fixture.propTypes = propTypes; export default Fixture;
16.894737
58
0.707965
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 */ // This file is used as temporary storage for modules generated in Flight tests. let moduleIdx = 0; const modules: Map<string, Function> = new Map(); // This simulates what the compiler will do when it replaces render functions with server blocks. export function saveModule(render: Function): string { const idx = '' + moduleIdx++; modules.set(idx, render); return idx; } export function readModule(idx: string): Function { return modules.get(idx); }
26.791667
97
0.720721
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. * * @flow */ import * as React from 'react'; import LargeSubtree from './LargeSubtree'; export default function Home(): React.Node { return ( <div> <LargeSubtree /> </div> ); }
18.6
66
0.657289
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const React = require('react'); const ReactDOM = require('react-dom'); describe('ReactMount', () => { it('should destroy a react root upon request', () => { const mainContainerDiv = document.createElement('div'); document.body.appendChild(mainContainerDiv); const instanceOne = <div className="firstReactDiv" />; const firstRootDiv = document.createElement('div'); mainContainerDiv.appendChild(firstRootDiv); ReactDOM.render(instanceOne, firstRootDiv); const instanceTwo = <div className="secondReactDiv" />; const secondRootDiv = document.createElement('div'); mainContainerDiv.appendChild(secondRootDiv); ReactDOM.render(instanceTwo, secondRootDiv); // Test that two react roots are rendered in isolation expect(firstRootDiv.firstChild.className).toBe('firstReactDiv'); expect(secondRootDiv.firstChild.className).toBe('secondReactDiv'); // Test that after unmounting each, they are no longer in the document. ReactDOM.unmountComponentAtNode(firstRootDiv); expect(firstRootDiv.firstChild).toBeNull(); ReactDOM.unmountComponentAtNode(secondRootDiv); expect(secondRootDiv.firstChild).toBeNull(); }); it('should warn when unmounting a non-container root node', () => { const mainContainerDiv = document.createElement('div'); const component = ( <div> <div /> </div> ); ReactDOM.render(component, mainContainerDiv); // Test that unmounting at a root node gives a helpful warning const rootDiv = mainContainerDiv.firstChild; expect(() => ReactDOM.unmountComponentAtNode(rootDiv)).toErrorDev( "Warning: unmountComponentAtNode(): The node you're attempting to " + 'unmount was rendered by React and is not a top-level container. You ' + 'may have accidentally passed in a React root node instead of its ' + 'container.', {withoutStack: true}, ); }); it('should warn when unmounting a non-container, non-root node', () => { const mainContainerDiv = document.createElement('div'); const component = ( <div> <div> <div /> </div> </div> ); ReactDOM.render(component, mainContainerDiv); // Test that unmounting at a non-root node gives a different warning const nonRootDiv = mainContainerDiv.firstChild.firstChild; expect(() => ReactDOM.unmountComponentAtNode(nonRootDiv)).toErrorDev( "Warning: unmountComponentAtNode(): The node you're attempting to " + 'unmount was rendered by React and is not a top-level container. ' + 'Instead, have the parent component update its state and rerender in ' + 'order to remove this component.', {withoutStack: true}, ); }); });
34.011765
80
0.685378
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 function clamp(min: number, max: number, value: number): number { if (Number.isNaN(min) || Number.isNaN(max) || Number.isNaN(value)) { throw new Error( `Clamp was called with NaN. Args: min: ${min}, max: ${max}, value: ${value}.`, ); } return Math.min(max, Math.max(min, value)); }
27.555556
84
0.645224
owtf
const React = global.React; const ReactDOM = global.ReactDOM; class Counter extends React.unstable_AsyncComponent { state = {counter: 0}; onCommit() { setImmediate(() => { this.setState(state => ({ counter: state.counter + 1, })); }); } componentDidMount() { this.onCommit(); } componentDidUpdate() { this.onCommit(); } render() { return <h1>{this.state.counter}</h1>; } } const interval = 200; function block() { const endTime = performance.now() + interval; while (performance.now() < endTime) {} } setInterval(block, interval); // Should render a counter that increments approximately every second (the // expiration time of a low priority update). ReactDOM.render(<Counter />, document.getElementById('root')); block();
21.571429
74
0.652725
null
'use strict'; const JestReact = require('jest-react'); // TODO: Move to ReactInternalTestUtils function captureAssertion(fn) { // Trick to use a Jest matcher inside another Jest matcher. `fn` contains an // assertion; if it throws, we capture the error and return it, so the stack // trace presented to the user points to the original assertion in the // test file. try { fn(); } catch (error) { return { pass: false, message: () => error.message, }; } return {pass: true}; } function assertYieldsWereCleared(Scheduler, caller) { const actualYields = Scheduler.unstable_clearLog(); if (actualYields.length !== 0) { const error = Error( 'The event log is not empty. Call assertLog(...) first.' ); Error.captureStackTrace(error, caller); throw error; } } function toMatchRenderedOutput(ReactNoop, expectedJSX) { if (typeof ReactNoop.getChildrenAsJSX === 'function') { const Scheduler = ReactNoop._Scheduler; assertYieldsWereCleared(Scheduler, toMatchRenderedOutput); return captureAssertion(() => { expect(ReactNoop.getChildrenAsJSX()).toEqual(expectedJSX); }); } return JestReact.unstable_toMatchRenderedOutput(ReactNoop, expectedJSX); } module.exports = { toMatchRenderedOutput, };
25.8125
78
0.691291
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 {createEventTarget} from 'dom-event-testing-library'; let React; let ReactDOM; let ReactDOMClient; let ReactDOMServer; let ReactFeatureFlags; let Scheduler; let Suspense; let act; let assertLog; let waitForAll; let waitFor; let waitForPaint; let IdleEventPriority; let ContinuousEventPriority; function dispatchMouseHoverEvent(to, from) { if (!to) { to = null; } if (!from) { from = null; } if (from) { const mouseOutEvent = document.createEvent('MouseEvents'); mouseOutEvent.initMouseEvent( 'mouseout', true, true, window, 0, 50, 50, 50, 50, false, false, false, false, 0, to, ); from.dispatchEvent(mouseOutEvent); } if (to) { const mouseOverEvent = document.createEvent('MouseEvents'); mouseOverEvent.initMouseEvent( 'mouseover', true, true, window, 0, 50, 50, 50, 50, false, false, false, false, 0, from, ); to.dispatchEvent(mouseOverEvent); } } function dispatchClickEvent(target) { const mouseOutEvent = document.createEvent('MouseEvents'); mouseOutEvent.initMouseEvent( 'click', true, true, window, 0, 50, 50, 50, 50, false, false, false, false, 0, target, ); return target.dispatchEvent(mouseOutEvent); } // TODO: There's currently no React DOM API to opt into Idle priority updates, // and there's no native DOM event that maps to idle priority, so this is a // temporary workaround. Need something like ReactDOM.unstable_IdleUpdates. function TODO_scheduleIdleDOMSchedulerTask(fn) { ReactDOM.unstable_runWithPriority(IdleEventPriority, () => { const prevEvent = window.event; window.event = {type: 'message'}; try { fn(); } finally { window.event = prevEvent; } }); } function TODO_scheduleContinuousSchedulerTask(fn) { ReactDOM.unstable_runWithPriority(ContinuousEventPriority, () => { const prevEvent = window.event; window.event = {type: 'message'}; try { fn(); } finally { window.event = prevEvent; } }); } describe('ReactDOMServerSelectiveHydration', () => { beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.enableCreateEventHandleAPI = true; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMServer = require('react-dom/server'); act = require('internal-test-utils').act; Scheduler = require('scheduler'); Suspense = React.Suspense; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForPaint = InternalTestUtils.waitForPaint; IdleEventPriority = require('react-reconciler/constants').IdleEventPriority; ContinuousEventPriority = require('react-reconciler/constants').ContinuousEventPriority; }); it('hydrates the target boundary synchronously during a click', async () => { function Child({text}) { Scheduler.log(text); return ( <span onClick={e => { e.preventDefault(); Scheduler.log('Clicked ' + text); }}> {text} </span> ); } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const span = container.getElementsByTagName('span')[1]; ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // This should synchronously hydrate the root App and the second suspense // boundary. const result = dispatchClickEvent(span); // The event should have been canceled because we called preventDefault. expect(result).toBe(false); // We rendered App, B and then invoked the event without rendering A. assertLog(['App', 'B', 'Clicked B']); // After continuing the scheduler, we finally hydrate A. await waitForAll(['A']); document.body.removeChild(container); }); it('hydrates at higher pri if sync did not work first time', async () => { let suspend = false; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); function Child({text}) { if ((text === 'A' || text === 'D') && suspend) { throw promise; } Scheduler.log(text); return ( <span onClick={e => { e.preventDefault(); Scheduler.log('Clicked ' + text); }}> {text} </span> ); } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> <Suspense fallback="Loading..."> <Child text="C" /> </Suspense> <Suspense fallback="Loading..."> <Child text="D" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C', 'D']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const spanD = container.getElementsByTagName('span')[3]; suspend = true; // A and D will be suspended. We'll click on D which should take // priority, after we unsuspend. ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // This click target cannot be hydrated yet because it's suspended. await act(() => { const result = dispatchClickEvent(spanD); expect(result).toBe(true); }); assertLog([ 'App', // Continuing rendering will render B next. 'B', 'C', ]); await act(async () => { suspend = false; resolve(); await promise; }); assertLog(['D', 'A']); document.body.removeChild(container); }); it('hydrates at higher pri for secondary discrete events', async () => { let suspend = false; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); function Child({text}) { if ((text === 'A' || text === 'D') && suspend) { throw promise; } Scheduler.log(text); return ( <span onClick={e => { e.preventDefault(); Scheduler.log('Clicked ' + text); }}> {text} </span> ); } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> <Suspense fallback="Loading..."> <Child text="C" /> </Suspense> <Suspense fallback="Loading..."> <Child text="D" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C', 'D']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const spanA = container.getElementsByTagName('span')[0]; const spanC = container.getElementsByTagName('span')[2]; const spanD = container.getElementsByTagName('span')[3]; suspend = true; // A and D will be suspended. We'll click on D which should take // priority, after we unsuspend. ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // This click target cannot be hydrated yet because the first is Suspended. dispatchClickEvent(spanA); dispatchClickEvent(spanC); dispatchClickEvent(spanD); assertLog(['App', 'C', 'Clicked C']); await act(async () => { suspend = false; resolve(); await promise; }); assertLog([ 'A', 'D', // B should render last since it wasn't clicked. 'B', ]); document.body.removeChild(container); }); // @gate www it('hydrates the target boundary synchronously during a click (createEventHandle)', async () => { const setClick = ReactDOM.unstable_createEventHandle('click'); let isServerRendering = true; function Child({text}) { const ref = React.useRef(null); Scheduler.log(text); if (!isServerRendering) { React.useLayoutEffect(() => { return setClick(ref.current, () => { Scheduler.log('Clicked ' + text); }); }); } return <span ref={ref}>{text}</span>; } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; isServerRendering = false; ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); const span = container.getElementsByTagName('span')[1]; const target = createEventTarget(span); // This should synchronously hydrate the root App and the second suspense // boundary. target.virtualclick(); // We rendered App, B and then invoked the event without rendering A. assertLog(['App', 'B', 'Clicked B']); // After continuing the scheduler, we finally hydrate A. await waitForAll(['A']); document.body.removeChild(container); }); // @gate www it('hydrates at higher pri if sync did not work first time (createEventHandle)', async () => { let suspend = false; let isServerRendering = true; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); const setClick = ReactDOM.unstable_createEventHandle('click'); function Child({text}) { const ref = React.useRef(null); if ((text === 'A' || text === 'D') && suspend) { throw promise; } Scheduler.log(text); if (!isServerRendering) { React.useLayoutEffect(() => { return setClick(ref.current, () => { Scheduler.log('Clicked ' + text); }); }); } return <span ref={ref}>{text}</span>; } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> <Suspense fallback="Loading..."> <Child text="C" /> </Suspense> <Suspense fallback="Loading..."> <Child text="D" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C', 'D']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const spanD = container.getElementsByTagName('span')[3]; suspend = true; isServerRendering = false; // A and D will be suspended. We'll click on D which should take // priority, after we unsuspend. ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // Continuing rendering will render B next. await act(() => { const target = createEventTarget(spanD); target.virtualclick(); }); assertLog(['App', 'B', 'C']); // After the click, we should prioritize D and the Click first, // and only after that render A and C. await act(async () => { suspend = false; resolve(); await promise; }); // no replay assertLog(['D', 'A']); document.body.removeChild(container); }); // @gate www it('hydrates at higher pri for secondary discrete events (createEventHandle)', async () => { const setClick = ReactDOM.unstable_createEventHandle('click'); let suspend = false; let isServerRendering = true; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); function Child({text}) { const ref = React.useRef(null); if ((text === 'A' || text === 'D') && suspend) { throw promise; } Scheduler.log(text); if (!isServerRendering) { React.useLayoutEffect(() => { return setClick(ref.current, () => { Scheduler.log('Clicked ' + text); }); }); } return <span ref={ref}>{text}</span>; } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> <Suspense fallback="Loading..."> <Child text="C" /> </Suspense> <Suspense fallback="Loading..."> <Child text="D" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C', 'D']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const spanA = container.getElementsByTagName('span')[0]; const spanC = container.getElementsByTagName('span')[2]; const spanD = container.getElementsByTagName('span')[3]; suspend = true; isServerRendering = false; // A and D will be suspended. We'll click on D which should take // priority, after we unsuspend. ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // This click target cannot be hydrated yet because the first is Suspended. createEventTarget(spanA).virtualclick(); createEventTarget(spanC).virtualclick(); createEventTarget(spanD).virtualclick(); assertLog(['App', 'C', 'Clicked C']); await act(async () => { suspend = false; resolve(); await promise; }); assertLog([ 'A', 'D', // B should render last since it wasn't clicked. 'B', ]); document.body.removeChild(container); }); it('hydrates the hovered targets as higher priority for continuous events', async () => { let suspend = false; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); function Child({text}) { if ((text === 'A' || text === 'D') && suspend) { throw promise; } Scheduler.log(text); return ( <span onClick={e => { e.preventDefault(); Scheduler.log('Clicked ' + text); }} onMouseEnter={e => { e.preventDefault(); Scheduler.log('Hover ' + text); }}> {text} </span> ); } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> <Suspense fallback="Loading..."> <Child text="C" /> </Suspense> <Suspense fallback="Loading..."> <Child text="D" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C', 'D']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const spanB = container.getElementsByTagName('span')[1]; const spanC = container.getElementsByTagName('span')[2]; const spanD = container.getElementsByTagName('span')[3]; suspend = true; // A and D will be suspended. We'll click on D which should take // priority, after we unsuspend. ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); await act(() => { // Click D dispatchMouseHoverEvent(spanD, null); dispatchClickEvent(spanD); // Hover over B and then C. dispatchMouseHoverEvent(spanB, spanD); dispatchMouseHoverEvent(spanC, spanB); assertLog(['App']); suspend = false; resolve(); }); // We should prioritize hydrating D first because we clicked it. // but event isnt replayed assertLog([ 'D', 'B', // Ideally this should be later. 'C', 'Hover C', 'A', ]); document.body.removeChild(container); }); it('replays capture phase for continuous events and respects stopPropagation', async () => { let suspend = false; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); function Child({text}) { if ((text === 'A' || text === 'D') && suspend) { throw promise; } Scheduler.log(text); return ( <span id={text} onClickCapture={e => { e.preventDefault(); Scheduler.log('Capture Clicked ' + text); }} onClick={e => { e.preventDefault(); Scheduler.log('Clicked ' + text); }} onMouseEnter={e => { e.preventDefault(); Scheduler.log('Mouse Enter ' + text); }} onMouseOut={e => { e.preventDefault(); Scheduler.log('Mouse Out ' + text); }} onMouseOutCapture={e => { e.preventDefault(); e.stopPropagation(); Scheduler.log('Mouse Out Capture ' + text); }} onMouseOverCapture={e => { e.preventDefault(); e.stopPropagation(); Scheduler.log('Mouse Over Capture ' + text); }} onMouseOver={e => { e.preventDefault(); Scheduler.log('Mouse Over ' + text); }}> <div onMouseOverCapture={e => { e.preventDefault(); Scheduler.log('Mouse Over Capture Inner ' + text); }}> {text} </div> </span> ); } function App() { Scheduler.log('App'); return ( <div onClickCapture={e => { e.preventDefault(); Scheduler.log('Capture Clicked Parent'); }} onMouseOverCapture={e => { Scheduler.log('Mouse Over Capture Parent'); }}> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> <Suspense fallback="Loading..."> <Child text="C" /> </Suspense> <Suspense fallback="Loading..."> <Child text="D" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C', 'D']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const spanB = document.getElementById('B').firstChild; const spanC = document.getElementById('C').firstChild; const spanD = document.getElementById('D').firstChild; suspend = true; // A and D will be suspended. We'll click on D which should take // priority, after we unsuspend. ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); await act(async () => { // Click D dispatchMouseHoverEvent(spanD, null); dispatchClickEvent(spanD); // Hover over B and then C. dispatchMouseHoverEvent(spanB, spanD); dispatchMouseHoverEvent(spanC, spanB); assertLog(['App']); suspend = false; resolve(); }); // We should prioritize hydrating D first because we clicked it. // but event isnt replayed assertLog([ 'D', 'B', // Ideally this should be later. 'C', // Mouse out events aren't replayed // 'Mouse Out Capture B', // 'Mouse Out B', 'Mouse Over Capture Parent', 'Mouse Over Capture C', // Stop propagation stops these // 'Mouse Over Capture Inner C', // 'Mouse Over C', 'A', ]); // This test shows existing quirk where stopPropagation on mouseout // prevents mouseEnter from firing dispatchMouseHoverEvent(spanC, spanB); assertLog([ 'Mouse Out Capture B', // stopPropagation stops these // 'Mouse Out B', // 'Mouse Enter C', 'Mouse Over Capture Parent', 'Mouse Over Capture C', // Stop propagation stops these // 'Mouse Over Capture Inner C', // 'Mouse Over C', ]); document.body.removeChild(container); }); describe('can handle replaying events as part of multiple instances of React', () => { let resolveInner; let resolveOuter; let innerPromise; let outerPromise; let OuterScheduler; let InnerScheduler; let innerDiv; let OuterTestUtils; let InnerTestUtils; beforeEach(async () => { document.body.innerHTML = ''; jest.resetModules(); let OuterReactDOMClient; let InnerReactDOMClient; jest.isolateModules(() => { OuterReactDOMClient = require('react-dom/client'); OuterScheduler = require('scheduler'); OuterTestUtils = require('internal-test-utils'); }); jest.isolateModules(() => { InnerReactDOMClient = require('react-dom/client'); InnerScheduler = require('scheduler'); InnerTestUtils = require('internal-test-utils'); }); expect(OuterReactDOMClient).not.toBe(InnerReactDOMClient); expect(OuterScheduler).not.toBe(InnerScheduler); const outerContainer = document.createElement('div'); const innerContainer = document.createElement('div'); let suspendOuter = false; outerPromise = new Promise(res => { resolveOuter = () => { suspendOuter = false; res(); }; }); function Outer() { if (suspendOuter) { OuterScheduler.log('Suspend Outer'); throw outerPromise; } OuterScheduler.log('Outer'); const innerRoot = outerContainer.querySelector('#inner-root'); return ( <div id="inner-root" onMouseEnter={() => { Scheduler.log('Outer Mouse Enter'); }} dangerouslySetInnerHTML={{ __html: innerRoot ? innerRoot.innerHTML : '', }} /> ); } const OuterApp = () => { return ( <Suspense fallback={<div>Loading</div>}> <Outer /> </Suspense> ); }; let suspendInner = false; innerPromise = new Promise(res => { resolveInner = () => { suspendInner = false; res(); }; }); function Inner() { if (suspendInner) { InnerScheduler.log('Suspend Inner'); throw innerPromise; } InnerScheduler.log('Inner'); return ( <div id="inner" onMouseEnter={() => { Scheduler.log('Inner Mouse Enter'); }} /> ); } const InnerApp = () => { return ( <Suspense fallback={<div>Loading</div>}> <Inner /> </Suspense> ); }; document.body.appendChild(outerContainer); const outerHTML = ReactDOMServer.renderToString(<OuterApp />); outerContainer.innerHTML = outerHTML; const innerWrapper = document.querySelector('#inner-root'); innerWrapper.appendChild(innerContainer); const innerHTML = ReactDOMServer.renderToString(<InnerApp />); innerContainer.innerHTML = innerHTML; OuterTestUtils.assertLog(['Outer']); InnerTestUtils.assertLog(['Inner']); suspendOuter = true; suspendInner = true; await OuterTestUtils.act(() => OuterReactDOMClient.hydrateRoot(outerContainer, <OuterApp />), ); await InnerTestUtils.act(() => InnerReactDOMClient.hydrateRoot(innerContainer, <InnerApp />), ); OuterTestUtils.assertLog(['Suspend Outer']); InnerTestUtils.assertLog(['Suspend Inner']); innerDiv = document.querySelector('#inner'); dispatchClickEvent(innerDiv); await act(() => { jest.runAllTimers(); Scheduler.unstable_flushAllWithoutAsserting(); OuterScheduler.unstable_flushAllWithoutAsserting(); InnerScheduler.unstable_flushAllWithoutAsserting(); }); OuterTestUtils.assertLog(['Suspend Outer']); // InnerApp doesn't see the event because OuterApp calls stopPropagation in // capture phase since the event is blocked on suspended component InnerTestUtils.assertLog([]); assertLog([]); }); afterEach(async () => { document.body.innerHTML = ''; }); it('Inner hydrates first then Outer', async () => { dispatchMouseHoverEvent(innerDiv); await InnerTestUtils.act(async () => { await OuterTestUtils.act(() => { resolveInner(); }); }); OuterTestUtils.assertLog(['Suspend Outer']); // Inner App renders because it is unblocked InnerTestUtils.assertLog(['Inner']); // No event is replayed yet assertLog([]); dispatchMouseHoverEvent(innerDiv); OuterTestUtils.assertLog([]); InnerTestUtils.assertLog([]); // No event is replayed yet assertLog([]); await InnerTestUtils.act(async () => { await OuterTestUtils.act(() => { resolveOuter(); // Nothing happens to inner app yet. // Its blocked on the outer app replaying the event InnerTestUtils.assertLog([]); // Outer hydrates and schedules Replay OuterTestUtils.waitFor(['Outer']); // No event is replayed yet assertLog([]); }); }); // fire scheduled Replay // First Inner Mouse Enter fires then Outer Mouse Enter assertLog(['Inner Mouse Enter', 'Outer Mouse Enter']); }); it('Outer hydrates first then Inner', async () => { dispatchMouseHoverEvent(innerDiv); await act(async () => { resolveOuter(); await outerPromise; Scheduler.unstable_flushAllWithoutAsserting(); OuterScheduler.unstable_flushAllWithoutAsserting(); InnerScheduler.unstable_flushAllWithoutAsserting(); }); // Outer resolves and scheduled replay OuterTestUtils.assertLog(['Outer']); // Inner App is still blocked InnerTestUtils.assertLog([]); // Replay outer event await act(() => { Scheduler.unstable_flushAllWithoutAsserting(); OuterScheduler.unstable_flushAllWithoutAsserting(); InnerScheduler.unstable_flushAllWithoutAsserting(); }); // Inner is still blocked so when Outer replays the event in capture phase // inner ends up caling stopPropagation assertLog([]); OuterTestUtils.assertLog([]); InnerTestUtils.assertLog(['Suspend Inner']); dispatchMouseHoverEvent(innerDiv); OuterTestUtils.assertLog([]); InnerTestUtils.assertLog([]); assertLog([]); await act(async () => { resolveInner(); await innerPromise; Scheduler.unstable_flushAllWithoutAsserting(); OuterScheduler.unstable_flushAllWithoutAsserting(); InnerScheduler.unstable_flushAllWithoutAsserting(); }); // Inner hydrates InnerTestUtils.assertLog(['Inner']); // Outer was hydrated earlier OuterTestUtils.assertLog([]); await act(() => { Scheduler.unstable_flushAllWithoutAsserting(); OuterScheduler.unstable_flushAllWithoutAsserting(); InnerScheduler.unstable_flushAllWithoutAsserting(); }); // First Inner Mouse Enter fires then Outer Mouse Enter assertLog(['Inner Mouse Enter', 'Outer Mouse Enter']); }); }); it('replays event with null target when tree is dismounted', async () => { let suspend = false; let resolve; const promise = new Promise(resolvePromise => { resolve = () => { suspend = false; resolvePromise(); }; }); function Child() { if (suspend) { throw promise; } Scheduler.log('Child'); return ( <div onMouseOver={() => { Scheduler.log('on mouse over'); }}> Child </div> ); } function App() { return ( <Suspense> <Child /> </Suspense> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['Child']); const container = document.createElement('div'); document.body.appendChild(container); container.innerHTML = finalHTML; suspend = true; ReactDOMClient.hydrateRoot(container, <App />); const childDiv = container.firstElementChild; await act(async () => { dispatchMouseHoverEvent(childDiv); // Not hydrated so event is saved for replay and stopPropagation is called assertLog([]); resolve(); await waitFor(['Child']); ReactDOM.flushSync(() => { container.removeChild(childDiv); const container2 = document.createElement('div'); container2.addEventListener('mouseover', () => { Scheduler.log('container2 mouse over'); }); container2.appendChild(childDiv); }); }); // Even though the tree is remove the event is still dispatched with native event handler // on the container firing. assertLog(['container2 mouse over']); document.body.removeChild(container); }); it('hydrates the last target path first for continuous events', async () => { let suspend = false; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); function Child({text}) { if ((text === 'A' || text === 'D') && suspend) { throw promise; } Scheduler.log(text); return ( <span onMouseEnter={e => { e.preventDefault(); Scheduler.log('Hover ' + text); }}> {text} </span> ); } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <div> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> </div> <Child text="C" /> </Suspense> <Suspense fallback="Loading..."> <Child text="D" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C', 'D']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const spanB = container.getElementsByTagName('span')[1]; const spanC = container.getElementsByTagName('span')[2]; const spanD = container.getElementsByTagName('span')[3]; suspend = true; // A and D will be suspended. We'll click on D which should take // priority, after we unsuspend. ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // Hover over B and then C. dispatchMouseHoverEvent(spanB, spanD); dispatchMouseHoverEvent(spanC, spanB); await act(async () => { suspend = false; resolve(); await promise; }); // We should prioritize hydrating D first because we clicked it. // Next we should hydrate C since that's the current hover target. // Next it doesn't matter if we hydrate A or B first but as an // implementation detail we're currently hydrating B first since // we at one point hovered over it and we never deprioritized it. assertLog(['App', 'C', 'Hover C', 'A', 'B', 'D']); document.body.removeChild(container); }); it('hydrates the last explicitly hydrated target at higher priority', async () => { function Child({text}) { Scheduler.log(text); return <span>{text}</span>; } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> <Suspense fallback="Loading..."> <Child text="C" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B', 'C']); const container = document.createElement('div'); container.innerHTML = finalHTML; const spanB = container.getElementsByTagName('span')[1]; const spanC = container.getElementsByTagName('span')[2]; const root = ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // Increase priority of B and then C. root.unstable_scheduleHydration(spanB); root.unstable_scheduleHydration(spanC); // We should prioritize hydrating C first because the last added // gets highest priority followed by the next added. await waitForAll(['App', 'C', 'B', 'A']); }); // @gate experimental || www it('hydrates before an update even if hydration moves away from it', async () => { function Child({text}) { Scheduler.log(text); return <span>{text}</span>; } const ChildWithBoundary = React.memo(function ({text}) { return ( <Suspense fallback="Loading..."> <Child text={text} /> <Child text={text.toLowerCase()} /> </Suspense> ); }); function App({a}) { Scheduler.log('App'); React.useEffect(() => { Scheduler.log('Commit'); }); return ( <div> <ChildWithBoundary text={a} /> <ChildWithBoundary text="B" /> <ChildWithBoundary text="C" /> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App a="A" />); assertLog(['App', 'A', 'a', 'B', 'b', 'C', 'c']); const container = document.createElement('div'); container.innerHTML = finalHTML; // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); const spanA = container.getElementsByTagName('span')[0]; const spanB = container.getElementsByTagName('span')[2]; const spanC = container.getElementsByTagName('span')[4]; await act(async () => { const root = ReactDOMClient.hydrateRoot(container, <App a="A" />); // Hydrate the shell. await waitFor(['App', 'Commit']); // Render an update at Idle priority that needs to update A. TODO_scheduleIdleDOMSchedulerTask(() => { root.render(<App a="AA" />); }); // Start rendering. This will force the first boundary to hydrate // by scheduling it at one higher pri than Idle. await waitFor([ 'App', // Start hydrating A 'A', ]); // Hover over A which (could) schedule at one higher pri than Idle. dispatchMouseHoverEvent(spanA, null); // Before, we're done we now switch to hover over B. // This is meant to test that this doesn't cause us to forget that // we still have to hydrate A. The first boundary. // This also tests that we don't do the -1 down-prioritization of // continuous hover events because that would decrease its priority // to Idle. dispatchMouseHoverEvent(spanB, spanA); // Also click C to prioritize that even higher which resets the // priority levels. dispatchClickEvent(spanC); assertLog([ // Hydrate C first since we clicked it. 'C', 'c', ]); await waitForAll([ // Finish hydration of A since we forced it to hydrate. 'A', 'a', // Also, hydrate B since we hovered over it. // It's not important which one comes first. A or B. // As long as they both happen before the Idle update. 'B', 'b', // Begin the Idle update again. 'App', 'AA', 'aa', 'Commit', ]); }); const spanA2 = container.getElementsByTagName('span')[0]; // This is supposed to have been hydrated, not replaced. expect(spanA).toBe(spanA2); document.body.removeChild(container); }); it('fires capture event handlers and native events if content is hydratable during discrete event', async () => { spyOnDev(console, 'error'); function Child({text}) { Scheduler.log(text); const ref = React.useRef(); React.useLayoutEffect(() => { if (!ref.current) { return; } ref.current.onclick = () => { Scheduler.log('Native Click ' + text); }; }, [text]); return ( <span ref={ref} onClickCapture={() => { Scheduler.log('Capture Clicked ' + text); }} onClick={e => { Scheduler.log('Clicked ' + text); }}> {text} </span> ); } function App() { Scheduler.log('App'); return ( <div> <Suspense fallback="Loading..."> <Child text="A" /> </Suspense> <Suspense fallback="Loading..."> <Child text="B" /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A', 'B']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const span = container.getElementsByTagName('span')[1]; ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); // This should synchronously hydrate the root App and the second suspense // boundary. dispatchClickEvent(span); // We rendered App, B and then invoked the event without rendering A. assertLog(['App', 'B', 'Capture Clicked B', 'Native Click B', 'Clicked B']); // After continuing the scheduler, we finally hydrate A. await waitForAll(['A']); document.body.removeChild(container); }); it('does not propagate discrete event if it cannot be synchronously hydrated', async () => { let triggeredParent = false; let triggeredChild = false; let suspend = false; const promise = new Promise(() => {}); function Child() { if (suspend) { throw promise; } Scheduler.log('Child'); return ( <span onClickCapture={e => { e.stopPropagation(); triggeredChild = true; }}> Click me </span> ); } function App() { const onClick = () => { triggeredParent = true; }; Scheduler.log('App'); return ( <div ref={n => { if (n) n.onclick = onClick; }} onClick={onClick}> <Suspense fallback={null}> <Child /> </Suspense> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'Child']); const container = document.createElement('div'); document.body.appendChild(container); container.innerHTML = finalHTML; suspend = true; ReactDOMClient.hydrateRoot(container, <App />); // Nothing has been hydrated so far. assertLog([]); const span = container.getElementsByTagName('span')[0]; dispatchClickEvent(span); assertLog(['App']); dispatchClickEvent(span); expect(triggeredParent).toBe(false); expect(triggeredChild).toBe(false); }); it('can attempt sync hydration if suspended root is still concurrently rendering', async () => { let suspend = false; let resolve; const promise = new Promise(resolvePromise => (resolve = resolvePromise)); function Child({text}) { if (suspend) { throw promise; } Scheduler.log(text); return ( <span onClick={e => { e.preventDefault(); Scheduler.log('Clicked ' + text); }}> {text} </span> ); } function App() { Scheduler.log('App'); return ( <div> <Child text="A" /> </div> ); } const finalHTML = ReactDOMServer.renderToString(<App />); assertLog(['App', 'A']); const container = document.createElement('div'); // We need this to be in the document since we'll dispatch events on it. document.body.appendChild(container); container.innerHTML = finalHTML; const span = container.getElementsByTagName('span')[0]; // We suspend on the client. suspend = true; React.startTransition(() => { ReactDOMClient.hydrateRoot(container, <App />); }); await waitFor(['App']); // This should attempt to synchronously hydrate the root, then pause // because it still suspended const result = dispatchClickEvent(span); assertLog(['App']); // The event should not have been cancelled because we didn't hydrate. expect(result).toBe(true); // Finish loading the data await act(async () => { suspend = false; await resolve(); }); // The app should have successfully hydrated and rendered assertLog(['App', 'A']); document.body.removeChild(container); }); it('can force hydration in response to sync update', async () => { function Child({text}) { Scheduler.log(`Child ${text}`); return <span ref={ref => (spanRef = ref)}>{text}</span>; } function App({text}) { Scheduler.log(`App ${text}`); return ( <div> <Suspense fallback={null}> <Child text={text} /> </Suspense> </div> ); } let spanRef; const finalHTML = ReactDOMServer.renderToString(<App text="A" />); assertLog(['App A', 'Child A']); const container = document.createElement('div'); document.body.appendChild(container); container.innerHTML = finalHTML; const initialSpan = container.getElementsByTagName('span')[0]; const root = ReactDOMClient.hydrateRoot(container, <App text="A" />); await waitForPaint(['App A']); await act(() => { ReactDOM.flushSync(() => { root.render(<App text="B" />); }); }); assertLog(['App B', 'Child A', 'App B', 'Child B']); expect(initialSpan).toBe(spanRef); }); // @gate experimental || www it('can force hydration in response to continuous update', async () => { function Child({text}) { Scheduler.log(`Child ${text}`); return <span ref={ref => (spanRef = ref)}>{text}</span>; } function App({text}) { Scheduler.log(`App ${text}`); return ( <div> <Suspense fallback={null}> <Child text={text} /> </Suspense> </div> ); } let spanRef; const finalHTML = ReactDOMServer.renderToString(<App text="A" />); assertLog(['App A', 'Child A']); const container = document.createElement('div'); document.body.appendChild(container); container.innerHTML = finalHTML; const initialSpan = container.getElementsByTagName('span')[0]; const root = ReactDOMClient.hydrateRoot(container, <App text="A" />); await waitForPaint(['App A']); await act(() => { TODO_scheduleContinuousSchedulerTask(() => { root.render(<App text="B" />); }); }); assertLog(['App B', 'Child A', 'App B', 'Child B']); expect(initialSpan).toBe(spanRef); }); it('can force hydration in response to default update', async () => { function Child({text}) { Scheduler.log(`Child ${text}`); return <span ref={ref => (spanRef = ref)}>{text}</span>; } function App({text}) { Scheduler.log(`App ${text}`); return ( <div> <Suspense fallback={null}> <Child text={text} /> </Suspense> </div> ); } let spanRef; const finalHTML = ReactDOMServer.renderToString(<App text="A" />); assertLog(['App A', 'Child A']); const container = document.createElement('div'); document.body.appendChild(container); container.innerHTML = finalHTML; const initialSpan = container.getElementsByTagName('span')[0]; const root = ReactDOMClient.hydrateRoot(container, <App text="A" />); await waitForPaint(['App A']); await act(() => { root.render(<App text="B" />); }); assertLog(['App B', 'Child A', 'App B', 'Child B']); expect(initialSpan).toBe(spanRef); }); // @gate experimental || www it('regression test: can unwind context on selective hydration interruption', async () => { const Context = React.createContext('DefaultContext'); function ContextReader(props) { const value = React.useContext(Context); Scheduler.log(value); return null; } function Child({text}) { Scheduler.log(text); return <span>{text}</span>; } const ChildWithBoundary = React.memo(function ({text}) { return ( <Suspense fallback="Loading..."> <Child text={text} /> </Suspense> ); }); function App({a}) { Scheduler.log('App'); React.useEffect(() => { Scheduler.log('Commit'); }); return ( <> <Context.Provider value="SiblingContext"> <ChildWithBoundary text={a} /> </Context.Provider> <ContextReader /> </> ); } const finalHTML = ReactDOMServer.renderToString(<App a="A" />); assertLog(['App', 'A', 'DefaultContext']); const container = document.createElement('div'); container.innerHTML = finalHTML; document.body.appendChild(container); const spanA = container.getElementsByTagName('span')[0]; await act(async () => { const root = ReactDOMClient.hydrateRoot(container, <App a="A" />); await waitFor(['App', 'DefaultContext', 'Commit']); TODO_scheduleIdleDOMSchedulerTask(() => { root.render(<App a="AA" />); }); await waitFor(['App', 'A']); dispatchClickEvent(spanA); assertLog(['A']); await waitForAll(['App', 'AA', 'DefaultContext', 'Commit']); }); }); it('regression test: can unwind context on selective hydration interruption for sync updates', async () => { const Context = React.createContext('DefaultContext'); function ContextReader(props) { const value = React.useContext(Context); Scheduler.log(value); return null; } function Child({text}) { Scheduler.log(text); return <span>{text}</span>; } const ChildWithBoundary = React.memo(function ({text}) { return ( <Suspense fallback="Loading..."> <Child text={text} /> </Suspense> ); }); function App({a}) { Scheduler.log('App'); React.useEffect(() => { Scheduler.log('Commit'); }); return ( <> <Context.Provider value="SiblingContext"> <ChildWithBoundary text={a} /> </Context.Provider> <ContextReader /> </> ); } const finalHTML = ReactDOMServer.renderToString(<App a="A" />); assertLog(['App', 'A', 'DefaultContext']); const container = document.createElement('div'); container.innerHTML = finalHTML; await act(async () => { const root = ReactDOMClient.hydrateRoot(container, <App a="A" />); await waitFor(['App', 'DefaultContext', 'Commit']); ReactDOM.flushSync(() => { root.render(<App a="AA" />); }); assertLog(['App', 'A', 'App', 'AA', 'DefaultContext', 'Commit']); }); }); it('regression: selective hydration does not contribute to "maximum update limit" count', async () => { const outsideRef = React.createRef(null); const insideRef = React.createRef(null); function Child() { return ( <Suspense fallback="Loading..."> <div ref={insideRef} /> </Suspense> ); } let setIsMounted = false; function App() { const [isMounted, setState] = React.useState(false); setIsMounted = setState; const children = []; for (let i = 0; i < 100; i++) { children.push(<Child key={i} isMounted={isMounted} />); } return <div ref={outsideRef}>{children}</div>; } const finalHTML = ReactDOMServer.renderToString(<App />); const container = document.createElement('div'); container.innerHTML = finalHTML; await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); // Commit just the shell await waitForPaint([]); // Assert that the shell has hydrated, but not the children expect(outsideRef.current).not.toBe(null); expect(insideRef.current).toBe(null); // Update the shell synchronously. The update will flow into the children, // which haven't hydrated yet. This will trigger a cascade of commits // caused by selective hydration. However, since there's really only one // update, it should not be treated as an update loop. // NOTE: It's unfortunate that every sibling boundary is separately // committed in this case. We should be able to commit everything in a // render phase, which we could do if we had resumable context stacks. ReactDOM.flushSync(() => { setIsMounted(true); }); }); // Should have successfully hydrated with no errors. expect(insideRef.current).not.toBe(null); }); });
26.48404
115
0.574475
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 ProfilerStore from './ProfilerStore'; import { getCommitTree, invalidateCommitTrees, } from 'react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder'; import { getChartData as getFlamegraphChartData, invalidateChartData as invalidateFlamegraphChartData, } from 'react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder'; import { getChartData as getRankedChartData, invalidateChartData as invalidateRankedChartData, } from 'react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder'; import type {CommitTree} from 'react-devtools-shared/src/devtools/views/Profiler/types'; import type {ChartData as FlamegraphChartData} from 'react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder'; import type {ChartData as RankedChartData} from 'react-devtools-shared/src/devtools/views/Profiler/RankedChartBuilder'; export default class ProfilingCache { _fiberCommits: Map<number, Array<number>> = new Map(); _profilerStore: ProfilerStore; constructor(profilerStore: ProfilerStore) { this._profilerStore = profilerStore; } getCommitTree: ({commitIndex: number, rootID: number}) => CommitTree = ({ commitIndex, rootID, }) => getCommitTree({ commitIndex, profilerStore: this._profilerStore, rootID, }); getFiberCommits: ({fiberID: number, rootID: number}) => Array<number> = ({ fiberID, rootID, }) => { const cachedFiberCommits = this._fiberCommits.get(fiberID); if (cachedFiberCommits != null) { return cachedFiberCommits; } const fiberCommits = []; const dataForRoot = this._profilerStore.getDataForRoot(rootID); dataForRoot.commitData.forEach((commitDatum, commitIndex) => { if (commitDatum.fiberActualDurations.has(fiberID)) { fiberCommits.push(commitIndex); } }); this._fiberCommits.set(fiberID, fiberCommits); return fiberCommits; }; getFlamegraphChartData: ({ commitIndex: number, commitTree: CommitTree, rootID: number, }) => FlamegraphChartData = ({commitIndex, commitTree, rootID}) => getFlamegraphChartData({ commitIndex, commitTree, profilerStore: this._profilerStore, rootID, }); getRankedChartData: ({ commitIndex: number, commitTree: CommitTree, rootID: number, }) => RankedChartData = ({commitIndex, commitTree, rootID}) => getRankedChartData({ commitIndex, commitTree, profilerStore: this._profilerStore, rootID, }); invalidate() { this._fiberCommits.clear(); invalidateCommitTrees(); invalidateFlamegraphChartData(); invalidateRankedChartData(); } }
27.88
127
0.712504
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 {Fragment, useContext, useMemo} from 'react'; import {StoreContext} from 'react-devtools-shared/src/devtools/views/context'; import {useSubscription} from 'react-devtools-shared/src/devtools/views/hooks'; import {NativeStyleContext} from './context'; import LayoutViewer from './LayoutViewer'; import StyleEditor from './StyleEditor'; import {TreeStateContext} from '../TreeContext'; type Props = {}; export default function NativeStyleEditorWrapper(_: Props): React.Node { const store = useContext(StoreContext); const subscription = useMemo( () => ({ getCurrentValue: () => store.supportsNativeStyleEditor, subscribe: (callback: Function) => { store.addListener('supportsNativeStyleEditor', callback); return () => { store.removeListener('supportsNativeStyleEditor', callback); }; }, }), [store], ); const supportsNativeStyleEditor = useSubscription<boolean>(subscription); if (!supportsNativeStyleEditor) { return null; } return <NativeStyleEditor />; } function NativeStyleEditor(_: Props) { const {getStyleAndLayout} = useContext(NativeStyleContext); const {inspectedElementID} = useContext(TreeStateContext); if (inspectedElementID === null) { return null; } const maybeStyleAndLayout = getStyleAndLayout(inspectedElementID); if (maybeStyleAndLayout === null) { return null; } const {layout, style} = maybeStyleAndLayout; return ( <Fragment> {layout !== null && ( <LayoutViewer id={inspectedElementID} layout={layout} /> )} {style !== null && ( <StyleEditor id={inspectedElementID} style={style !== null ? style : {}} /> )} </Fragment> ); }
25.851351
79
0.667674
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'; /* eslint-disable no-for-of-loops/no-for-of-loops */ // Hi, if this is your first time editing/reading a Dangerfile, here's a summary: // It's a JS runtime which helps you provide continuous feedback inside GitHub. // // You can see the docs here: http://danger.systems/js/ // // If you want to test changes Danger, I'd recommend checking out an existing PR // and then running the `danger pr` command. // // You'll need a GitHub token, you can re-use this one: // // 0a7d5c3cad9a6dbec2d9 9a5222cf49062a4c1ef7 // // (Just remove the space) // // So, for example: // // `DANGER_GITHUB_API_TOKEN=[ENV_ABOVE] yarn danger pr https://github.com/facebook/react/pull/11865 const {markdown, danger, warn} = require('danger'); const {promisify} = require('util'); const glob = promisify(require('glob')); const gzipSize = require('gzip-size'); const {readFileSync, statSync} = require('fs'); const BASE_DIR = 'base-build'; const HEAD_DIR = 'build'; const CRITICAL_THRESHOLD = 0.02; const SIGNIFICANCE_THRESHOLD = 0.002; const CRITICAL_ARTIFACT_PATHS = new Set([ // We always report changes to these bundles, even if the change is // insignificant or non-existent. 'oss-stable/react-dom/cjs/react-dom.production.min.js', 'oss-experimental/react-dom/cjs/react-dom.production.min.js', 'facebook-www/ReactDOM-prod.classic.js', 'facebook-www/ReactDOM-prod.modern.js', ]); const kilobyteFormatter = new Intl.NumberFormat('en', { style: 'unit', unit: 'kilobyte', minimumFractionDigits: 2, maximumFractionDigits: 2, }); function kbs(bytes) { return kilobyteFormatter.format(bytes / 1000); } const percentFormatter = new Intl.NumberFormat('en', { style: 'percent', signDisplay: 'exceptZero', minimumFractionDigits: 2, maximumFractionDigits: 2, }); function change(decimal) { if (Number === Infinity) { return 'New file'; } if (decimal === -1) { return 'Deleted'; } if (decimal < 0.0001) { return '='; } return percentFormatter.format(decimal); } const header = ` | Name | +/- | Base | Current | +/- gzip | Base gzip | Current gzip | | ---- | --- | ---- | ------- | -------- | --------- | ------------ |`; function row(result, baseSha, headSha) { const diffViewUrl = `https://react-builds.vercel.app/commits/${headSha}/files/${result.path}?compare=${baseSha}`; const rowArr = [ `| [${result.path}](${diffViewUrl})`, `**${change(result.change)}**`, `${kbs(result.baseSize)}`, `${kbs(result.headSize)}`, `${change(result.changeGzip)}`, `${kbs(result.baseSizeGzip)}`, `${kbs(result.headSizeGzip)}`, ]; return rowArr.join(' | '); } (async function () { // Use git locally to grab the commit which represents the place // where the branches differ const upstreamRepo = danger.github.pr.base.repo.full_name; if (upstreamRepo !== 'facebook/react') { // Exit unless we're running in the main repo return; } let headSha; let baseSha; try { headSha = String(readFileSync(HEAD_DIR + '/COMMIT_SHA')).trim(); baseSha = String(readFileSync(BASE_DIR + '/COMMIT_SHA')).trim(); } catch { warn( "Failed to read build artifacts. It's possible a build configuration " + 'has changed upstream. Try pulling the latest changes from the ' + 'main branch.' ); return; } // Disable sizeBot in a Devtools Pull Request. Because that doesn't affect production bundle size. const commitFiles = [ ...danger.git.created_files, ...danger.git.deleted_files, ...danger.git.modified_files, ]; if ( commitFiles.every(filename => filename.includes('packages/react-devtools')) ) return; const resultsMap = new Map(); // Find all the head (current) artifacts paths. const headArtifactPaths = await glob('**/*.js', {cwd: 'build'}); for (const artifactPath of headArtifactPaths) { try { // This will throw if there's no matching base artifact const baseSize = statSync(BASE_DIR + '/' + artifactPath).size; const baseSizeGzip = gzipSize.fileSync(BASE_DIR + '/' + artifactPath); const headSize = statSync(HEAD_DIR + '/' + artifactPath).size; const headSizeGzip = gzipSize.fileSync(HEAD_DIR + '/' + artifactPath); resultsMap.set(artifactPath, { path: artifactPath, headSize, headSizeGzip, baseSize, baseSizeGzip, change: (headSize - baseSize) / baseSize, changeGzip: (headSizeGzip - baseSizeGzip) / baseSizeGzip, }); } catch { // There's no matching base artifact. This is a new file. const baseSize = 0; const baseSizeGzip = 0; const headSize = statSync(HEAD_DIR + '/' + artifactPath).size; const headSizeGzip = gzipSize.fileSync(HEAD_DIR + '/' + artifactPath); resultsMap.set(artifactPath, { path: artifactPath, headSize, headSizeGzip, baseSize, baseSizeGzip, change: Infinity, changeGzip: Infinity, }); } } // Check for base artifacts that were deleted in the head. const baseArtifactPaths = await glob('**/*.js', {cwd: 'base-build'}); for (const artifactPath of baseArtifactPaths) { if (!resultsMap.has(artifactPath)) { const baseSize = statSync(BASE_DIR + '/' + artifactPath).size; const baseSizeGzip = gzipSize.fileSync(BASE_DIR + '/' + artifactPath); const headSize = 0; const headSizeGzip = 0; resultsMap.set(artifactPath, { path: artifactPath, headSize, headSizeGzip, baseSize, baseSizeGzip, change: -1, changeGzip: -1, }); } } const results = Array.from(resultsMap.values()); results.sort((a, b) => b.change - a.change); let criticalResults = []; for (const artifactPath of CRITICAL_ARTIFACT_PATHS) { const result = resultsMap.get(artifactPath); if (result === undefined) { throw new Error( 'Missing expected bundle. If this was an intentional change to the ' + 'build configuration, update Dangerfile.js accordingly: ' + artifactPath ); } criticalResults.push(row(result, baseSha, headSha)); } let significantResults = []; for (const result of results) { // If result exceeds critical threshold, add to top section. if ( (result.change > CRITICAL_THRESHOLD || 0 - result.change > CRITICAL_THRESHOLD || // New file result.change === Infinity || // Deleted file result.change === -1) && // Skip critical artifacts. We added those earlier, in a fixed order. !CRITICAL_ARTIFACT_PATHS.has(result.path) ) { criticalResults.push(row(result, baseSha, headSha)); } // Do the same for results that exceed the significant threshold. These // will go into the bottom, collapsed section. Intentionally including // critical artifacts in this section, too. if ( result.change > SIGNIFICANCE_THRESHOLD || 0 - result.change > SIGNIFICANCE_THRESHOLD || result.change === Infinity || result.change === -1 ) { significantResults.push(row(result, baseSha, headSha)); } } markdown(` Comparing: ${baseSha}...${headSha} ## Critical size changes Includes critical production bundles, as well as any change greater than ${ CRITICAL_THRESHOLD * 100 }%: ${header} ${criticalResults.join('\n')} ## Significant size changes Includes any change greater than ${SIGNIFICANCE_THRESHOLD * 100}%: ${ significantResults.length > 0 ? ` <details> <summary>Expand to show</summary> ${header} ${significantResults.join('\n')} </details> ` : '(No significant changes)' } `); })();
28.373134
115
0.643247
Penetration-Testing-with-Shellcode
/** * 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/ReactFlightDOMServerNode';
22
66
0.702381
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('Profiler change descriptions', () => { let React; let legacyRender; let store; let utils; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); legacyRender = utils.legacyRender; store = global.store; store.collapseNodesByDefault = false; store.recordChangeDescriptions = true; React = require('react'); }); // @reactVersion >=18.0 it('should identify useContext as the cause for a re-render', () => { const Context = React.createContext(0); function Child() { const context = React.useContext(Context); return context; } function areEqual() { return true; } const MemoizedChild = React.memo(Child, areEqual); const ForwardRefChild = React.forwardRef( function RefForwardingComponent(props, ref) { return <Child />; }, ); let forceUpdate = null; const App = function App() { const [val, dispatch] = React.useReducer(x => x + 1, 0); forceUpdate = dispatch; return ( <Context.Provider value={val}> <Child /> <MemoizedChild /> <ForwardRefChild /> </Context.Provider> ); }; const container = document.createElement('div'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender(<App />, container)); utils.act(() => forceUpdate()); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; const commitData = store.profilerStore.getCommitData(rootID, 1); expect(store).toMatchInlineSnapshot(` [root] ▾ <App> ▾ <Context.Provider> <Child> ▾ <Child> [Memo] <Child> ▾ <RefForwardingComponent> [ForwardRef] <Child> `); let element = store.getElementAtIndex(2); expect(element.displayName).toBe('Child'); expect(element.hocDisplayNames).toBeNull(); expect(commitData.changeDescriptions.get(element.id)) .toMatchInlineSnapshot(` { "context": true, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, } `); element = store.getElementAtIndex(3); expect(element.displayName).toBe('Child'); expect(element.hocDisplayNames).toEqual(['Memo']); expect(commitData.changeDescriptions.get(element.id)).toBeUndefined(); element = store.getElementAtIndex(4); expect(element.displayName).toBe('Child'); expect(element.hocDisplayNames).toBeNull(); expect(commitData.changeDescriptions.get(element.id)) .toMatchInlineSnapshot(` { "context": true, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, } `); element = store.getElementAtIndex(5); expect(element.displayName).toBe('RefForwardingComponent'); expect(element.hocDisplayNames).toEqual(['ForwardRef']); expect(commitData.changeDescriptions.get(element.id)) .toMatchInlineSnapshot(` { "context": null, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, } `); element = store.getElementAtIndex(6); expect(element.displayName).toBe('Child'); expect(element.hocDisplayNames).toBeNull(); expect(commitData.changeDescriptions.get(element.id)) .toMatchInlineSnapshot(` { "context": true, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, } `); }); });
24.901316
74
0.597053
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 ReactDOMClient; let ReactDOMServer; let PropTypes; let act; let useMemo; let useState; let useReducer; const ReactFeatureFlags = require('shared/ReactFeatureFlags'); describe('ReactStrictMode', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMServer = require('react-dom/server'); act = require('internal-test-utils').act; useMemo = React.useMemo; useState = React.useState; useReducer = React.useReducer; }); it('should appear in the client component stack', () => { function Foo() { return <div ariaTypo="" />; } const container = document.createElement('div'); expect(() => { ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); }).toErrorDev( 'Invalid ARIA attribute `ariaTypo`. ' + 'ARIA attributes follow the pattern aria-* and must be lowercase.\n' + ' in div (at **)\n' + ' in Foo (at **)', ); }); it('should appear in the SSR component stack', () => { function Foo() { return <div ariaTypo="" />; } expect(() => { ReactDOMServer.renderToString( <React.StrictMode> <Foo /> </React.StrictMode>, ); }).toErrorDev( 'Invalid ARIA attribute `ariaTypo`. ' + 'ARIA attributes follow the pattern aria-* and must be lowercase.\n' + ' in div (at **)\n' + ' in Foo (at **)', ); }); // @gate __DEV__ it('should invoke precommit lifecycle methods twice', () => { let log = []; let shouldComponentUpdate = false; class ClassComponent extends React.Component { state = {}; static getDerivedStateFromProps() { log.push('getDerivedStateFromProps'); return null; } constructor(props) { super(props); log.push('constructor'); } componentDidMount() { log.push('componentDidMount'); } componentDidUpdate() { log.push('componentDidUpdate'); } componentWillUnmount() { log.push('componentWillUnmount'); } shouldComponentUpdate() { log.push('shouldComponentUpdate'); return shouldComponentUpdate; } render() { log.push('render'); return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <ClassComponent /> </React.StrictMode>, container, ); expect(log).toEqual([ 'constructor', 'constructor', 'getDerivedStateFromProps', 'getDerivedStateFromProps', 'render', 'render', 'componentDidMount', ]); log = []; shouldComponentUpdate = true; ReactDOM.render( <React.StrictMode> <ClassComponent /> </React.StrictMode>, container, ); expect(log).toEqual([ 'getDerivedStateFromProps', 'getDerivedStateFromProps', 'shouldComponentUpdate', 'shouldComponentUpdate', 'render', 'render', 'componentDidUpdate', ]); log = []; shouldComponentUpdate = false; ReactDOM.render( <React.StrictMode> <ClassComponent /> </React.StrictMode>, container, ); expect(log).toEqual([ 'getDerivedStateFromProps', 'getDerivedStateFromProps', 'shouldComponentUpdate', 'shouldComponentUpdate', ]); }); it('should invoke setState callbacks twice', () => { let instance; class ClassComponent extends React.Component { state = { count: 1, }; render() { instance = this; return null; } } let setStateCount = 0; const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <ClassComponent /> </React.StrictMode>, container, ); instance.setState(state => { setStateCount++; return { count: state.count + 1, }; }); // Callback should be invoked twice in DEV expect(setStateCount).toBe(__DEV__ ? 2 : 1); // But each time `state` should be the previous value expect(instance.state.count).toBe(2); }); it('should invoke precommit lifecycle methods twice in DEV', () => { const {StrictMode} = React; let log = []; let shouldComponentUpdate = false; function Root() { return ( <StrictMode> <ClassComponent /> </StrictMode> ); } class ClassComponent extends React.Component { state = {}; static getDerivedStateFromProps() { log.push('getDerivedStateFromProps'); return null; } constructor(props) { super(props); log.push('constructor'); } componentDidMount() { log.push('componentDidMount'); } componentDidUpdate() { log.push('componentDidUpdate'); } componentWillUnmount() { log.push('componentWillUnmount'); } shouldComponentUpdate() { log.push('shouldComponentUpdate'); return shouldComponentUpdate; } render() { log.push('render'); return null; } } const container = document.createElement('div'); ReactDOM.render(<Root />, container); if (__DEV__) { expect(log).toEqual([ 'constructor', 'constructor', 'getDerivedStateFromProps', 'getDerivedStateFromProps', 'render', 'render', 'componentDidMount', ]); } else { expect(log).toEqual([ 'constructor', 'getDerivedStateFromProps', 'render', 'componentDidMount', ]); } log = []; shouldComponentUpdate = true; ReactDOM.render(<Root />, container); if (__DEV__) { expect(log).toEqual([ 'getDerivedStateFromProps', 'getDerivedStateFromProps', 'shouldComponentUpdate', 'shouldComponentUpdate', 'render', 'render', 'componentDidUpdate', ]); } else { expect(log).toEqual([ 'getDerivedStateFromProps', 'shouldComponentUpdate', 'render', 'componentDidUpdate', ]); } log = []; shouldComponentUpdate = false; ReactDOM.render(<Root />, container); if (__DEV__) { expect(log).toEqual([ 'getDerivedStateFromProps', 'getDerivedStateFromProps', 'shouldComponentUpdate', 'shouldComponentUpdate', ]); } else { expect(log).toEqual([ 'getDerivedStateFromProps', 'shouldComponentUpdate', ]); } }); it('should invoke setState callbacks twice in DEV', () => { const {StrictMode} = React; let instance; class ClassComponent extends React.Component { state = { count: 1, }; render() { instance = this; return null; } } let setStateCount = 0; const container = document.createElement('div'); ReactDOM.render( <StrictMode> <ClassComponent /> </StrictMode>, container, ); instance.setState(state => { setStateCount++; return { count: state.count + 1, }; }); // Callback should be invoked twice (in DEV) expect(setStateCount).toBe(__DEV__ ? 2 : 1); // But each time `state` should be the previous value expect(instance.state.count).toBe(2); }); // @gate debugRenderPhaseSideEffectsForStrictMode it('double invokes useMemo functions', async () => { let log = []; function Uppercased({text}) { return useMemo(() => { const uppercased = text.toUpperCase(); log.push('Compute toUpperCase: ' + uppercased); return uppercased; }, [text]); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); // Mount await act(() => { root.render( <React.StrictMode> <Uppercased text="hello" /> </React.StrictMode>, ); }); expect(container.textContent).toBe('HELLO'); expect(log).toEqual([ 'Compute toUpperCase: HELLO', 'Compute toUpperCase: HELLO', ]); log = []; // Update await act(() => { root.render( <React.StrictMode> <Uppercased text="goodbye" /> </React.StrictMode>, ); }); expect(container.textContent).toBe('GOODBYE'); expect(log).toEqual([ 'Compute toUpperCase: GOODBYE', 'Compute toUpperCase: GOODBYE', ]); }); // @gate debugRenderPhaseSideEffectsForStrictMode it('double invokes useMemo functions', async () => { let log = []; function Uppercased({text}) { const memoizedResult = useMemo(() => { const uppercased = text.toUpperCase(); log.push('Compute toUpperCase: ' + uppercased); return {uppercased}; }, [text]); // Push this to the log so we can check whether the same memoized result // it returned during both invocations. log.push(memoizedResult); return memoizedResult.uppercased; } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); // Mount await act(() => { root.render( <React.StrictMode> <Uppercased text="hello" /> </React.StrictMode>, ); }); expect(container.textContent).toBe('HELLO'); expect(log).toEqual([ 'Compute toUpperCase: HELLO', 'Compute toUpperCase: HELLO', {uppercased: 'HELLO'}, {uppercased: 'HELLO'}, ]); // Even though the memoized function is invoked twice, the same object // is returned both times. expect(log[2]).toBe(log[3]); log = []; // Update await act(() => { root.render( <React.StrictMode> <Uppercased text="goodbye" /> </React.StrictMode>, ); }); expect(container.textContent).toBe('GOODBYE'); expect(log).toEqual([ 'Compute toUpperCase: GOODBYE', 'Compute toUpperCase: GOODBYE', {uppercased: 'GOODBYE'}, {uppercased: 'GOODBYE'}, ]); // Even though the memoized function is invoked twice, the same object // is returned both times. expect(log[2]).toBe(log[3]); }); // @gate debugRenderPhaseSideEffectsForStrictMode it('double invokes setState updater functions', async () => { const log = []; let setCount; function App() { const [count, _setCount] = useState(0); setCount = _setCount; return count; } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <React.StrictMode> <App /> </React.StrictMode>, ); }); expect(container.textContent).toBe('0'); await act(() => { setCount(() => { log.push('Compute count: 1'); return 1; }); }); expect(container.textContent).toBe('1'); expect(log).toEqual(['Compute count: 1', 'Compute count: 1']); }); // @gate debugRenderPhaseSideEffectsForStrictMode it('double invokes reducer functions', async () => { const log = []; function reducer(prevState, action) { log.push('Compute new state: ' + action); return action; } let dispatch; function App() { const [count, _dispatch] = useReducer(reducer, 0); dispatch = _dispatch; return count; } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <React.StrictMode> <App /> </React.StrictMode>, ); }); expect(container.textContent).toBe('0'); await act(() => { dispatch(1); }); expect(container.textContent).toBe('1'); expect(log).toEqual(['Compute new state: 1', 'Compute new state: 1']); }); }); describe('Concurrent Mode', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); act = require('internal-test-utils').act; }); it('should warn about unsafe legacy lifecycle methods anywhere in a StrictMode tree', async () => { function StrictRoot() { return ( <React.StrictMode> <App /> </React.StrictMode> ); } class App extends React.Component { UNSAFE_componentWillMount() {} UNSAFE_componentWillUpdate() {} render() { return ( <div> <Wrapper> <Foo /> </Wrapper> <div> <Bar /> <Foo /> </div> </div> ); } } function Wrapper({children}) { return <div>{children}</div>; } class Foo extends React.Component { UNSAFE_componentWillReceiveProps() {} render() { return null; } } class Bar extends React.Component { UNSAFE_componentWillReceiveProps() {} render() { return null; } } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await expect( async () => await act(() => root.render(<StrictRoot />)), ).toErrorDev( [ /* eslint-disable max-len */ `Warning: Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move code with side effects to componentDidMount, and set initial state in the constructor. Please update the following components: App`, `Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move data fetching code or side effects to componentDidUpdate. * If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state Please update the following components: Bar, Foo`, `Warning: Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move data fetching code or side effects to componentDidUpdate. Please update the following components: App`, /* eslint-enable max-len */ ], {withoutStack: true}, ); // Dedupe await act(() => root.render(<App />)); }); it('should coalesce warnings by lifecycle name', async () => { function StrictRoot() { return ( <React.StrictMode> <App /> </React.StrictMode> ); } class App extends React.Component { UNSAFE_componentWillMount() {} UNSAFE_componentWillUpdate() {} render() { return <Parent />; } } class Parent extends React.Component { componentWillMount() {} componentWillUpdate() {} componentWillReceiveProps() {} render() { return <Child />; } } class Child extends React.Component { UNSAFE_componentWillReceiveProps() {} render() { return null; } } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await expect(async () => { await expect( async () => await act(() => root.render(<StrictRoot />)), ).toErrorDev( [ /* eslint-disable max-len */ `Warning: Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move code with side effects to componentDidMount, and set initial state in the constructor. Please update the following components: App`, `Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move data fetching code or side effects to componentDidUpdate. * If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state Please update the following components: Child`, `Warning: Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move data fetching code or side effects to componentDidUpdate. Please update the following components: App`, /* eslint-enable max-len */ ], {withoutStack: true}, ); }).toWarnDev( [ /* eslint-disable max-len */ `Warning: componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move code with side effects to componentDidMount, and set initial state in the constructor. * Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run \`npx react-codemod rename-unsafe-lifecycles\` in your project source folder. Please update the following components: Parent`, `Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move data fetching code or side effects to componentDidUpdate. * If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state * Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run \`npx react-codemod rename-unsafe-lifecycles\` in your project source folder. Please update the following components: Parent`, `Warning: componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details. * Move data fetching code or side effects to componentDidUpdate. * Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run \`npx react-codemod rename-unsafe-lifecycles\` in your project source folder. Please update the following components: Parent`, /* eslint-enable max-len */ ], {withoutStack: true}, ); // Dedupe await act(() => root.render(<StrictRoot />)); }); it('should warn about components not present during the initial render', async () => { function StrictRoot({foo}) { return <React.StrictMode>{foo ? <Foo /> : <Bar />}</React.StrictMode>; } class Foo extends React.Component { UNSAFE_componentWillMount() {} render() { return null; } } class Bar extends React.Component { UNSAFE_componentWillMount() {} render() { return null; } } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await expect(async () => { await act(() => root.render(<StrictRoot foo={true} />)); }).toErrorDev( 'Using UNSAFE_componentWillMount in strict mode is not recommended', {withoutStack: true}, ); await expect(async () => { await act(() => root.render(<StrictRoot foo={false} />)); }).toErrorDev( 'Using UNSAFE_componentWillMount in strict mode is not recommended', {withoutStack: true}, ); // Dedupe await act(() => root.render(<StrictRoot foo={true} />)); await act(() => root.render(<StrictRoot foo={false} />)); }); it('should also warn inside of "strict" mode trees', () => { const {StrictMode} = React; class SyncRoot extends React.Component { UNSAFE_componentWillMount() {} UNSAFE_componentWillUpdate() {} UNSAFE_componentWillReceiveProps() {} render() { return ( <StrictMode> <Wrapper /> </StrictMode> ); } } function Wrapper({children}) { return ( <div> <Bar /> <Foo /> </div> ); } class Foo extends React.Component { UNSAFE_componentWillReceiveProps() {} render() { return null; } } class Bar extends React.Component { UNSAFE_componentWillReceiveProps() {} render() { return null; } } const container = document.createElement('div'); expect(() => ReactDOM.render(<SyncRoot />, container)).toErrorDev( 'Using UNSAFE_componentWillReceiveProps in strict mode is not recommended', {withoutStack: true}, ); // Dedupe ReactDOM.render(<SyncRoot />, container); }); }); describe('symbol checks', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); }); it('should switch from StrictMode to a Fragment and reset state', () => { const {Fragment, StrictMode} = React; function ParentComponent({useFragment}) { return useFragment ? ( <Fragment> <ChildComponent /> </Fragment> ) : ( <StrictMode> <ChildComponent /> </StrictMode> ); } class ChildComponent extends React.Component { state = { count: 0, }; static getDerivedStateFromProps(nextProps, prevState) { return { count: prevState.count + 1, }; } render() { return `count:${this.state.count}`; } } const container = document.createElement('div'); ReactDOM.render(<ParentComponent useFragment={false} />, container); expect(container.textContent).toBe('count:1'); ReactDOM.render(<ParentComponent useFragment={true} />, container); expect(container.textContent).toBe('count:1'); }); it('should switch from a Fragment to StrictMode and reset state', () => { const {Fragment, StrictMode} = React; function ParentComponent({useFragment}) { return useFragment ? ( <Fragment> <ChildComponent /> </Fragment> ) : ( <StrictMode> <ChildComponent /> </StrictMode> ); } class ChildComponent extends React.Component { state = { count: 0, }; static getDerivedStateFromProps(nextProps, prevState) { return { count: prevState.count + 1, }; } render() { return `count:${this.state.count}`; } } const container = document.createElement('div'); ReactDOM.render(<ParentComponent useFragment={true} />, container); expect(container.textContent).toBe('count:1'); ReactDOM.render(<ParentComponent useFragment={false} />, container); expect(container.textContent).toBe('count:1'); }); it('should update with StrictMode without losing state', () => { const {StrictMode} = React; function ParentComponent() { return ( <StrictMode> <ChildComponent /> </StrictMode> ); } class ChildComponent extends React.Component { state = { count: 0, }; static getDerivedStateFromProps(nextProps, prevState) { return { count: prevState.count + 1, }; } render() { return `count:${this.state.count}`; } } const container = document.createElement('div'); ReactDOM.render(<ParentComponent />, container); expect(container.textContent).toBe('count:1'); ReactDOM.render(<ParentComponent />, container); expect(container.textContent).toBe('count:2'); }); }); describe('string refs', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); }); it('should warn within a strict tree', () => { const {StrictMode} = React; class OuterComponent extends React.Component { render() { return ( <StrictMode> <InnerComponent ref="somestring" /> </StrictMode> ); } } class InnerComponent extends React.Component { render() { return null; } } const container = document.createElement('div'); expect(() => { ReactDOM.render(<OuterComponent />, container); }).toErrorDev( 'Warning: Component "StrictMode" contains the string ref "somestring". ' + '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 OuterComponent (at **)', ); // Dedup ReactDOM.render(<OuterComponent />, container); }); it('should warn within a strict tree', () => { const {StrictMode} = React; class OuterComponent extends React.Component { render() { return ( <StrictMode> <InnerComponent /> </StrictMode> ); } } class InnerComponent extends React.Component { render() { return <MiddleComponent ref="somestring" />; } } class MiddleComponent extends React.Component { render() { return null; } } const container = document.createElement('div'); expect(() => { ReactDOM.render(<OuterComponent />, container); }).toErrorDev( 'Warning: Component "InnerComponent" contains the string ref "somestring". ' + '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 InnerComponent (at **)\n' + ' in OuterComponent (at **)', ); // Dedup ReactDOM.render(<OuterComponent />, container); }); }); describe('context legacy', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); PropTypes = require('prop-types'); }); afterEach(() => { jest.restoreAllMocks(); }); // @gate !disableLegacyContext || !__DEV__ it('should warn if the legacy context API have been used in strict mode', () => { class LegacyContextProvider extends React.Component { getChildContext() { return {color: 'purple'}; } render() { return ( <div> <LegacyContextConsumer /> <FunctionalLegacyContextConsumer /> </div> ); } } function FunctionalLegacyContextConsumer() { return null; } LegacyContextProvider.childContextTypes = { color: PropTypes.string, }; class LegacyContextConsumer extends React.Component { render() { return null; } } const {StrictMode} = React; class Root extends React.Component { render() { return ( <div> <StrictMode> <LegacyContextProvider /> </StrictMode> </div> ); } } LegacyContextConsumer.contextTypes = { color: PropTypes.string, }; FunctionalLegacyContextConsumer.contextTypes = { color: PropTypes.string, }; const container = document.createElement('div'); expect(() => { ReactDOM.render(<Root />, container); }).toErrorDev( 'Warning: Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: ' + 'FunctionalLegacyContextConsumer, LegacyContextConsumer, LegacyContextProvider' + '\n\nLearn more about this warning here: ' + 'https://reactjs.org/link/legacy-context' + '\n in LegacyContextProvider (at **)' + '\n in div (at **)' + '\n in Root (at **)', ); // Dedupe ReactDOM.render(<Root />, container); }); describe('console logs logging', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); }); if (ReactFeatureFlags.consoleManagedByDevToolsDuringStrictMode) { it('does not disable logs for class double render', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { render() { count++; console.log('foo ' + count); return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(__DEV__ ? 2 : 1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('does not disable logs for class double ctor', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { constructor(props) { super(props); count++; console.log('foo ' + count); } render() { return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(__DEV__ ? 2 : 1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('does not disable logs for class double getDerivedStateFromProps', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { state = {}; static getDerivedStateFromProps() { count++; console.log('foo ' + count); return {}; } render() { return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(__DEV__ ? 2 : 1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('does not disable logs for class double shouldComponentUpdate', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { state = {}; shouldComponentUpdate() { count++; console.log('foo ' + count); return {}; } render() { return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); // Trigger sCU: ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(__DEV__ ? 2 : 1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('does not disable logs for class state updaters', () => { spyOnDevAndProd(console, 'log'); let inst; let count = 0; class Foo extends React.Component { state = {}; render() { inst = this; return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); inst.setState(() => { count++; console.log('foo ' + count); return {}; }); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(__DEV__ ? 2 : 1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('does not disable logs for function double render', () => { spyOnDevAndProd(console, 'log'); let count = 0; function Foo() { count++; console.log('foo ' + count); return null; } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(__DEV__ ? 2 : 1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); } else { it('disable logs for class double render', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { render() { count++; console.log('foo ' + count); return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('disables logs for class double ctor', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { constructor(props) { super(props); count++; console.log('foo ' + count); } render() { return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('disable logs for class double getDerivedStateFromProps', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { state = {}; static getDerivedStateFromProps() { count++; console.log('foo ' + count); return {}; } render() { return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('disable logs for class double shouldComponentUpdate', () => { spyOnDevAndProd(console, 'log'); let count = 0; class Foo extends React.Component { state = {}; shouldComponentUpdate() { count++; console.log('foo ' + count); return {}; } render() { return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); // Trigger sCU: ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('disable logs for class state updaters', () => { spyOnDevAndProd(console, 'log'); let inst; let count = 0; class Foo extends React.Component { state = {}; render() { inst = this; return null; } } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); inst.setState(() => { count++; console.log('foo ' + count); return {}; }); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); it('disable logs for function double render', () => { spyOnDevAndProd(console, 'log'); let count = 0; function Foo() { count++; console.log('foo ' + count); return null; } const container = document.createElement('div'); ReactDOM.render( <React.StrictMode> <Foo /> </React.StrictMode>, container, ); expect(count).toBe(__DEV__ ? 2 : 1); expect(console.log).toBeCalledTimes(1); // Note: we should display the first log because otherwise // there is a risk of suppressing warnings when they happen, // and on the next render they'd get deduplicated and ignored. expect(console.log).toBeCalledWith('foo 1'); }); } }); });
27.339532
309
0.578035
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 ReactDOM = require('ReactDOM'); module.exports = ReactDOM.unstable_renderSubtreeIntoContainer;
22.846154
66
0.737864