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. * * @flow */ export {renderToReadableStream, version} from './ReactDOMFizzServerBrowser.js';
24.909091
79
0.725352
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'; // 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 webpackServerMap; 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-webpack/server', () => require('react-server-dom-webpack/server.browser'), ); const WebpackMock = require('./utils/WebpackMock'); // serverExports = WebpackMock.serverExports; webpackServerMap = WebpackMock.webpackServerMap; ReactServerDOMServer = require('react-server-dom-webpack/server.browser'); jest.resetModules(); ReactServerDOMClient = require('react-server-dom-webpack/client'); }); // This method should exist on File but is not implemented in JSDOM async function arrayBuffer(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function () { return resolve(reader.result); }; reader.onerror = function () { return reject(reader.error); }; reader.readAsArrayBuffer(file); }); } it('can pass undefined as a reply', async () => { const body = await ReactServerDOMClient.encodeReply(undefined); const missing = await ReactServerDOMServer.decodeReply( body, webpackServerMap, ); expect(missing).toBe(undefined); const body2 = await ReactServerDOMClient.encodeReply({ array: [undefined, null, undefined], prop: undefined, }); const object = await ReactServerDOMServer.decodeReply( body2, webpackServerMap, ); expect(object.array.length).toBe(3); expect(object.array[0]).toBe(undefined); expect(object.array[1]).toBe(null); expect(object.array[3]).toBe(undefined); expect(object.prop).toBe(undefined); // These should really be true but our deserialization doesn't currently deal with it. expect('3' in object.array).toBe(false); expect('prop' in object).toBe(false); }); it('can pass an iterable as a reply', async () => { const body = await ReactServerDOMClient.encodeReply({ [Symbol.iterator]: function* () { yield 'A'; yield 'B'; yield 'C'; }, }); const iterable = await ReactServerDOMServer.decodeReply( body, webpackServerMap, ); const items = []; // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const item of iterable) { items.push(item); } expect(items).toEqual(['A', 'B', 'C']); }); it('can pass weird numbers as a reply', async () => { const nums = [0, -0, Infinity, -Infinity, NaN]; const body = await ReactServerDOMClient.encodeReply(nums); const nums2 = await ReactServerDOMServer.decodeReply( body, webpackServerMap, ); expect(nums).toEqual(nums2); expect(nums.every((n, i) => Object.is(n, nums2[i]))).toBe(true); }); it('can pass a BigInt as a reply', async () => { const body = await ReactServerDOMClient.encodeReply(90071992547409910000n); const n = await ReactServerDOMServer.decodeReply(body, webpackServerMap); expect(n).toEqual(90071992547409910000n); }); it('can pass FormData as a reply', async () => { const formData = new FormData(); formData.set('hello', 'world'); formData.append('list', '1'); formData.append('list', '2'); formData.append('list', '3'); const typedArray = new Uint8Array([0, 1, 2, 3]); const blob = new Blob([typedArray]); formData.append('blob', blob, 'filename.blob'); const body = await ReactServerDOMClient.encodeReply(formData); const formData2 = await ReactServerDOMServer.decodeReply( body, webpackServerMap, ); expect(formData2).not.toBe(formData); expect(Array.from(formData2).length).toBe(5); expect(formData2.get('hello')).toBe('world'); expect(formData2.getAll('list')).toEqual(['1', '2', '3']); const blob2 = formData.get('blob'); expect(blob2.size).toBe(4); expect(blob2.name).toBe('filename.blob'); expect(blob2.type).toBe(''); const typedArray2 = new Uint8Array(await arrayBuffer(blob2)); expect(typedArray2).toEqual(typedArray); }); it('can pass multiple Files in FormData', async () => { const typedArrayA = new Uint8Array([0, 1, 2, 3]); const typedArrayB = new Uint8Array([4, 5]); const blobA = new Blob([typedArrayA]); const blobB = new Blob([typedArrayB]); const formData = new FormData(); formData.append('filelist', 'string'); formData.append('filelist', blobA); formData.append('filelist', blobB); const body = await ReactServerDOMClient.encodeReply(formData); const formData2 = await ReactServerDOMServer.decodeReply( body, webpackServerMap, ); const filelist2 = formData2.getAll('filelist'); expect(filelist2.length).toBe(3); expect(filelist2[0]).toBe('string'); const blobA2 = filelist2[1]; expect(blobA2.size).toBe(4); expect(blobA2.name).toBe('blob'); expect(blobA2.type).toBe(''); const typedArrayA2 = new Uint8Array(await arrayBuffer(blobA2)); expect(typedArrayA2).toEqual(typedArrayA); const blobB2 = filelist2[2]; expect(blobB2.size).toBe(2); expect(blobB2.name).toBe('blob'); expect(blobB2.type).toBe(''); const typedArrayB2 = new Uint8Array(await arrayBuffer(blobB2)); expect(typedArrayB2).toEqual(typedArrayB); }); it('can pass two independent FormData with same keys', async () => { const formDataA = new FormData(); formDataA.set('greeting', 'hello'); const formDataB = new FormData(); formDataB.set('greeting', 'hi'); const body = await ReactServerDOMClient.encodeReply({ a: formDataA, b: formDataB, }); const {a: formDataA2, b: formDataB2} = await ReactServerDOMServer.decodeReply(body, webpackServerMap); expect(Array.from(formDataA2).length).toBe(1); expect(Array.from(formDataB2).length).toBe(1); expect(formDataA2.get('greeting')).toBe('hello'); expect(formDataB2.get('greeting')).toBe('hi'); }); it('can pass a Date as a reply', async () => { const d = new Date(1234567890123); const body = await ReactServerDOMClient.encodeReply(d); const d2 = await ReactServerDOMServer.decodeReply(body, webpackServerMap); expect(d).toEqual(d2); expect(d % 1000).toEqual(123); // double-check the milliseconds made it through }); it('can pass a Map as a reply', async () => { const objKey = {obj: 'key'}; const m = new Map([ ['hi', {greet: 'world'}], [objKey, 123], ]); const body = await ReactServerDOMClient.encodeReply(m); const m2 = await ReactServerDOMServer.decodeReply(body, webpackServerMap); expect(m2 instanceof Map).toBe(true); expect(m2.size).toBe(2); expect(m2.get('hi').greet).toBe('world'); expect(m2).toEqual(m); }); it('can pass a Set as a reply', async () => { const objKey = {obj: 'key'}; const s = new Set(['hi', objKey]); const body = await ReactServerDOMClient.encodeReply(s); const s2 = await ReactServerDOMServer.decodeReply(body, webpackServerMap); expect(s2 instanceof Set).toBe(true); expect(s2.size).toBe(2); expect(s2.has('hi')).toBe(true); expect(s2).toEqual(s); }); it('does not hang indefinitely when calling decodeReply with FormData', async () => { let error; try { await ReactServerDOMServer.decodeReply(new FormData(), webpackServerMap); } catch (e) { error = e; } expect(error.message).toBe('Connection closed.'); }); });
32.044898
90
0.657196
null
'use strict'; const fetch = require('node-fetch'); const POLLING_INTERVAL = 10 * 1000; // 10 seconds const RETRY_TIMEOUT = 4 * 60 * 1000; // 4 minutes function wait(ms) { return new Promise(resolve => { setTimeout(() => resolve(), ms); }); } function scrapeBuildIDFromStatus(status) { return /\/facebook\/react\/([0-9]+)/.exec(status.target_url)[1]; } async function getBuildIdForCommit(sha, allowBrokenCI = false) { const retryLimit = Date.now() + RETRY_TIMEOUT; retry: while (true) { const statusesResponse = await fetch( `https://api.github.com/repos/facebook/react/commits/${sha}/status?per_page=100` ); if (!statusesResponse.ok) { if (statusesResponse.status === 404) { throw Error('Could not find commit for: ' + sha); } const {message, documentation_url} = await statusesResponse.json(); const msg = documentation_url ? `${message}\n\t${documentation_url}` : message; throw Error(msg); } const {statuses, state} = await statusesResponse.json(); if (!allowBrokenCI && state === 'failure') { throw new Error(`Base commit is broken: ${sha}`); } for (let i = 0; i < statuses.length; i++) { const status = statuses[i]; if (status.context === `ci/circleci: process_artifacts_combined`) { if (status.state === 'success') { return scrapeBuildIDFromStatus(status); } if (status.state === 'failure') { throw new Error(`Build job for commit failed: ${sha}`); } if (status.state === 'pending') { if (Date.now() < retryLimit) { await wait(POLLING_INTERVAL); continue retry; } // GitHub's status API is super flaky. Sometimes it reports a job // as "pending" even after it completes in CircleCI. If it's still // pending when we time out, return the build ID anyway. // TODO: The location of the retry loop is a bit weird. We should // probably combine this function with the one that downloads the // artifacts, and wrap the retry loop around the whole thing. return scrapeBuildIDFromStatus(status); } } } if (state === 'pending') { if (Date.now() < retryLimit) { await wait(POLLING_INTERVAL); continue retry; } throw new Error('Exceeded retry limit. Build job is still pending.'); } throw new Error('Could not find build for commit: ' + sha); } } module.exports = getBuildIdForCommit;
32.592105
86
0.603448
Mastering-Machine-Learning-for-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import styles from './LayoutViewer.css'; import type {Layout} from './types'; type Props = { id: number, layout: Layout, }; export default function LayoutViewer({id, layout}: Props): React.Node { const {height, margin, padding, y, width, x} = layout; return ( <div className={styles.LayoutViewer}> <div className={styles.Header}>layout</div> <div className={styles.DashedBox}> <div className={styles.LabelRow}> <label className={styles.Label}>margin</label> <label>{margin.top || '-'}</label> </div> <div className={styles.BoxRow}> <label>{margin.left || '-'}</label> <div className={styles.SolidBox}> <div className={styles.LabelRow}> <label className={styles.Label}>padding</label> <label>{padding.top || '-'}</label> </div> <div className={styles.BoxRow}> <label>{padding.left || '-'}</label> <div className={styles.DashedBox}> <div className={styles.LabelRow}> {format(width)} x {format(height)} ({format(x)}, {format(y)}) </div> </div> <label>{padding.right || '-'}</label> </div> <label>{padding.bottom || '-'}</label> </div> <label>{margin.right || '-'}</label> </div> <label>{margin.bottom || '-'}</label> </div> </div> ); } function format(number: number): string | number { if (Math.round(number) === number) { return number; } else { return number.toFixed(1); } }
24.958333
79
0.544433
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 Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import styles from './ExpandCollapseToggle.css'; type ExpandCollapseToggleProps = { disabled: boolean, isOpen: boolean, setIsOpen: Function, }; export default function ExpandCollapseToggle({ disabled, isOpen, setIsOpen, }: ExpandCollapseToggleProps): React.Node { return ( <Button className={styles.ExpandCollapseToggle} disabled={disabled} onClick={() => setIsOpen(prevIsOpen => !prevIsOpen)} title={`${isOpen ? 'Collapse' : 'Expand'} prop value`}> <ButtonIcon type={isOpen ? 'expanded' : 'collapsed'} /> </Button> ); }
22.972973
66
0.67833
owtf
/* * Copyright (c) Facebook, Inc. and its affiliates. */ import {Page} from 'components/Layout/Page'; import {MDXComponents} from 'components/MDX/MDXComponents'; import sidebarLearn from '../sidebarLearn.json'; const {Intro, MaxWidth, p: P, a: A} = MDXComponents; export default function NotFound() { return ( <Page toc={[]} meta={{title: 'Not Found'}} routeTree={sidebarLearn}> <MaxWidth> <Intro> <P>This page doesn’t exist.</P> <P> If this is a mistake{', '} <A href="https://github.com/reactjs/react.dev/issues/new"> let us know </A> {', '} and we will try to fix it! </P> </Intro> </MaxWidth> </Page> ); }
24.333333
72
0.545455
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import './ReactNativeInjectionShared'; import { getFiberCurrentPropsFromNode, getInstanceFromNode, getNodeFromInstance, } from './ReactFabricComponentTree'; import {setComponentTree} from './legacy-events/EventPluginUtils'; import ReactFabricGlobalResponderHandler from './ReactFabricGlobalResponderHandler'; import ResponderEventPlugin from './legacy-events/ResponderEventPlugin'; setComponentTree( getFiberCurrentPropsFromNode, getInstanceFromNode, getNodeFromInstance, ); ResponderEventPlugin.injection.injectGlobalResponderHandler( ReactFabricGlobalResponderHandler, );
25.533333
84
0.8
PenTesting
/** * 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-webpack/client instead.');
20.923077
66
0.700704
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 {useState} from 'react'; import Store from '../../store'; import EditableName from './EditableName'; import EditableValue from './EditableValue'; import {parseHookPathForEdit} from './utils'; import styles from './NewKeyValue.css'; import type {InspectedElement} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; type Props = { bridge: FrontendBridge, depth: number, hidden: boolean, hookID?: ?number, inspectedElement: InspectedElement, path: Array<string | number>, store: Store, type: 'props' | 'state' | 'hooks' | 'context', }; export default function NewKeyValue({ bridge, depth, hidden, hookID, inspectedElement, path, store, type, }: Props): React.Node { const [newPropKey, setNewPropKey] = useState<number>(0); const [newPropName, setNewPropName] = useState<string>(''); // $FlowFixMe[missing-local-annot] const overrideNewEntryName = (oldPath: any, newPath) => { setNewPropName(newPath[newPath.length - 1]); }; const overrideNewEntryValue = ( newPath: Array<string | number>, value: any, ) => { if (!newPropName) { return; } setNewPropName(''); setNewPropKey(newPropKey + 1); const {id} = inspectedElement; const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { let basePath: Array<string | number> = newPath; if (hookID != null) { basePath = parseHookPathForEdit(basePath); } bridge.send('overrideValueAtPath', { type, hookID, id, path: basePath, rendererID, value, }); } }; return ( <div key={newPropKey} hidden={hidden} style={{ paddingLeft: `${(depth - 1) * 0.75}rem`, }}> <div className={styles.NewKeyValue}> <EditableName autoFocus={newPropKey > 0} className={styles.EditableName} overrideName={overrideNewEntryName} path={[]} /> :&nbsp; <EditableValue className={styles.EditableValue} overrideValue={overrideNewEntryValue} path={[...path, newPropName]} value={''} /> </div> </div> ); }
22.904762
79
0.616979
null
'use strict'; const fs = require('fs'); const ClosureCompiler = require('google-closure-compiler').compiler; const prettier = require('prettier'); const instructionDir = './packages/react-dom-bindings/src/server/fizz-instruction-set'; // This is the name of the generated file that exports the inline instruction // set as strings. const inlineCodeStringsFilename = instructionDir + '/ReactDOMFizzInstructionSetInlineCodeStrings.js'; const config = [ { entry: 'ReactDOMFizzInlineClientRenderBoundary.js', exportName: 'clientRenderBoundary', }, { entry: 'ReactDOMFizzInlineCompleteBoundary.js', exportName: 'completeBoundary', }, { entry: 'ReactDOMFizzInlineCompleteBoundaryWithStyles.js', exportName: 'completeBoundaryWithStyles', }, { entry: 'ReactDOMFizzInlineCompleteSegment.js', exportName: 'completeSegment', }, { entry: 'ReactDOMFizzInlineFormReplaying.js', exportName: 'formReplaying', }, ]; const prettierConfig = require('../../.prettierrc.js'); async function main() { const exportStatements = await Promise.all( config.map(async ({entry, exportName}) => { const fullEntryPath = instructionDir + '/' + entry; const compiler = new ClosureCompiler({ entry_point: fullEntryPath, js: [ require.resolve('./externs/closure-externs.js'), fullEntryPath, instructionDir + '/ReactDOMFizzInstructionSetInlineSource.js', instructionDir + '/ReactDOMFizzInstructionSetShared.js', ], compilation_level: 'ADVANCED', language_in: 'ECMASCRIPT_2020', language_out: 'ECMASCRIPT5_STRICT', module_resolution: 'NODE', // This is necessary to prevent Closure from inlining a Promise polyfill rewrite_polyfills: false, }); const code = await new Promise((resolve, reject) => { compiler.run((exitCode, stdOut, stdErr) => { if (exitCode !== 0) { reject(new Error(stdErr)); } else { resolve(stdOut); } }); }); return `export const ${exportName} = ${JSON.stringify(code.trim())};`; }) ); let outputCode = [ '// This is a generated file. The source files are in react-dom-bindings/src/server/fizz-instruction-set.', '// The build script is at scripts/rollup/generate-inline-fizz-runtime.js.', '// Run `yarn generate-inline-fizz-runtime` to generate.', ...exportStatements, ].join('\n'); // This replaces "window.$globalVar" with "$globalVar". There's probably a // better way to do this with Closure, with externs or something, but I // couldn't figure it out. Good enough for now. This only affects the inline // Fizz runtime, and should break immediately if there were a mistake, so I'm // not too worried about it. outputCode = outputCode.replace( /window\.(\$[A-z0-9_]*|matchMedia)/g, (_, variableName) => variableName ); const prettyOutputCode = await prettier.format(outputCode, prettierConfig); fs.writeFileSync(inlineCodeStringsFilename, prettyOutputCode, 'utf8'); } main().catch(err => { console.error(err); process.exit(1); });
30.76
111
0.664567
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; describe('ReactDOMComponent', () => { let React; let ReactTestUtils; let ReactDOM; let ReactDOMServer; 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'); }); afterEach(() => { jest.restoreAllMocks(); }); describe('updateDOM', () => { it('should handle className', () => { const container = document.createElement('div'); ReactDOM.render(<div style={{}} />, container); ReactDOM.render(<div className={'foo'} />, container); expect(container.firstChild.className).toEqual('foo'); ReactDOM.render(<div className={'bar'} />, container); expect(container.firstChild.className).toEqual('bar'); ReactDOM.render(<div className={null} />, container); expect(container.firstChild.className).toEqual(''); }); it('should gracefully handle various style value types', () => { const container = document.createElement('div'); ReactDOM.render(<div style={{}} />, container); const stubStyle = container.firstChild.style; // set initial style const setup = { display: 'block', left: '1px', top: 2, fontFamily: 'Arial', }; ReactDOM.render(<div style={setup} />, container); expect(stubStyle.display).toEqual('block'); expect(stubStyle.left).toEqual('1px'); expect(stubStyle.top).toEqual('2px'); expect(stubStyle.fontFamily).toEqual('Arial'); // reset the style to their default state const reset = {display: '', left: null, top: false, fontFamily: true}; ReactDOM.render(<div style={reset} />, container); expect(stubStyle.display).toEqual(''); expect(stubStyle.left).toEqual(''); expect(stubStyle.top).toEqual(''); expect(stubStyle.fontFamily).toEqual(''); }); it('should not update styles when mutating a proxy style object', () => { const styleStore = { display: 'none', fontFamily: 'Arial', lineHeight: 1.2, }; // We use a proxy style object so that we can mutate it even if it is // frozen in DEV. const styles = { get display() { return styleStore.display; }, set display(v) { styleStore.display = v; }, get fontFamily() { return styleStore.fontFamily; }, set fontFamily(v) { styleStore.fontFamily = v; }, get lineHeight() { return styleStore.lineHeight; }, set lineHeight(v) { styleStore.lineHeight = v; }, }; const container = document.createElement('div'); ReactDOM.render(<div style={styles} />, container); const stubStyle = container.firstChild.style; stubStyle.display = styles.display; stubStyle.fontFamily = styles.fontFamily; styles.display = 'block'; ReactDOM.render(<div style={styles} />, container); expect(stubStyle.display).toEqual('none'); expect(stubStyle.fontFamily).toEqual('Arial'); expect(stubStyle.lineHeight).toEqual('1.2'); styles.fontFamily = 'Helvetica'; ReactDOM.render(<div style={styles} />, container); expect(stubStyle.display).toEqual('none'); expect(stubStyle.fontFamily).toEqual('Arial'); expect(stubStyle.lineHeight).toEqual('1.2'); styles.lineHeight = 0.5; ReactDOM.render(<div style={styles} />, container); expect(stubStyle.display).toEqual('none'); expect(stubStyle.fontFamily).toEqual('Arial'); expect(stubStyle.lineHeight).toEqual('1.2'); ReactDOM.render(<div style={undefined} />, container); expect(stubStyle.display).toBe(''); expect(stubStyle.fontFamily).toBe(''); expect(stubStyle.lineHeight).toBe(''); }); it('should throw when mutating style objects', () => { const style = {border: '1px solid black'}; class App extends React.Component { state = {style: style}; render() { return <div style={this.state.style}>asd</div>; } } ReactTestUtils.renderIntoDocument(<App />); if (__DEV__) { expect(() => (style.position = 'absolute')).toThrow(); } }); it('should warn for unknown prop', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<div foo={() => {}} />, container), ).toErrorDev( 'Warning: Invalid value for prop `foo` on <div> tag. Either remove it ' + 'from the element, or pass a string or number value to keep ' + 'it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ' + '\n in div (at **)', ); }); it('should group multiple unknown prop warnings together', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<div foo={() => {}} baz={() => {}} />, container), ).toErrorDev( 'Warning: Invalid values for props `foo`, `baz` on <div> tag. Either remove ' + 'them from the element, or pass a string or number value to keep ' + 'them in the DOM. For details, see https://reactjs.org/link/attribute-behavior ' + '\n in div (at **)', ); }); it('should warn for onDblClick prop', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<div onDblClick={() => {}} />, container), ).toErrorDev( 'Warning: Invalid event handler property `onDblClick`. Did you mean `onDoubleClick`?\n in div (at **)', ); }); it('should warn for unknown string event handlers', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<div onUnknown='alert("hack")' />, container), ).toErrorDev( 'Warning: Unknown event handler property `onUnknown`. It will be ignored.\n in div (at **)', ); expect(container.firstChild.hasAttribute('onUnknown')).toBe(false); expect(container.firstChild.onUnknown).toBe(undefined); expect(() => ReactDOM.render(<div onunknown='alert("hack")' />, container), ).toErrorDev( 'Warning: Unknown event handler property `onunknown`. It will be ignored.\n in div (at **)', ); expect(container.firstChild.hasAttribute('onunknown')).toBe(false); expect(container.firstChild.onunknown).toBe(undefined); expect(() => ReactDOM.render(<div on-unknown='alert("hack")' />, container), ).toErrorDev( 'Warning: Unknown event handler property `on-unknown`. It will be ignored.\n in div (at **)', ); expect(container.firstChild.hasAttribute('on-unknown')).toBe(false); expect(container.firstChild['on-unknown']).toBe(undefined); }); it('should warn for unknown function event handlers', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<div onUnknown={function () {}} />, container), ).toErrorDev( 'Warning: Unknown event handler property `onUnknown`. It will be ignored.\n in div (at **)', ); expect(container.firstChild.hasAttribute('onUnknown')).toBe(false); expect(container.firstChild.onUnknown).toBe(undefined); expect(() => ReactDOM.render(<div onunknown={function () {}} />, container), ).toErrorDev( 'Warning: Unknown event handler property `onunknown`. It will be ignored.\n in div (at **)', ); expect(container.firstChild.hasAttribute('onunknown')).toBe(false); expect(container.firstChild.onunknown).toBe(undefined); expect(() => ReactDOM.render(<div on-unknown={function () {}} />, container), ).toErrorDev( 'Warning: Unknown event handler property `on-unknown`. It will be ignored.\n in div (at **)', ); expect(container.firstChild.hasAttribute('on-unknown')).toBe(false); expect(container.firstChild['on-unknown']).toBe(undefined); }); it('should warn for badly cased React attributes', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<div CHILDREN="5" />, container)).toErrorDev( 'Warning: Invalid DOM property `CHILDREN`. Did you mean `children`?\n in div (at **)', ); expect(container.firstChild.getAttribute('CHILDREN')).toBe('5'); }); it('should not warn for "0" as a unitless style value', () => { class Component extends React.Component { render() { return <div style={{margin: '0'}} />; } } ReactTestUtils.renderIntoDocument(<Component />); }); it('should warn nicely about NaN in style', () => { const style = {fontSize: NaN}; const div = document.createElement('div'); expect(() => ReactDOM.render(<span style={style} />, div)).toErrorDev( 'Warning: `NaN` is an invalid value for the `fontSize` css style property.' + '\n in span (at **)', ); ReactDOM.render(<span style={style} />, div); }); it('throws with Temporal-like objects as style values', () => { 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 style = {fontSize: new TemporalLike()}; const div = document.createElement('div'); const test = () => ReactDOM.render(<span style={style} />, div); expect(() => expect(test).toThrowError(new TypeError('prod message')), ).toErrorDev( 'Warning: The provided `fontSize` CSS property is an unsupported type TemporalLike.' + ' This value must be coerced to a string before using it here.', ); }); it('should update styles if initially null', () => { let styles = null; const container = document.createElement('div'); ReactDOM.render(<div style={styles} />, container); const stubStyle = container.firstChild.style; styles = {display: 'block'}; ReactDOM.render(<div style={styles} />, container); expect(stubStyle.display).toEqual('block'); }); it('should update styles if updated to null multiple times', () => { let styles = null; const container = document.createElement('div'); ReactDOM.render(<div style={styles} />, container); styles = {display: 'block'}; const stubStyle = container.firstChild.style; ReactDOM.render(<div style={styles} />, container); expect(stubStyle.display).toEqual('block'); ReactDOM.render(<div style={null} />, container); expect(stubStyle.display).toEqual(''); ReactDOM.render(<div style={styles} />, container); expect(stubStyle.display).toEqual('block'); ReactDOM.render(<div style={null} />, container); expect(stubStyle.display).toEqual(''); }); it('should allow named slot projection on both web components and regular DOM elements', () => { const container = document.createElement('div'); ReactDOM.render( <my-component> <my-second-component slot="first" /> <button slot="second">Hello</button> </my-component>, container, ); const lightDOM = container.firstChild.childNodes; expect(lightDOM[0].getAttribute('slot')).toBe('first'); expect(lightDOM[1].getAttribute('slot')).toBe('second'); }); it('should skip reserved props on web components', () => { const container = document.createElement('div'); ReactDOM.render( <my-component children={['foo']} suppressContentEditableWarning={true} suppressHydrationWarning={true} />, container, ); expect(container.firstChild.hasAttribute('children')).toBe(false); expect( container.firstChild.hasAttribute('suppressContentEditableWarning'), ).toBe(false); expect( container.firstChild.hasAttribute('suppressHydrationWarning'), ).toBe(false); ReactDOM.render( <my-component children={['bar']} suppressContentEditableWarning={false} suppressHydrationWarning={false} />, container, ); expect(container.firstChild.hasAttribute('children')).toBe(false); expect( container.firstChild.hasAttribute('suppressContentEditableWarning'), ).toBe(false); expect( container.firstChild.hasAttribute('suppressHydrationWarning'), ).toBe(false); }); it('should skip dangerouslySetInnerHTML on web components', () => { const container = document.createElement('div'); ReactDOM.render( <my-component dangerouslySetInnerHTML={{__html: 'hi'}} />, container, ); expect(container.firstChild.hasAttribute('dangerouslySetInnerHTML')).toBe( false, ); ReactDOM.render( <my-component dangerouslySetInnerHTML={{__html: 'bye'}} />, container, ); expect(container.firstChild.hasAttribute('dangerouslySetInnerHTML')).toBe( false, ); }); it('should render null and undefined as empty but print other falsy values', () => { const container = document.createElement('div'); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: 'textContent'}} />, container, ); expect(container.textContent).toEqual('textContent'); ReactDOM.render(<div dangerouslySetInnerHTML={{__html: 0}} />, container); expect(container.textContent).toEqual('0'); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: false}} />, container, ); expect(container.textContent).toEqual('false'); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: ''}} />, container, ); expect(container.textContent).toEqual(''); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: null}} />, container, ); expect(container.textContent).toEqual(''); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: undefined}} />, container, ); expect(container.textContent).toEqual(''); }); it('should remove attributes', () => { const container = document.createElement('div'); ReactDOM.render(<img height="17" />, container); expect(container.firstChild.hasAttribute('height')).toBe(true); ReactDOM.render(<img />, container); expect(container.firstChild.hasAttribute('height')).toBe(false); }); it('should remove properties', () => { const container = document.createElement('div'); ReactDOM.render(<div className="monkey" />, container); expect(container.firstChild.className).toEqual('monkey'); ReactDOM.render(<div />, container); expect(container.firstChild.className).toEqual(''); }); it('should not set null/undefined attributes', () => { const container = document.createElement('div'); // Initial render. ReactDOM.render(<img src={null} data-foo={undefined} />, container); const node = container.firstChild; expect(node.hasAttribute('src')).toBe(false); expect(node.hasAttribute('data-foo')).toBe(false); // Update in one direction. ReactDOM.render(<img src={undefined} data-foo={null} />, container); expect(node.hasAttribute('src')).toBe(false); expect(node.hasAttribute('data-foo')).toBe(false); // Update in another direction. ReactDOM.render(<img src={null} data-foo={undefined} />, container); expect(node.hasAttribute('src')).toBe(false); expect(node.hasAttribute('data-foo')).toBe(false); // Removal. ReactDOM.render(<img />, container); expect(node.hasAttribute('src')).toBe(false); expect(node.hasAttribute('data-foo')).toBe(false); // Addition. ReactDOM.render(<img src={undefined} data-foo={null} />, container); expect(node.hasAttribute('src')).toBe(false); expect(node.hasAttribute('data-foo')).toBe(false); }); if (ReactFeatureFlags.enableFilterEmptyStringAttributesDOM) { it('should not add an empty src attribute', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<img src="" />, container)).toErrorDev( 'An empty string ("") was passed to the src attribute. ' + 'This may cause the browser to download the whole page again over the network. ' + 'To fix this, either do not render the element at all ' + 'or pass null to src instead of an empty string.', ); const node = container.firstChild; expect(node.hasAttribute('src')).toBe(false); ReactDOM.render(<img src="abc" />, container); expect(node.hasAttribute('src')).toBe(true); expect(() => ReactDOM.render(<img src="" />, container)).toErrorDev( 'An empty string ("") was passed to the src attribute. ' + 'This may cause the browser to download the whole page again over the network. ' + 'To fix this, either do not render the element at all ' + 'or pass null to src instead of an empty string.', ); expect(node.hasAttribute('src')).toBe(false); }); it('should not add an empty href attribute', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<link href="" />, container)).toErrorDev( 'An empty string ("") was passed to the href attribute. ' + 'To fix this, either do not render the element at all ' + 'or pass null to href instead of an empty string.', ); const node = container.firstChild; expect(node.hasAttribute('href')).toBe(false); ReactDOM.render(<link href="abc" />, container); expect(node.hasAttribute('href')).toBe(true); expect(() => ReactDOM.render(<link href="" />, container)).toErrorDev( 'An empty string ("") was passed to the href attribute. ' + 'To fix this, either do not render the element at all ' + 'or pass null to href instead of an empty string.', ); expect(node.hasAttribute('href')).toBe(false); }); it('should allow an empty action attribute', () => { const container = document.createElement('div'); ReactDOM.render(<form action="" />, container); const node = container.firstChild; expect(node.getAttribute('action')).toBe(''); ReactDOM.render(<form action="abc" />, container); expect(node.hasAttribute('action')).toBe(true); ReactDOM.render(<form action="" />, container); expect(node.getAttribute('action')).toBe(''); }); it('allows empty string of a formAction to override the default of a parent', () => { const container = document.createElement('div'); ReactDOM.render( <form action="hello"> <button formAction="" />, </form>, container, ); const node = container.firstChild.firstChild; expect(node.hasAttribute('formaction')).toBe(true); expect(node.getAttribute('formaction')).toBe(''); }); it('should not filter attributes for custom elements', () => { const container = document.createElement('div'); ReactDOM.render( <some-custom-element action="" formAction="" href="" src="" />, container, ); const node = container.firstChild; expect(node.hasAttribute('action')).toBe(true); expect(node.hasAttribute('formAction')).toBe(true); expect(node.hasAttribute('href')).toBe(true); expect(node.hasAttribute('src')).toBe(true); }); } it('should apply React-specific aliases to HTML elements', () => { const container = document.createElement('div'); ReactDOM.render(<form acceptCharset="foo" />, container); const node = container.firstChild; // Test attribute initialization. expect(node.getAttribute('accept-charset')).toBe('foo'); expect(node.hasAttribute('acceptCharset')).toBe(false); // Test attribute update. ReactDOM.render(<form acceptCharset="boo" />, container); expect(node.getAttribute('accept-charset')).toBe('boo'); expect(node.hasAttribute('acceptCharset')).toBe(false); // Test attribute removal by setting to null. ReactDOM.render(<form acceptCharset={null} />, container); expect(node.hasAttribute('accept-charset')).toBe(false); expect(node.hasAttribute('acceptCharset')).toBe(false); // Restore. ReactDOM.render(<form acceptCharset="foo" />, container); expect(node.getAttribute('accept-charset')).toBe('foo'); expect(node.hasAttribute('acceptCharset')).toBe(false); // Test attribute removal by setting to undefined. ReactDOM.render(<form acceptCharset={undefined} />, container); expect(node.hasAttribute('accept-charset')).toBe(false); expect(node.hasAttribute('acceptCharset')).toBe(false); // Restore. ReactDOM.render(<form acceptCharset="foo" />, container); expect(node.getAttribute('accept-charset')).toBe('foo'); expect(node.hasAttribute('acceptCharset')).toBe(false); // Test attribute removal. ReactDOM.render(<form />, container); expect(node.hasAttribute('accept-charset')).toBe(false); expect(node.hasAttribute('acceptCharset')).toBe(false); }); it('should apply React-specific aliases to SVG elements', () => { const container = document.createElement('div'); ReactDOM.render(<svg arabicForm="foo" />, container); const node = container.firstChild; // Test attribute initialization. expect(node.getAttribute('arabic-form')).toBe('foo'); expect(node.hasAttribute('arabicForm')).toBe(false); // Test attribute update. ReactDOM.render(<svg arabicForm="boo" />, container); expect(node.getAttribute('arabic-form')).toBe('boo'); expect(node.hasAttribute('arabicForm')).toBe(false); // Test attribute removal by setting to null. ReactDOM.render(<svg arabicForm={null} />, container); expect(node.hasAttribute('arabic-form')).toBe(false); expect(node.hasAttribute('arabicForm')).toBe(false); // Restore. ReactDOM.render(<svg arabicForm="foo" />, container); expect(node.getAttribute('arabic-form')).toBe('foo'); expect(node.hasAttribute('arabicForm')).toBe(false); // Test attribute removal by setting to undefined. ReactDOM.render(<svg arabicForm={undefined} />, container); expect(node.hasAttribute('arabic-form')).toBe(false); expect(node.hasAttribute('arabicForm')).toBe(false); // Restore. ReactDOM.render(<svg arabicForm="foo" />, container); expect(node.getAttribute('arabic-form')).toBe('foo'); expect(node.hasAttribute('arabicForm')).toBe(false); // Test attribute removal. ReactDOM.render(<svg />, container); expect(node.hasAttribute('arabic-form')).toBe(false); expect(node.hasAttribute('arabicForm')).toBe(false); }); it('should properly update custom attributes on custom elements', () => { const container = document.createElement('div'); ReactDOM.render(<some-custom-element foo="bar" />, container); ReactDOM.render(<some-custom-element bar="buzz" />, container); const node = container.firstChild; expect(node.hasAttribute('foo')).toBe(false); expect(node.getAttribute('bar')).toBe('buzz'); }); it('should not apply React-specific aliases to custom elements', () => { const container = document.createElement('div'); ReactDOM.render(<some-custom-element arabicForm="foo" />, container); const node = container.firstChild; // Should not get transformed to arabic-form as SVG would be. expect(node.getAttribute('arabicForm')).toBe('foo'); expect(node.hasAttribute('arabic-form')).toBe(false); // Test attribute update. ReactDOM.render(<some-custom-element arabicForm="boo" />, container); expect(node.getAttribute('arabicForm')).toBe('boo'); // Test attribute removal and addition. ReactDOM.render(<some-custom-element acceptCharset="buzz" />, container); // Verify the previous attribute was removed. expect(node.hasAttribute('arabicForm')).toBe(false); // Should not get transformed to accept-charset as HTML would be. expect(node.getAttribute('acceptCharset')).toBe('buzz'); expect(node.hasAttribute('accept-charset')).toBe(false); }); it('should clear a single style prop when changing `style`', () => { let styles = {display: 'none', color: 'red'}; const container = document.createElement('div'); ReactDOM.render(<div style={styles} />, container); const stubStyle = container.firstChild.style; styles = {color: 'green'}; ReactDOM.render(<div style={styles} />, container); expect(stubStyle.display).toEqual(''); expect(stubStyle.color).toEqual('green'); }); it('should reject attribute key injection attack on markup for regular DOM (SSR)', () => { expect(() => { for (let i = 0; i < 3; i++) { const element1 = React.createElement( 'div', {'blah" onclick="beevil" noise="hi': 'selected'}, null, ); const element2 = React.createElement( 'div', {'></div><script>alert("hi")</script>': 'selected'}, null, ); const result1 = ReactDOMServer.renderToString(element1); const result2 = ReactDOMServer.renderToString(element2); expect(result1.toLowerCase()).not.toContain('onclick'); expect(result2.toLowerCase()).not.toContain('script'); } }).toErrorDev([ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`', 'Warning: Invalid attribute name: `></div><script>alert("hi")</script>`', ]); }); it('should reject attribute key injection attack on markup for custom elements (SSR)', () => { expect(() => { for (let i = 0; i < 3; i++) { const element1 = React.createElement( 'x-foo-component', {'blah" onclick="beevil" noise="hi': 'selected'}, null, ); const element2 = React.createElement( 'x-foo-component', {'></x-foo-component><script>alert("hi")</script>': 'selected'}, null, ); const result1 = ReactDOMServer.renderToString(element1); const result2 = ReactDOMServer.renderToString(element2); expect(result1.toLowerCase()).not.toContain('onclick'); expect(result2.toLowerCase()).not.toContain('script'); } }).toErrorDev([ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`', 'Warning: Invalid attribute name: `></x-foo-component><script>alert("hi")</script>`', ]); }); it('should reject attribute key injection attack on mount for regular DOM', () => { expect(() => { for (let i = 0; i < 3; i++) { const container = document.createElement('div'); ReactDOM.render( React.createElement( 'div', {'blah" onclick="beevil" noise="hi': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); ReactDOM.unmountComponentAtNode(container); ReactDOM.render( React.createElement( 'div', {'></div><script>alert("hi")</script>': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); } }).toErrorDev([ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`', 'Warning: Invalid attribute name: `></div><script>alert("hi")</script>`', ]); }); it('should reject attribute key injection attack on mount for custom elements', () => { expect(() => { for (let i = 0; i < 3; i++) { const container = document.createElement('div'); ReactDOM.render( React.createElement( 'x-foo-component', {'blah" onclick="beevil" noise="hi': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); ReactDOM.unmountComponentAtNode(container); ReactDOM.render( React.createElement( 'x-foo-component', {'></x-foo-component><script>alert("hi")</script>': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); } }).toErrorDev([ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`', 'Warning: Invalid attribute name: `></x-foo-component><script>alert("hi")</script>`', ]); }); it('should reject attribute key injection attack on update for regular DOM', () => { expect(() => { for (let i = 0; i < 3; i++) { const container = document.createElement('div'); const beforeUpdate = React.createElement('div', {}, null); ReactDOM.render(beforeUpdate, container); ReactDOM.render( React.createElement( 'div', {'blah" onclick="beevil" noise="hi': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); ReactDOM.render( React.createElement( 'div', {'></div><script>alert("hi")</script>': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); } }).toErrorDev([ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`', 'Warning: Invalid attribute name: `></div><script>alert("hi")</script>`', ]); }); it('should reject attribute key injection attack on update for custom elements', () => { expect(() => { for (let i = 0; i < 3; i++) { const container = document.createElement('div'); const beforeUpdate = React.createElement('x-foo-component', {}, null); ReactDOM.render(beforeUpdate, container); ReactDOM.render( React.createElement( 'x-foo-component', {'blah" onclick="beevil" noise="hi': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); ReactDOM.render( React.createElement( 'x-foo-component', {'></x-foo-component><script>alert("hi")</script>': 'selected'}, null, ), container, ); expect(container.firstChild.attributes.length).toBe(0); } }).toErrorDev([ 'Warning: Invalid attribute name: `blah" onclick="beevil" noise="hi`', 'Warning: Invalid attribute name: `></x-foo-component><script>alert("hi")</script>`', ]); }); it('should update arbitrary attributes for tags containing dashes', () => { const container = document.createElement('div'); const beforeUpdate = React.createElement('x-foo-component', {}, null); ReactDOM.render(beforeUpdate, container); const afterUpdate = <x-foo-component myattr="myval" />; ReactDOM.render(afterUpdate, container); expect(container.childNodes[0].getAttribute('myattr')).toBe('myval'); }); it('should clear all the styles when removing `style`', () => { const styles = {display: 'none', color: 'red'}; const container = document.createElement('div'); ReactDOM.render(<div style={styles} />, container); const stubStyle = container.firstChild.style; ReactDOM.render(<div />, container); expect(stubStyle.display).toEqual(''); expect(stubStyle.color).toEqual(''); }); it('should update styles when `style` changes from null to object', () => { const container = document.createElement('div'); const styles = {color: 'red'}; ReactDOM.render(<div style={styles} />, container); ReactDOM.render(<div />, container); ReactDOM.render(<div style={styles} />, container); const stubStyle = container.firstChild.style; expect(stubStyle.color).toEqual('red'); }); it('should not reset innerHTML for when children is null', () => { const container = document.createElement('div'); ReactDOM.render(<div />, container); container.firstChild.innerHTML = 'bonjour'; expect(container.firstChild.innerHTML).toEqual('bonjour'); ReactDOM.render(<div />, container); expect(container.firstChild.innerHTML).toEqual('bonjour'); }); it('should reset innerHTML when switching from a direct text child to an empty child', () => { const transitionToValues = [null, undefined, false]; transitionToValues.forEach(transitionToValue => { const container = document.createElement('div'); ReactDOM.render(<div>bonjour</div>, container); expect(container.firstChild.innerHTML).toEqual('bonjour'); ReactDOM.render(<div>{transitionToValue}</div>, container); expect(container.firstChild.innerHTML).toEqual(''); }); }); it('should empty element when removing innerHTML', () => { const container = document.createElement('div'); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: ':)'}} />, container, ); expect(container.firstChild.innerHTML).toEqual(':)'); ReactDOM.render(<div />, container); expect(container.firstChild.innerHTML).toEqual(''); }); it('should transition from string content to innerHTML', () => { const container = document.createElement('div'); ReactDOM.render(<div>hello</div>, container); expect(container.firstChild.innerHTML).toEqual('hello'); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: 'goodbye'}} />, container, ); expect(container.firstChild.innerHTML).toEqual('goodbye'); }); it('should transition from innerHTML to string content', () => { const container = document.createElement('div'); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: 'bonjour'}} />, container, ); expect(container.firstChild.innerHTML).toEqual('bonjour'); ReactDOM.render(<div>adieu</div>, container); expect(container.firstChild.innerHTML).toEqual('adieu'); }); it('should transition from innerHTML to children in nested el', () => { const container = document.createElement('div'); ReactDOM.render( <div> <div dangerouslySetInnerHTML={{__html: 'bonjour'}} /> </div>, container, ); expect(container.textContent).toEqual('bonjour'); ReactDOM.render( <div> <div> <span>adieu</span> </div> </div>, container, ); expect(container.textContent).toEqual('adieu'); }); it('should transition from children to innerHTML in nested el', () => { const container = document.createElement('div'); ReactDOM.render( <div> <div> <span>adieu</span> </div> </div>, container, ); expect(container.textContent).toEqual('adieu'); ReactDOM.render( <div> <div dangerouslySetInnerHTML={{__html: 'bonjour'}} /> </div>, container, ); expect(container.textContent).toEqual('bonjour'); }); it('should not incur unnecessary DOM mutations for attributes', () => { const container = document.createElement('div'); ReactDOM.render(<div id="" />, container); const node = container.firstChild; const nodeSetAttribute = node.setAttribute; node.setAttribute = jest.fn(); node.setAttribute.mockImplementation(nodeSetAttribute); const nodeRemoveAttribute = node.removeAttribute; node.removeAttribute = jest.fn(); node.removeAttribute.mockImplementation(nodeRemoveAttribute); ReactDOM.render(<div id="" />, container); expect(node.setAttribute).toHaveBeenCalledTimes(0); expect(node.removeAttribute).toHaveBeenCalledTimes(0); ReactDOM.render(<div id="foo" />, container); expect(node.setAttribute).toHaveBeenCalledTimes(1); expect(node.removeAttribute).toHaveBeenCalledTimes(0); ReactDOM.render(<div id="foo" />, container); expect(node.setAttribute).toHaveBeenCalledTimes(1); expect(node.removeAttribute).toHaveBeenCalledTimes(0); ReactDOM.render(<div />, container); expect(node.setAttribute).toHaveBeenCalledTimes(1); expect(node.removeAttribute).toHaveBeenCalledTimes(1); ReactDOM.render(<div id="" />, container); expect(node.setAttribute).toHaveBeenCalledTimes(2); expect(node.removeAttribute).toHaveBeenCalledTimes(1); ReactDOM.render(<div />, container); expect(node.setAttribute).toHaveBeenCalledTimes(2); expect(node.removeAttribute).toHaveBeenCalledTimes(2); }); it('should not incur unnecessary DOM mutations for string properties', () => { const container = document.createElement('div'); ReactDOM.render(<div value="" />, container); const node = container.firstChild; const nodeValueSetter = jest.fn(); const oldSetAttribute = node.setAttribute.bind(node); node.setAttribute = function (key, value) { oldSetAttribute(key, value); nodeValueSetter(key, value); }; ReactDOM.render(<div value="foo" />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); ReactDOM.render(<div value="foo" />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); ReactDOM.render(<div />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); ReactDOM.render(<div value={null} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); ReactDOM.render(<div value="" />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(2); ReactDOM.render(<div />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(2); }); it('should not incur unnecessary DOM mutations for controlled string properties', () => { function onChange() {} const container = document.createElement('div'); ReactDOM.render(<input value="" onChange={onChange} />, container); const node = container.firstChild; let nodeValue = ''; const nodeValueSetter = jest.fn(); Object.defineProperty(node, 'value', { get: function () { return nodeValue; }, set: nodeValueSetter.mockImplementation(function (newValue) { nodeValue = newValue; }), }); ReactDOM.render(<input value="foo" onChange={onChange} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); ReactDOM.render( <input value="foo" data-unrelated={true} onChange={onChange} />, container, ); expect(nodeValueSetter).toHaveBeenCalledTimes(1); expect(() => { ReactDOM.render(<input onChange={onChange} />, container); }).toErrorDev( 'A component is changing a controlled input to be uncontrolled. This is likely caused by ' + 'the value changing from a defined to undefined, which should not happen. Decide between ' + 'using a controlled or uncontrolled input element for the lifetime of the component.', ); expect(nodeValueSetter).toHaveBeenCalledTimes(1); expect(() => { ReactDOM.render(<input value={null} onChange={onChange} />, container); }).toErrorDev( 'value` prop on `input` should not be null. Consider using an empty string to clear the ' + 'component or `undefined` for uncontrolled components.', ); expect(nodeValueSetter).toHaveBeenCalledTimes(1); expect(() => { ReactDOM.render(<input value="" onChange={onChange} />, container); }).toErrorDev( ' A component is changing an uncontrolled input to be controlled. This is likely caused by ' + 'the value changing from undefined to a defined value, which should not happen. Decide between ' + 'using a controlled or uncontrolled input element for the lifetime of the component.', ); expect(nodeValueSetter).toHaveBeenCalledTimes(2); ReactDOM.render(<input onChange={onChange} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(2); }); it('should not incur unnecessary DOM mutations for boolean properties', () => { const container = document.createElement('div'); ReactDOM.render(<audio muted={true} />, container); const node = container.firstChild; let nodeValue = true; const nodeValueSetter = jest.fn(); Object.defineProperty(node, 'muted', { get: function () { return nodeValue; }, set: nodeValueSetter.mockImplementation(function (newValue) { nodeValue = newValue; }), }); ReactDOM.render(<audio muted={true} data-unrelated="yes" />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(0); ReactDOM.render(<audio muted={false} data-unrelated="ok" />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); }); it('should ignore attribute list for elements with the "is" attribute', () => { const container = document.createElement('div'); ReactDOM.render(<button is="test" cowabunga="chevynova" />, container); expect(container.firstChild.hasAttribute('cowabunga')).toBe(true); }); it('should warn about non-string "is" attribute', () => { const container = document.createElement('div'); expect(() => ReactDOM.render(<button is={function () {}} />, container), ).toErrorDev( 'Received a `function` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', ); }); it('should not update when switching between null/undefined', () => { const container = document.createElement('div'); const node = ReactDOM.render(<div />, container); const setter = jest.fn(); node.setAttribute = setter; ReactDOM.render(<div dir={null} />, container); ReactDOM.render(<div dir={undefined} />, container); ReactDOM.render(<div />, container); expect(setter).toHaveBeenCalledTimes(0); ReactDOM.render(<div dir="ltr" />, container); expect(setter).toHaveBeenCalledTimes(1); }); it('handles multiple child updates without interference', () => { // This test might look like it's just testing ReactMultiChild but the // last bug in this was actually in DOMChildrenOperations so this test // needs to be in some DOM-specific test file. const container = document.createElement('div'); // ABCD ReactDOM.render( <div> <div key="one"> <div key="A">A</div> <div key="B">B</div> </div> <div key="two"> <div key="C">C</div> <div key="D">D</div> </div> </div>, container, ); // BADC ReactDOM.render( <div> <div key="one"> <div key="B">B</div> <div key="A">A</div> </div> <div key="two"> <div key="D">D</div> <div key="C">C</div> </div> </div>, container, ); expect(container.textContent).toBe('BADC'); }); }); describe('createOpenTagMarkup', () => { function quoteRegexp(str) { return String(str).replace(/([.?*+\^$\[\]\\(){}|-])/g, '\\$1'); } function expectToHaveAttribute(actual, expected) { const [attr, value] = expected; let re = '(?:^|\\s)' + attr + '=[\\\'"]'; if (typeof value !== 'undefined') { re += quoteRegexp(value) + '[\\\'"]'; } expect(actual).toMatch(new RegExp(re)); } function genMarkup(props) { return ReactDOMServer.renderToString(<div {...props} />); } it('should generate the correct markup with className', () => { expectToHaveAttribute(genMarkup({className: 'a'}), ['class', 'a']); expectToHaveAttribute(genMarkup({className: 'a b'}), ['class', 'a b']); expectToHaveAttribute(genMarkup({className: ''}), ['class', '']); }); it('should escape style names and values', () => { expectToHaveAttribute( genMarkup({ style: {'b&ckground': '<3'}, }), ['style', 'b&amp;ckground:&lt;3'], ); }); }); describe('createContentMarkup', () => { function quoteRegexp(str) { return String(str).replace(/([.?*+\^$\[\]\\(){}|-])/g, '\\$1'); } function genMarkup(props) { return ReactDOMServer.renderToString(<div {...props} />); } function toHaveInnerhtml(actual, expected) { const re = quoteRegexp(expected); return new RegExp(re).test(actual); } it('should handle dangerouslySetInnerHTML', () => { const innerHTML = {__html: 'testContent'}; expect( toHaveInnerhtml( genMarkup({dangerouslySetInnerHTML: innerHTML}), 'testContent', ), ).toBe(true); }); }); describe('mountComponent', () => { let mountComponent; beforeEach(() => { mountComponent = function (props) { const container = document.createElement('div'); ReactDOM.render(<div {...props} />, container); }; }); it('should work error event on <source> element', () => { spyOnDevAndProd(console, 'log'); const container = document.createElement('div'); ReactDOM.render( <video> <source src="http://example.org/video" type="video/mp4" onError={e => console.log('onError called')} /> </video>, container, ); const errorEvent = document.createEvent('Event'); errorEvent.initEvent('error', false, false); container.getElementsByTagName('source')[0].dispatchEvent(errorEvent); if (__DEV__) { expect(console.log).toHaveBeenCalledTimes(1); expect(console.log.mock.calls[0][0]).toContain('onError called'); } }); it('should warn for uppercased selfclosing tags', () => { class Container extends React.Component { render() { return React.createElement('BR', null); } } let returnedValue; expect(() => { returnedValue = ReactDOMServer.renderToString(<Container />); }).toErrorDev( '<BR /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', ); // This includes a duplicate tag because we didn't treat this as self-closing. expect(returnedValue).toContain('</BR>'); }); it('should warn on upper case HTML tags, not SVG nor custom tags', () => { ReactTestUtils.renderIntoDocument( React.createElement('svg', null, React.createElement('PATH')), ); ReactTestUtils.renderIntoDocument(React.createElement('CUSTOM-TAG')); expect(() => ReactTestUtils.renderIntoDocument(React.createElement('IMG')), ).toErrorDev( '<IMG /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', ); }); it('should warn on props reserved for future use', () => { expect(() => ReactTestUtils.renderIntoDocument(<div aria="hello" />), ).toErrorDev( 'The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.', ); }); it('should warn if the tag is unrecognized', () => { let realToString; try { realToString = Object.prototype.toString; const wrappedToString = function () { // Emulate browser behavior which is missing in jsdom if (this instanceof window.HTMLUnknownElement) { return '[object HTMLUnknownElement]'; } return realToString.apply(this, arguments); }; Object.prototype.toString = wrappedToString; // eslint-disable-line no-extend-native expect(() => ReactTestUtils.renderIntoDocument(<bar />)).toErrorDev( 'The tag <bar> is unrecognized in this browser', ); // Test deduplication expect(() => ReactTestUtils.renderIntoDocument(<foo />)).toErrorDev( 'The tag <foo> is unrecognized in this browser', ); ReactTestUtils.renderIntoDocument(<foo />); ReactTestUtils.renderIntoDocument(<time />); // Corner case. Make sure out deduplication logic doesn't break with weird tag. expect(() => ReactTestUtils.renderIntoDocument(<hasOwnProperty />), ).toErrorDev([ '<hasOwnProperty /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', 'The tag <hasOwnProperty> is unrecognized in this browser', ]); } finally { Object.prototype.toString = realToString; // eslint-disable-line no-extend-native } }); it('should throw on children for void elements', () => { const container = document.createElement('div'); expect(() => { ReactDOM.render(<input>children</input>, container); }).toThrowError( 'input is a void element tag and must neither have `children` nor ' + 'use `dangerouslySetInnerHTML`.', ); }); it('should throw on dangerouslySetInnerHTML for void elements', () => { const container = document.createElement('div'); expect(() => { ReactDOM.render( <input dangerouslySetInnerHTML={{__html: 'content'}} />, container, ); }).toThrowError( 'input is a void element tag and must neither have `children` nor ' + 'use `dangerouslySetInnerHTML`.', ); }); it('should treat menuitem as a void element but still create the closing tag', () => { // menuitem is not implemented in jsdom, so this triggers the unknown warning error const container = document.createElement('div'); const returnedValue = ReactDOMServer.renderToString( <menu> <menuitem /> </menu>, ); expect(returnedValue).toContain('</menuitem>'); expect(function () { expect(() => { ReactDOM.render( <menu> <menuitem>children</menuitem> </menu>, container, ); }).toErrorDev('The tag <menuitem> is unrecognized in this browser.'); }).toThrowError( 'menuitem is a void element tag and must neither have `children` nor use ' + '`dangerouslySetInnerHTML`.', ); }); it('should validate against multiple children props', () => { expect(function () { mountComponent({children: '', dangerouslySetInnerHTML: ''}); }).toThrowError( '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.', ); }); it('should validate against use of innerHTML', () => { expect(() => mountComponent({innerHTML: '<span>Hi Jim!</span>'}), ).toErrorDev('Directly setting property `innerHTML` is not permitted. '); }); it('should validate against use of innerHTML without case sensitivity', () => { expect(() => mountComponent({innerhtml: '<span>Hi Jim!</span>'}), ).toErrorDev('Directly setting property `innerHTML` is not permitted. '); }); it('should validate use of dangerouslySetInnerHTML', () => { expect(function () { mountComponent({dangerouslySetInnerHTML: '<span>Hi Jim!</span>'}); }).toThrowError( '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.', ); }); it('should validate use of dangerouslySetInnerHTML', () => { expect(function () { mountComponent({dangerouslySetInnerHTML: {foo: 'bar'}}); }).toThrowError( '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.', ); }); it('should allow {__html: null}', () => { expect(function () { mountComponent({dangerouslySetInnerHTML: {__html: null}}); }).not.toThrow(); }); it('should warn about contentEditable and children', () => { expect(() => mountComponent({contentEditable: true, children: ''}), ).toErrorDev( 'Warning: A component is `contentEditable` and contains `children` ' + 'managed by React. It is now your responsibility to guarantee that ' + 'none of those nodes are unexpectedly modified or duplicated. This ' + 'is probably not intentional.\n in div (at **)', ); }); it('should respect suppressContentEditableWarning', () => { mountComponent({ contentEditable: true, children: '', suppressContentEditableWarning: true, }); }); it('should validate against invalid styles', () => { expect(function () { mountComponent({style: 'display: none'}); }).toThrowError( 'The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} " + 'when using JSX.', ); }); it('should throw for children on void elements', () => { class X extends React.Component { render() { return <input>moo</input>; } } const container = document.createElement('div'); expect(() => { ReactDOM.render(<X />, container); }).toThrowError( 'input is a void element tag and must neither have `children` ' + 'nor use `dangerouslySetInnerHTML`.', ); }); it('should support custom elements which extend native elements', () => { const container = document.createElement('div'); spyOnDevAndProd(document, 'createElement'); ReactDOM.render(<div is="custom-div" />, container); expect(document.createElement).toHaveBeenCalledWith('div', { is: 'custom-div', }); }); it('should work load and error events on <image> element in SVG', () => { spyOnDevAndProd(console, 'log'); const container = document.createElement('div'); ReactDOM.render( <svg> <image xlinkHref="http://example.org/image" onError={e => console.log('onError called')} onLoad={e => console.log('onLoad called')} /> </svg>, container, ); const loadEvent = document.createEvent('Event'); const errorEvent = document.createEvent('Event'); loadEvent.initEvent('load', false, false); errorEvent.initEvent('error', false, false); container.getElementsByTagName('image')[0].dispatchEvent(errorEvent); container.getElementsByTagName('image')[0].dispatchEvent(loadEvent); if (__DEV__) { expect(console.log).toHaveBeenCalledTimes(2); expect(console.log.mock.calls[0][0]).toContain('onError called'); expect(console.log.mock.calls[1][0]).toContain('onLoad called'); } }); it('should receive a load event on <link> elements', () => { const container = document.createElement('div'); const onLoad = jest.fn(); ReactDOM.render( <link href="http://example.org/link" onLoad={onLoad} />, container, ); const loadEvent = document.createEvent('Event'); const link = container.getElementsByTagName('link')[0]; loadEvent.initEvent('load', false, false); link.dispatchEvent(loadEvent); expect(onLoad).toHaveBeenCalledTimes(1); }); it('should receive an error event on <link> elements', () => { const container = document.createElement('div'); const onError = jest.fn(); ReactDOM.render( <link href="http://example.org/link" onError={onError} />, container, ); const errorEvent = document.createEvent('Event'); const link = container.getElementsByTagName('link')[0]; errorEvent.initEvent('error', false, false); link.dispatchEvent(errorEvent); expect(onError).toHaveBeenCalledTimes(1); }); }); describe('updateComponent', () => { let container; beforeEach(() => { container = document.createElement('div'); }); it('should warn against children for void elements', () => { ReactDOM.render(<input />, container); expect(function () { ReactDOM.render(<input>children</input>, container); }).toThrowError( 'input is a void element tag and must neither have `children` nor use ' + '`dangerouslySetInnerHTML`.', ); }); it('should warn against dangerouslySetInnerHTML for void elements', () => { ReactDOM.render(<input />, container); expect(function () { ReactDOM.render( <input dangerouslySetInnerHTML={{__html: 'content'}} />, container, ); }).toThrowError( 'input is a void element tag and must neither have `children` nor use ' + '`dangerouslySetInnerHTML`.', ); }); it('should validate against multiple children props', () => { ReactDOM.render(<div />, container); expect(function () { ReactDOM.render( <div children="" dangerouslySetInnerHTML={{__html: ''}} />, container, ); }).toThrowError( 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.', ); }); it('should warn about contentEditable and children', () => { expect(() => { ReactDOM.render( <div contentEditable={true}> <div /> </div>, container, ); }).toErrorDev('contentEditable'); }); it('should validate against invalid styles', () => { ReactDOM.render(<div />, container); expect(function () { ReactDOM.render(<div style={1} />, container); }).toThrowError( 'The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} " + 'when using JSX.', ); }); it('should report component containing invalid styles', () => { class Animal extends React.Component { render() { return <div style={1} />; } } expect(() => { ReactDOM.render(<Animal />, container); }).toThrowError( 'The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} " + 'when using JSX.', ); }); it('should properly escape text content and attributes values', () => { expect( ReactDOMServer.renderToStaticMarkup( React.createElement( 'div', { title: '\'"<>&', style: { textAlign: '\'"<>&', }, }, '\'"<>&', ), ), ).toBe( '<div title="&#x27;&quot;&lt;&gt;&amp;" style="text-align:&#x27;&quot;&lt;&gt;&amp;">' + '&#x27;&quot;&lt;&gt;&amp;' + '</div>', ); }); }); describe('unmountComponent', () => { it('unmounts children before unsetting DOM node info', () => { class Inner extends React.Component { render() { return <span />; } componentWillUnmount() { // Should not throw expect(ReactDOM.findDOMNode(this).nodeName).toBe('SPAN'); } } const container = document.createElement('div'); ReactDOM.render( <div> <Inner /> </div>, container, ); ReactDOM.unmountComponentAtNode(container); }); }); describe('tag sanitization', () => { it('should throw when an invalid tag name is used server-side', () => { const hackzor = React.createElement('script tag'); expect(() => ReactDOMServer.renderToString(hackzor)).toThrowError( 'Invalid tag: script tag', ); }); it('should throw when an attack vector is used server-side', () => { const hackzor = React.createElement('div><img /><div'); expect(() => ReactDOMServer.renderToString(hackzor)).toThrowError( 'Invalid tag: div><img /><div', ); }); it('should throw when an invalid tag name is used', () => { const hackzor = React.createElement('script tag'); expect(() => ReactTestUtils.renderIntoDocument(hackzor)).toThrow(); }); it('should throw when an attack vector is used', () => { const hackzor = React.createElement('div><img /><div'); expect(() => ReactTestUtils.renderIntoDocument(hackzor)).toThrow(); }); }); describe('nesting validation', () => { it('warns on invalid nesting', () => { expect(() => { ReactTestUtils.renderIntoDocument( <div> <tr /> <tr /> </div>, ); }).toErrorDev([ 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' + '<div>.' + '\n in tr (at **)' + '\n in div (at **)', ]); }); it('warns on invalid nesting at root', () => { const p = document.createElement('p'); expect(() => { ReactDOM.render( <span> <p /> </span>, p, ); }).toErrorDev( 'Warning: validateDOMNesting(...): <p> cannot appear as a descendant ' + 'of <p>.' + // There is no outer `p` here because root container is not part of the stack. '\n in p (at **)' + '\n in span (at **)', ); }); it('warns nicely for table rows', () => { class Row extends React.Component { render() { return <tr>x</tr>; } } class Foo extends React.Component { render() { return ( <table> <Row />{' '} </table> ); } } expect(() => ReactTestUtils.renderIntoDocument(<Foo />)).toErrorDev([ 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' + '<table>. Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated ' + 'by the browser.' + '\n in tr (at **)' + '\n in Row (at **)' + '\n in table (at **)' + '\n in Foo (at **)', 'Warning: validateDOMNesting(...): Text nodes cannot appear as a ' + 'child of <tr>.' + '\n in tr (at **)' + '\n in Row (at **)' + '\n in table (at **)' + '\n in Foo (at **)', 'Warning: validateDOMNesting(...): Whitespace text nodes cannot ' + "appear as a child of <table>. Make sure you don't have any extra " + 'whitespace between tags on each line of your source code.' + '\n in table (at **)' + '\n in Foo (at **)', ]); }); it('warns nicely for updating table rows to use text', () => { const container = document.createElement('div'); function Row({children}) { return <tr>{children}</tr>; } function Foo({children}) { return <table>{children}</table>; } // First is fine. ReactDOM.render(<Foo />, container); expect(() => ReactDOM.render(<Foo> </Foo>, container)).toErrorDev([ 'Warning: validateDOMNesting(...): Whitespace text nodes cannot ' + "appear as a child of <table>. Make sure you don't have any extra " + 'whitespace between tags on each line of your source code.' + '\n in table (at **)' + '\n in Foo (at **)', ]); ReactDOM.render( <Foo> <tbody> <Row /> </tbody> </Foo>, container, ); expect(() => ReactDOM.render( <Foo> <tbody> <Row>text</Row> </tbody> </Foo>, container, ), ).toErrorDev([ 'Warning: validateDOMNesting(...): Text nodes cannot appear as a ' + 'child of <tr>.' + '\n in tr (at **)' + '\n in Row (at **)' + '\n in tbody (at **)' + '\n in table (at **)' + '\n in Foo (at **)', ]); }); it('gives useful context in warnings', () => { function Row() { return <tr />; } function FancyRow() { return <Row />; } function Viz1() { return ( <table> <FancyRow /> </table> ); } function App1() { return <Viz1 />; } expect(() => ReactTestUtils.renderIntoDocument(<App1 />)).toErrorDev( '\n in tr (at **)' + '\n in Row (at **)' + '\n in FancyRow (at **)' + '\n in table (at **)' + '\n in Viz1 (at **)', ); }); it('gives useful context in warnings 2', () => { function Row() { return <tr />; } function FancyRow() { return <Row />; } class Table extends React.Component { render() { return <table>{this.props.children}</table>; } } class FancyTable extends React.Component { render() { return <Table>{this.props.children}</Table>; } } function Viz2() { return ( <FancyTable> <FancyRow /> </FancyTable> ); } function App2() { return <Viz2 />; } expect(() => ReactTestUtils.renderIntoDocument(<App2 />)).toErrorDev( '\n in tr (at **)' + '\n in Row (at **)' + '\n in FancyRow (at **)' + '\n in table (at **)' + '\n in Table (at **)' + '\n in FancyTable (at **)' + '\n in Viz2 (at **)', ); }); it('gives useful context in warnings 3', () => { function Row() { return <tr />; } function FancyRow() { return <Row />; } class Table extends React.Component { render() { return <table>{this.props.children}</table>; } } class FancyTable extends React.Component { render() { return <Table>{this.props.children}</Table>; } } expect(() => { ReactTestUtils.renderIntoDocument( <FancyTable> <FancyRow /> </FancyTable>, ); }).toErrorDev( '\n in tr (at **)' + '\n in Row (at **)' + '\n in FancyRow (at **)' + '\n in table (at **)' + '\n in Table (at **)' + '\n in FancyTable (at **)', ); }); it('gives useful context in warnings 4', () => { function Row() { return <tr />; } function FancyRow() { return <Row />; } expect(() => { ReactTestUtils.renderIntoDocument( <table> <FancyRow /> </table>, ); }).toErrorDev( '\n in tr (at **)' + '\n in Row (at **)' + '\n in FancyRow (at **)' + '\n in table (at **)', ); }); it('gives useful context in warnings 5', () => { class Table extends React.Component { render() { return <table>{this.props.children}</table>; } } class FancyTable extends React.Component { render() { return <Table>{this.props.children}</Table>; } } expect(() => { ReactTestUtils.renderIntoDocument( <FancyTable> <tr /> </FancyTable>, ); }).toErrorDev( '\n in tr (at **)' + '\n in table (at **)' + '\n in Table (at **)' + '\n in FancyTable (at **)', ); class Link extends React.Component { render() { return <a>{this.props.children}</a>; } } expect(() => { ReactTestUtils.renderIntoDocument( <Link> <div> <Link /> </div> </Link>, ); }).toErrorDev( '\n in a (at **)' + '\n in Link (at **)' + '\n in div (at **)' + '\n in a (at **)' + '\n in Link (at **)', ); }); it('should warn about incorrect casing on properties (ssr)', () => { expect(() => { ReactDOMServer.renderToString( React.createElement('input', {type: 'text', tabindex: '1'}), ); }).toErrorDev('tabIndex'); }); it('should warn about incorrect casing on event handlers (ssr)', () => { expect(() => { ReactDOMServer.renderToString( React.createElement('input', {type: 'text', oninput: '1'}), ); }).toErrorDev( 'Invalid event handler property `oninput`. ' + 'React events use the camelCase naming convention, ' + // Note: we don't know the right event name so we // use a generic one (onClick) as a suggestion. // This is because we don't bundle the event system // on the server. 'for example `onClick`.', ); ReactDOMServer.renderToString( React.createElement('input', {type: 'text', onKeydown: '1'}), ); // We can't warn for `onKeydown` on the server because // there is no way tell if this is a valid event or not // without access to the event system (which we don't bundle). }); it('should warn about incorrect casing on properties', () => { expect(() => { ReactTestUtils.renderIntoDocument( React.createElement('input', {type: 'text', tabindex: '1'}), ); }).toErrorDev('tabIndex'); }); it('should warn about incorrect casing on event handlers', () => { expect(() => { ReactTestUtils.renderIntoDocument( React.createElement('input', {type: 'text', oninput: '1'}), ); }).toErrorDev('onInput'); expect(() => { ReactTestUtils.renderIntoDocument( React.createElement('input', {type: 'text', onKeydown: '1'}), ); }).toErrorDev('onKeyDown'); }); it('should warn about class', () => { expect(() => { ReactTestUtils.renderIntoDocument( React.createElement('div', {class: 'muffins'}), ); }).toErrorDev('className'); }); it('should warn about class (ssr)', () => { expect(() => { ReactDOMServer.renderToString( React.createElement('div', {class: 'muffins'}), ); }).toErrorDev('className'); }); it('should warn about props that are no longer supported', () => { ReactTestUtils.renderIntoDocument(<div />); expect(() => ReactTestUtils.renderIntoDocument(<div onFocusIn={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); expect(() => ReactTestUtils.renderIntoDocument(<div onFocusOut={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); }); it('should warn about props that are no longer supported without case sensitivity', () => { ReactTestUtils.renderIntoDocument(<div />); expect(() => ReactTestUtils.renderIntoDocument(<div onfocusin={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); expect(() => ReactTestUtils.renderIntoDocument(<div onfocusout={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); }); it('should warn about props that are no longer supported (ssr)', () => { ReactDOMServer.renderToString(<div />); expect(() => ReactDOMServer.renderToString(<div onFocusIn={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); expect(() => ReactDOMServer.renderToString(<div onFocusOut={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); }); it('should warn about props that are no longer supported without case sensitivity (ssr)', () => { ReactDOMServer.renderToString(<div />); expect(() => ReactDOMServer.renderToString(<div onfocusin={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); expect(() => ReactDOMServer.renderToString(<div onfocusout={() => {}} />), ).toErrorDev( 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut.', ); }); it('gives source code refs for unknown prop warning', () => { expect(() => ReactTestUtils.renderIntoDocument(<div class="paladin" />), ).toErrorDev( 'Warning: Invalid DOM property `class`. Did you mean `className`?\n in div (at **)', ); expect(() => ReactTestUtils.renderIntoDocument(<input type="text" onclick="1" />), ).toErrorDev( 'Warning: Invalid event handler property `onclick`. Did you mean ' + '`onClick`?\n in input (at **)', ); }); it('gives source code refs for unknown prop warning (ssr)', () => { expect(() => ReactDOMServer.renderToString(<div class="paladin" />), ).toErrorDev( 'Warning: Invalid DOM property `class`. Did you mean `className`?\n in div (at **)', ); expect(() => ReactDOMServer.renderToString(<input type="text" oninput="1" />), ).toErrorDev( 'Warning: Invalid event handler property `oninput`. ' + // Note: we don't know the right event name so we // use a generic one (onClick) as a suggestion. // This is because we don't bundle the event system // on the server. 'React events use the camelCase naming convention, for example `onClick`.' + '\n in input (at **)', ); }); it('gives source code refs for unknown prop warning for update render', () => { const container = document.createElement('div'); ReactTestUtils.renderIntoDocument(<div className="paladin" />, container); expect(() => ReactTestUtils.renderIntoDocument(<div class="paladin" />, container), ).toErrorDev( 'Warning: Invalid DOM property `class`. Did you mean `className`?\n in div (at **)', ); }); it('gives source code refs for unknown prop warning for exact elements', () => { expect(() => ReactTestUtils.renderIntoDocument( <div className="foo1"> <span class="foo2" /> <div onClick={() => {}} /> <strong onclick={() => {}} /> <div className="foo5" /> <div className="foo6" /> </div>, ), ).toErrorDev([ 'Invalid DOM property `class`. Did you mean `className`?\n in span (at **)', 'Invalid event handler property `onclick`. Did you mean `onClick`?\n in strong (at **)', ]); }); it('gives source code refs for unknown prop warning for exact elements (ssr)', () => { expect(() => ReactDOMServer.renderToString( <div className="foo1"> <span class="foo2" /> <div onClick="foo3" /> <strong onclick="foo4" /> <div className="foo5" /> <div className="foo6" /> </div>, ), ).toErrorDev([ 'Invalid DOM property `class`. Did you mean `className`?\n in span (at **)', 'Invalid event handler property `onclick`. ' + 'React events use the camelCase naming convention, for example `onClick`.' + '\n in strong (at **)', ]); }); it('gives source code refs for unknown prop warning for exact elements in composition', () => { const container = document.createElement('div'); class Parent extends React.Component { render() { return ( <div> <Child1 /> <Child2 /> <Child3 /> <Child4 /> </div> ); } } class Child1 extends React.Component { render() { return <span class="paladin">Child1</span>; } } class Child2 extends React.Component { render() { return <div>Child2</div>; } } class Child3 extends React.Component { render() { return <strong onclick="1">Child3</strong>; } } class Child4 extends React.Component { render() { return <div>Child4</div>; } } expect(() => ReactTestUtils.renderIntoDocument(<Parent />, container), ).toErrorDev([ 'Invalid DOM property `class`. Did you mean `className`?\n in span (at **)', 'Invalid event handler property `onclick`. Did you mean `onClick`?\n in strong (at **)', ]); }); it('gives source code refs for unknown prop warning for exact elements in composition (ssr)', () => { const container = document.createElement('div'); class Parent extends React.Component { render() { return ( <div> <Child1 /> <Child2 /> <Child3 /> <Child4 /> </div> ); } } class Child1 extends React.Component { render() { return <span class="paladin">Child1</span>; } } class Child2 extends React.Component { render() { return <div>Child2</div>; } } class Child3 extends React.Component { render() { return <strong onclick="1">Child3</strong>; } } class Child4 extends React.Component { render() { return <div>Child4</div>; } } expect(() => ReactDOMServer.renderToString(<Parent />, container), ).toErrorDev([ 'Invalid DOM property `class`. Did you mean `className`?\n in span (at **)', 'Invalid event handler property `onclick`. ' + 'React events use the camelCase naming convention, for example `onClick`.' + '\n in strong (at **)', ]); }); it('should suggest property name if available', () => { expect(() => ReactTestUtils.renderIntoDocument( React.createElement('label', {for: 'test'}), ), ).toErrorDev( 'Warning: Invalid DOM property `for`. Did you mean `htmlFor`?\n in label', ); expect(() => ReactTestUtils.renderIntoDocument( React.createElement('input', {type: 'text', autofocus: true}), ), ).toErrorDev( 'Warning: Invalid DOM property `autofocus`. Did you mean `autoFocus`?\n in input', ); }); it('should suggest property name if available (ssr)', () => { expect(() => ReactDOMServer.renderToString( React.createElement('label', {for: 'test'}), ), ).toErrorDev( 'Warning: Invalid DOM property `for`. Did you mean `htmlFor`?\n in label', ); expect(() => ReactDOMServer.renderToString( React.createElement('input', {type: 'text', autofocus: true}), ), ).toErrorDev( 'Warning: Invalid DOM property `autofocus`. Did you mean `autoFocus`?\n in input', ); }); }); describe('whitespace', () => { it('renders innerHTML and preserves whitespace', () => { const container = document.createElement('div'); const html = '\n \t <span> \n testContent \t </span> \n \t'; const elem = <div dangerouslySetInnerHTML={{__html: html}} />; ReactDOM.render(elem, container); expect(container.firstChild.innerHTML).toBe(html); }); it('render and then updates innerHTML and preserves whitespace', () => { const container = document.createElement('div'); const html = '\n \t <span> \n testContent1 \t </span> \n \t'; const elem = <div dangerouslySetInnerHTML={{__html: html}} />; ReactDOM.render(elem, container); const html2 = '\n \t <div> \n testContent2 \t </div> \n \t'; const elem2 = <div dangerouslySetInnerHTML={{__html: html2}} />; ReactDOM.render(elem2, container); expect(container.firstChild.innerHTML).toBe(html2); }); }); describe('Attributes with aliases', function () { it('sets aliased attributes on HTML attributes', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div class="test" />); }).toErrorDev( 'Warning: Invalid DOM property `class`. Did you mean `className`?', ); expect(el.className).toBe('test'); }); it('sets incorrectly cased aliased attributes on HTML attributes with a warning', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div cLASS="test" />); }).toErrorDev( 'Warning: Invalid DOM property `cLASS`. Did you mean `className`?', ); expect(el.className).toBe('test'); }); it('sets aliased attributes on SVG elements with a warning', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument( <svg> <text arabic-form="initial" /> </svg>, ); }).toErrorDev( 'Warning: Invalid DOM property `arabic-form`. Did you mean `arabicForm`?', ); const text = el.querySelector('text'); expect(text.hasAttribute('arabic-form')).toBe(true); }); it('sets aliased attributes on custom elements', function () { const el = ReactTestUtils.renderIntoDocument( <div is="custom-element" class="test" />, ); expect(el.getAttribute('class')).toBe('test'); }); it('aliased attributes on custom elements with bad casing', function () { const el = ReactTestUtils.renderIntoDocument( <div is="custom-element" claSS="test" />, ); expect(el.getAttribute('class')).toBe('test'); }); it('updates aliased attributes on custom elements', function () { const container = document.createElement('div'); ReactDOM.render(<div is="custom-element" class="foo" />, container); ReactDOM.render(<div is="custom-element" class="bar" />, container); expect(container.firstChild.getAttribute('class')).toBe('bar'); }); }); describe('Custom attributes', function () { it('allows assignment of custom attributes with string values', function () { const el = ReactTestUtils.renderIntoDocument(<div whatever="30" />); expect(el.getAttribute('whatever')).toBe('30'); }); it('removes custom attributes', function () { const container = document.createElement('div'); ReactDOM.render(<div whatever="30" />, container); expect(container.firstChild.getAttribute('whatever')).toBe('30'); ReactDOM.render(<div whatever={null} />, container); expect(container.firstChild.hasAttribute('whatever')).toBe(false); }); it('does not assign a boolean custom attributes as a string', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div whatever={true} />); }).toErrorDev( 'Received `true` for a non-boolean attribute `whatever`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + 'whatever="true" or whatever={value.toString()}.', ); expect(el.hasAttribute('whatever')).toBe(false); }); it('does not assign an implicit boolean custom attributes', function () { let el; expect(() => { // eslint-disable-next-line react/jsx-boolean-value el = ReactTestUtils.renderIntoDocument(<div whatever />); }).toErrorDev( 'Received `true` for a non-boolean attribute `whatever`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + 'whatever="true" or whatever={value.toString()}.', ); expect(el.hasAttribute('whatever')).toBe(false); }); it('assigns a numeric custom attributes as a string', function () { const el = ReactTestUtils.renderIntoDocument(<div whatever={3} />); expect(el.getAttribute('whatever')).toBe('3'); }); it('will not assign a function custom attributes', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div whatever={() => {}} />); }).toErrorDev('Warning: Invalid value for prop `whatever` on <div> tag'); expect(el.hasAttribute('whatever')).toBe(false); }); it('will assign an object custom attributes', function () { const el = ReactTestUtils.renderIntoDocument(<div whatever={{}} />); expect(el.getAttribute('whatever')).toBe('[object Object]'); }); it('allows Temporal-like objects as HTML (they are not coerced to strings first)', function () { 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'; } } // `dangerouslySetInnerHTML` is never coerced to a string, so won't throw // even with a Temporal-like object. const container = document.createElement('div'); ReactDOM.render( <div dangerouslySetInnerHTML={{__html: new TemporalLike()}} />, container, ); expect(container.firstChild.innerHTML).toEqual('2020-01-01'); }); it('allows cased data attributes', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div data-fooBar="true" />); }).toErrorDev( 'React does not recognize the `data-fooBar` prop on a DOM element. ' + 'If you intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `data-foobar` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.\n' + ' in div (at **)', ); expect(el.getAttribute('data-foobar')).toBe('true'); }); it('allows cased custom attributes', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div fooBar="true" />); }).toErrorDev( 'React does not recognize the `fooBar` prop on a DOM element. ' + 'If you intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `foobar` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.\n' + ' in div (at **)', ); expect(el.getAttribute('foobar')).toBe('true'); }); it('warns on NaN attributes', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div whatever={NaN} />); }).toErrorDev( 'Warning: Received NaN for the `whatever` attribute. If this is ' + 'expected, cast the value to a string.\n in div', ); expect(el.getAttribute('whatever')).toBe('NaN'); }); it('removes a property when it becomes invalid', function () { const container = document.createElement('div'); ReactDOM.render(<div whatever={0} />, container); expect(() => ReactDOM.render(<div whatever={() => {}} />, container), ).toErrorDev('Warning: Invalid value for prop `whatever` on <div> tag.'); const el = container.firstChild; expect(el.hasAttribute('whatever')).toBe(false); }); it('warns on bad casing of known HTML attributes', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div SiZe="30" />); }).toErrorDev( 'Warning: Invalid DOM property `SiZe`. Did you mean `size`?', ); expect(el.getAttribute('size')).toBe('30'); }); }); describe('Object stringification', function () { it('allows objects on known properties', function () { const el = ReactTestUtils.renderIntoDocument(<div acceptCharset={{}} />); expect(el.getAttribute('accept-charset')).toBe('[object Object]'); }); it('should pass objects as attributes if they define toString', () => { const obj = { toString() { return 'hello'; }, }; const container = document.createElement('div'); ReactDOM.render(<img src={obj} />, container); expect(container.firstChild.src).toBe('http://localhost/hello'); ReactDOM.render(<svg arabicForm={obj} />, container); expect(container.firstChild.getAttribute('arabic-form')).toBe('hello'); ReactDOM.render(<div unknown={obj} />, container); expect(container.firstChild.getAttribute('unknown')).toBe('hello'); }); it('passes objects on known SVG attributes if they do not define toString', () => { const obj = {}; const container = document.createElement('div'); ReactDOM.render(<svg arabicForm={obj} />, container); expect(container.firstChild.getAttribute('arabic-form')).toBe( '[object Object]', ); }); it('passes objects on custom attributes if they do not define toString', () => { const obj = {}; const container = document.createElement('div'); ReactDOM.render(<div unknown={obj} />, container); expect(container.firstChild.getAttribute('unknown')).toBe( '[object Object]', ); }); it('allows objects that inherit a custom toString method', function () { const parent = {toString: () => 'hello.jpg'}; const child = Object.create(parent); const el = ReactTestUtils.renderIntoDocument(<img src={child} />); expect(el.src).toBe('http://localhost/hello.jpg'); }); it('assigns ajaxify (an important internal FB attribute)', function () { const options = {toString: () => 'ajaxy'}; const el = ReactTestUtils.renderIntoDocument(<div ajaxify={options} />); expect(el.getAttribute('ajaxify')).toBe('ajaxy'); }); }); describe('String boolean attributes', function () { it('does not assign string boolean attributes for custom attributes', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div whatever={true} />); }).toErrorDev( 'Received `true` for a non-boolean attribute `whatever`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + 'whatever="true" or whatever={value.toString()}.', ); expect(el.hasAttribute('whatever')).toBe(false); }); it('stringifies the boolean true for allowed attributes', function () { const el = ReactTestUtils.renderIntoDocument(<div spellCheck={true} />); expect(el.getAttribute('spellCheck')).toBe('true'); }); it('stringifies the boolean false for allowed attributes', function () { const el = ReactTestUtils.renderIntoDocument(<div spellCheck={false} />); expect(el.getAttribute('spellCheck')).toBe('false'); }); it('stringifies implicit booleans for allowed attributes', function () { // eslint-disable-next-line react/jsx-boolean-value const el = ReactTestUtils.renderIntoDocument(<div spellCheck />); expect(el.getAttribute('spellCheck')).toBe('true'); }); }); describe('Boolean attributes', function () { it('warns on the ambiguous string value "false"', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div hidden="false" />); }).toErrorDev( 'Received the string `false` for the boolean attribute `hidden`. ' + 'The browser will interpret it as a truthy value. ' + 'Did you mean hidden={false}?', ); expect(el.getAttribute('hidden')).toBe(''); }); it('warns on the potentially-ambiguous string value "true"', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument(<div hidden="true" />); }).toErrorDev( 'Received the string `true` for the boolean attribute `hidden`. ' + 'Although this works, it will not work as expected if you pass the string "false". ' + 'Did you mean hidden={true}?', ); expect(el.getAttribute('hidden')).toBe(''); }); }); describe('Hyphenated SVG elements', function () { it('the font-face element is not a custom element', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument( <svg> <font-face x-height={false} /> </svg>, ); }).toErrorDev( 'Warning: Invalid DOM property `x-height`. Did you mean `xHeight`', ); expect(el.querySelector('font-face').hasAttribute('x-height')).toBe( false, ); }); it('the font-face element does not allow unknown boolean values', function () { let el; expect(() => { el = ReactTestUtils.renderIntoDocument( <svg> <font-face whatever={false} /> </svg>, ); }).toErrorDev( 'Received `false` for a non-boolean attribute `whatever`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + 'whatever="false" or whatever={value.toString()}.\n\n' + 'If you used to conditionally omit it with whatever={condition && value}, ' + 'pass whatever={condition ? value : undefined} instead.', ); expect(el.querySelector('font-face').hasAttribute('whatever')).toBe( false, ); }); }); // These tests mostly verify the existing behavior. // It may not always makes sense but we can't change it in minors. describe('Custom elements', () => { it('does not strip unknown boolean attributes', () => { const container = document.createElement('div'); ReactDOM.render(<some-custom-element foo={true} />, container); const node = container.firstChild; expect(node.getAttribute('foo')).toBe( ReactFeatureFlags.enableCustomElementPropertySupport ? '' : 'true', ); ReactDOM.render(<some-custom-element foo={false} />, container); expect(node.getAttribute('foo')).toBe( ReactFeatureFlags.enableCustomElementPropertySupport ? null : 'false', ); ReactDOM.render(<some-custom-element />, container); expect(node.hasAttribute('foo')).toBe(false); ReactDOM.render(<some-custom-element foo={true} />, container); expect(node.hasAttribute('foo')).toBe(true); }); it('does not strip the on* attributes', () => { const container = document.createElement('div'); ReactDOM.render(<some-custom-element onx="bar" />, container); const node = container.firstChild; expect(node.getAttribute('onx')).toBe('bar'); ReactDOM.render(<some-custom-element onx="buzz" />, container); expect(node.getAttribute('onx')).toBe('buzz'); ReactDOM.render(<some-custom-element />, container); expect(node.hasAttribute('onx')).toBe(false); ReactDOM.render(<some-custom-element onx="bar" />, container); expect(node.getAttribute('onx')).toBe('bar'); }); }); it('receives events in specific order', () => { const eventOrder = []; const track = tag => () => eventOrder.push(tag); const outerRef = React.createRef(); const innerRef = React.createRef(); function OuterReactApp() { return ( <div ref={outerRef} onClick={track('outer bubble')} onClickCapture={track('outer capture')} /> ); } function InnerReactApp() { return ( <div ref={innerRef} onClick={track('inner bubble')} onClickCapture={track('inner capture')} /> ); } const container = document.createElement('div'); document.body.appendChild(container); try { ReactDOM.render(<OuterReactApp />, container); ReactDOM.render(<InnerReactApp />, outerRef.current); document.addEventListener('click', track('document bubble')); document.addEventListener('click', track('document capture'), true); innerRef.current.click(); if (ReactFeatureFlags.enableLegacyFBSupport) { // The order will change here, as the legacy FB support adds // the event listener onto the document after the one above has. expect(eventOrder).toEqual([ 'document capture', 'outer capture', 'inner capture', 'document bubble', 'inner bubble', 'outer bubble', ]); } else { expect(eventOrder).toEqual([ 'document capture', 'outer capture', 'inner capture', 'inner bubble', 'outer bubble', 'document bubble', ]); } } finally { document.body.removeChild(container); } }); describe('iOS Tap Highlight', () => { it('adds onclick handler to elements with onClick prop', () => { const container = document.createElement('div'); const elementRef = React.createRef(); function Component() { return <div ref={elementRef} onClick={() => {}} />; } ReactDOM.render(<Component />, container); expect(typeof elementRef.current.onclick).toBe('function'); }); it('adds onclick handler to a portal root', () => { const container = document.createElement('div'); const portalContainer = document.createElement('div'); function Component() { return ReactDOM.createPortal( <div onClick={() => {}} />, portalContainer, ); } ReactDOM.render(<Component />, container); expect(typeof portalContainer.onclick).toBe('function'); }); it('does not add onclick handler to the React root', () => { const container = document.createElement('div'); function Component() { return <div onClick={() => {}} />; } ReactDOM.render(<Component />, container); expect(typeof container.onclick).not.toBe('function'); }); }); });
33.656357
114
0.576763
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 */ import * as acorn from 'acorn-loose'; type ResolveContext = { conditions: Array<string>, parentURL: string | void, }; type ResolveFunction = ( string, ResolveContext, ResolveFunction, ) => {url: string} | Promise<{url: string}>; type GetSourceContext = { format: string, }; type GetSourceFunction = ( string, GetSourceContext, GetSourceFunction, ) => Promise<{source: Source}>; type TransformSourceContext = { format: string, url: string, }; type TransformSourceFunction = ( Source, TransformSourceContext, TransformSourceFunction, ) => Promise<{source: Source}>; type LoadContext = { conditions: Array<string>, format: string | null | void, importAssertions: Object, }; type LoadFunction = ( string, LoadContext, LoadFunction, ) => Promise<{format: string, shortCircuit?: boolean, source: Source}>; type Source = string | ArrayBuffer | Uint8Array; let warnedAboutConditionsFlag = false; let stashedGetSource: null | GetSourceFunction = null; let stashedResolve: null | ResolveFunction = null; export async function resolve( specifier: string, context: ResolveContext, defaultResolve: ResolveFunction, ): Promise<{url: string}> { // We stash this in case we end up needing to resolve export * statements later. stashedResolve = defaultResolve; if (!context.conditions.includes('react-server')) { context = { ...context, conditions: [...context.conditions, 'react-server'], }; if (!warnedAboutConditionsFlag) { warnedAboutConditionsFlag = true; // eslint-disable-next-line react-internal/no-production-logging console.warn( 'You did not run Node.js with the `--conditions react-server` flag. ' + 'Any "react-server" override will only work with ESM imports.', ); } } return await defaultResolve(specifier, context, defaultResolve); } export async function getSource( url: string, context: GetSourceContext, defaultGetSource: GetSourceFunction, ): Promise<{source: Source}> { // We stash this in case we end up needing to resolve export * statements later. stashedGetSource = defaultGetSource; return defaultGetSource(url, context, defaultGetSource); } function addLocalExportedNames(names: Map<string, string>, node: any) { switch (node.type) { case 'Identifier': names.set(node.name, node.name); return; case 'ObjectPattern': for (let i = 0; i < node.properties.length; i++) addLocalExportedNames(names, node.properties[i]); return; case 'ArrayPattern': for (let i = 0; i < node.elements.length; i++) { const element = node.elements[i]; if (element) addLocalExportedNames(names, element); } return; case 'Property': addLocalExportedNames(names, node.value); return; case 'AssignmentPattern': addLocalExportedNames(names, node.left); return; case 'RestElement': addLocalExportedNames(names, node.argument); return; case 'ParenthesizedExpression': addLocalExportedNames(names, node.expression); return; } } function transformServerModule( source: string, body: any, url: string, loader: LoadFunction, ): string { // If the same local name is exported more than once, we only need one of the names. const localNames: Map<string, string> = new Map(); const localTypes: Map<string, string> = new Map(); for (let i = 0; i < body.length; i++) { const node = body[i]; switch (node.type) { case 'ExportAllDeclaration': // If export * is used, the other file needs to explicitly opt into "use server" too. break; case 'ExportDefaultDeclaration': if (node.declaration.type === 'Identifier') { localNames.set(node.declaration.name, 'default'); } else if (node.declaration.type === 'FunctionDeclaration') { if (node.declaration.id) { localNames.set(node.declaration.id.name, 'default'); localTypes.set(node.declaration.id.name, 'function'); } else { // TODO: This needs to be rewritten inline because it doesn't have a local name. } } continue; case 'ExportNamedDeclaration': if (node.declaration) { if (node.declaration.type === 'VariableDeclaration') { const declarations = node.declaration.declarations; for (let j = 0; j < declarations.length; j++) { addLocalExportedNames(localNames, declarations[j].id); } } else { const name = node.declaration.id.name; localNames.set(name, name); if (node.declaration.type === 'FunctionDeclaration') { localTypes.set(name, 'function'); } } } if (node.specifiers) { const specifiers = node.specifiers; for (let j = 0; j < specifiers.length; j++) { const specifier = specifiers[j]; localNames.set(specifier.local.name, specifier.exported.name); } } continue; } } if (localNames.size === 0) { return source; } let newSrc = source + '\n\n;'; newSrc += 'import {registerServerReference} from "react-server-dom-turbopack/server";\n'; localNames.forEach(function (exported, local) { if (localTypes.get(local) !== 'function') { // We first check if the export is a function and if so annotate it. newSrc += 'if (typeof ' + local + ' === "function") '; } newSrc += 'registerServerReference(' + local + ','; newSrc += JSON.stringify(url) + ','; newSrc += JSON.stringify(exported) + ');\n'; }); return newSrc; } function addExportNames(names: Array<string>, node: any) { switch (node.type) { case 'Identifier': names.push(node.name); return; case 'ObjectPattern': for (let i = 0; i < node.properties.length; i++) addExportNames(names, node.properties[i]); return; case 'ArrayPattern': for (let i = 0; i < node.elements.length; i++) { const element = node.elements[i]; if (element) addExportNames(names, element); } return; case 'Property': addExportNames(names, node.value); return; case 'AssignmentPattern': addExportNames(names, node.left); return; case 'RestElement': addExportNames(names, node.argument); return; case 'ParenthesizedExpression': addExportNames(names, node.expression); return; } } function resolveClientImport( specifier: string, parentURL: string, ): {url: string} | Promise<{url: string}> { // Resolve an import specifier as if it was loaded by the client. This doesn't use // the overrides that this loader does but instead reverts to the default. // This resolution algorithm will not necessarily have the same configuration // as the actual client loader. It should mostly work and if it doesn't you can // always convert to explicit exported names instead. const conditions = ['node', 'import']; if (stashedResolve === null) { throw new Error( 'Expected resolve to have been called before transformSource', ); } return stashedResolve(specifier, {conditions, parentURL}, stashedResolve); } async function parseExportNamesInto( body: any, names: Array<string>, parentURL: string, loader: LoadFunction, ): Promise<void> { for (let i = 0; i < body.length; i++) { const node = body[i]; switch (node.type) { case 'ExportAllDeclaration': if (node.exported) { addExportNames(names, node.exported); continue; } else { const {url} = await resolveClientImport(node.source.value, parentURL); const {source} = await loader( url, {format: 'module', conditions: [], importAssertions: {}}, loader, ); if (typeof source !== 'string') { throw new Error('Expected the transformed source to be a string.'); } let childBody; try { childBody = acorn.parse(source, { ecmaVersion: '2024', sourceType: 'module', }).body; } catch (x) { // eslint-disable-next-line react-internal/no-production-logging console.error('Error parsing %s %s', url, x.message); continue; } await parseExportNamesInto(childBody, names, url, loader); continue; } case 'ExportDefaultDeclaration': names.push('default'); continue; case 'ExportNamedDeclaration': if (node.declaration) { if (node.declaration.type === 'VariableDeclaration') { const declarations = node.declaration.declarations; for (let j = 0; j < declarations.length; j++) { addExportNames(names, declarations[j].id); } } else { addExportNames(names, node.declaration.id); } } if (node.specifiers) { const specifiers = node.specifiers; for (let j = 0; j < specifiers.length; j++) { addExportNames(names, specifiers[j].exported); } } continue; } } } async function transformClientModule( body: any, url: string, loader: LoadFunction, ): Promise<string> { const names: Array<string> = []; await parseExportNamesInto(body, names, url, loader); if (names.length === 0) { return ''; } let newSrc = 'import {registerClientReference} from "react-server-dom-turbopack/server";\n'; for (let i = 0; i < names.length; i++) { const name = names[i]; if (name === 'default') { newSrc += 'export default '; newSrc += 'registerClientReference(function() {'; newSrc += 'throw new Error(' + JSON.stringify( `Attempted to call the default export of ${url} from the server` + `but it's on the client. It's not possible to invoke a client function from ` + `the server, it can only be rendered as a Component or passed to props of a` + `Client Component.`, ) + ');'; } else { newSrc += 'export const ' + name + ' = '; newSrc += 'registerClientReference(function() {'; newSrc += 'throw new Error(' + JSON.stringify( `Attempted to call ${name}() from the server but ${name} is on the client. ` + `It's not possible to invoke a client function from the server, it can ` + `only be rendered as a Component or passed to props of a Client Component.`, ) + ');'; } newSrc += '},'; newSrc += JSON.stringify(url) + ','; newSrc += JSON.stringify(name) + ');\n'; } return newSrc; } async function loadClientImport( url: string, defaultTransformSource: TransformSourceFunction, ): Promise<{format: string, shortCircuit?: boolean, source: Source}> { if (stashedGetSource === null) { throw new Error( 'Expected getSource to have been called before transformSource', ); } // TODO: Validate that this is another module by calling getFormat. const {source} = await stashedGetSource( url, {format: 'module'}, stashedGetSource, ); const result = await defaultTransformSource( source, {format: 'module', url}, defaultTransformSource, ); return {format: 'module', source: result.source}; } async function transformModuleIfNeeded( source: string, url: string, loader: LoadFunction, ): Promise<string> { // Do a quick check for the exact string. If it doesn't exist, don't // bother parsing. if ( source.indexOf('use client') === -1 && source.indexOf('use server') === -1 ) { return source; } let body; try { body = acorn.parse(source, { ecmaVersion: '2024', sourceType: 'module', }).body; } catch (x) { // eslint-disable-next-line react-internal/no-production-logging console.error('Error parsing %s %s', url, x.message); return source; } let useClient = false; let useServer = false; for (let i = 0; i < body.length; i++) { const node = body[i]; if (node.type !== 'ExpressionStatement' || !node.directive) { break; } if (node.directive === 'use client') { useClient = true; } if (node.directive === 'use server') { useServer = true; } } if (!useClient && !useServer) { return source; } if (useClient && useServer) { throw new Error( 'Cannot have both "use client" and "use server" directives in the same file.', ); } if (useClient) { return transformClientModule(body, url, loader); } return transformServerModule(source, body, url, loader); } export async function transformSource( source: Source, context: TransformSourceContext, defaultTransformSource: TransformSourceFunction, ): Promise<{source: Source}> { const transformed = await defaultTransformSource( source, context, defaultTransformSource, ); if (context.format === 'module') { const transformedSource = transformed.source; if (typeof transformedSource !== 'string') { throw new Error('Expected source to have been transformed to a string.'); } const newSrc = await transformModuleIfNeeded( transformedSource, context.url, (url: string, ctx: LoadContext, defaultLoad: LoadFunction) => { return loadClientImport(url, defaultTransformSource); }, ); return {source: newSrc}; } return transformed; } export async function load( url: string, context: LoadContext, defaultLoad: LoadFunction, ): Promise<{format: string, shortCircuit?: boolean, source: Source}> { const result = await defaultLoad(url, context, defaultLoad); if (result.format === 'module') { if (typeof result.source !== 'string') { throw new Error('Expected source to have been loaded into a string.'); } const newSrc = await transformModuleIfNeeded( result.source, url, defaultLoad, ); return {format: 'module', source: newSrc}; } return result; }
28.706612
93
0.622453
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 * as React from 'react'; import is from 'shared/objectIs'; import {useSyncExternalStore} from 'use-sync-external-store/src/useSyncExternalStore'; // Intentionally not using named imports because Rollup uses dynamic dispatch // for CommonJS interop. const {useRef, useEffect, useMemo, useDebugValue} = React; // Same as useSyncExternalStore, but supports selector and isEqual arguments. export function useSyncExternalStoreWithSelector<Snapshot, Selection>( subscribe: (() => void) => () => void, getSnapshot: () => Snapshot, getServerSnapshot: void | null | (() => Snapshot), selector: (snapshot: Snapshot) => Selection, isEqual?: (a: Selection, b: Selection) => boolean, ): Selection { // Use this to track the rendered snapshot. const instRef = useRef< | { hasValue: true, value: Selection, } | { hasValue: false, value: null, } | null, >(null); let inst; if (instRef.current === null) { inst = { hasValue: false, value: null, }; instRef.current = inst; } else { inst = instRef.current; } const [getSelection, getServerSelection] = useMemo(() => { // Track the memoized state using closure variables that are local to this // memoized instance of a getSnapshot function. Intentionally not using a // useRef hook, because that state would be shared across all concurrent // copies of the hook/component. let hasMemo = false; let memoizedSnapshot; let memoizedSelection: Selection; const memoizedSelector = (nextSnapshot: Snapshot) => { if (!hasMemo) { // The first time the hook is called, there is no memoized result. hasMemo = true; memoizedSnapshot = nextSnapshot; const nextSelection = selector(nextSnapshot); if (isEqual !== undefined) { // Even if the selector has changed, the currently rendered selection // may be equal to the new selection. We should attempt to reuse the // current value if possible, to preserve downstream memoizations. if (inst.hasValue) { const currentSelection = inst.value; if (isEqual(currentSelection, nextSelection)) { memoizedSelection = currentSelection; return currentSelection; } } } memoizedSelection = nextSelection; return nextSelection; } // We may be able to reuse the previous invocation's result. const prevSnapshot: Snapshot = (memoizedSnapshot: any); const prevSelection: Selection = (memoizedSelection: any); if (is(prevSnapshot, nextSnapshot)) { // The snapshot is the same as last time. Reuse the previous selection. return prevSelection; } // The snapshot has changed, so we need to compute a new selection. const nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data // has changed. If it hasn't, return the previous selection. That signals // to React that the selections are conceptually equal, and we can bail // out of rendering. if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) { return prevSelection; } memoizedSnapshot = nextSnapshot; memoizedSelection = nextSelection; return nextSelection; }; // Assigning this to a constant so that Flow knows it can't change. const maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot; const getSnapshotWithSelector = () => memoizedSelector(getSnapshot()); const getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : () => memoizedSelector(maybeGetServerSnapshot()); return [getSnapshotWithSelector, getServerSnapshotWithSelector]; }, [getSnapshot, getServerSnapshot, selector, isEqual]); const value = useSyncExternalStore( subscribe, getSelection, getServerSelection, ); useEffect(() => { // $FlowFixMe[incompatible-type] changing the variant using mutation isn't supported inst.hasValue = true; // $FlowFixMe[incompatible-type] inst.value = value; }, [value]); useDebugValue(value); return value; }
33.653846
88
0.66452
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 ReactVersion from 'shared/ReactVersion'; import type {ReactNodeList} from 'shared/ReactTypes'; import { createRequest, startWork, startFlowing, abort, } from 'react-server/src/ReactFizzServer'; import { createResumableState, createRenderState, createRootFormatContext, } from 'react-dom-bindings/src/server/ReactFizzConfigDOMLegacy'; type ServerOptions = { identifierPrefix?: string, }; function onError() { // Non-fatal errors are ignored. } function renderToStringImpl( children: ReactNodeList, options: void | ServerOptions, generateStaticMarkup: boolean, abortReason: string, ): string { let didFatal = false; let fatalError = null; let result = ''; const destination = { // $FlowFixMe[missing-local-annot] push(chunk) { if (chunk !== null) { result += chunk; } return true; }, // $FlowFixMe[missing-local-annot] destroy(error) { didFatal = true; fatalError = error; }, }; let readyToStream = false; function onShellReady() { readyToStream = true; } const resumableState = createResumableState( options ? options.identifierPrefix : undefined, undefined, ); const request = createRequest( children, resumableState, createRenderState(resumableState, generateStaticMarkup), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined, undefined, ); startWork(request); // If anything suspended and is still pending, we'll abort it before writing. // That way we write only client-rendered boundaries from the start. abort(request, abortReason); startFlowing(request, destination); if (didFatal && fatalError !== abortReason) { throw fatalError; } if (!readyToStream) { // Note: This error message is the one we use on the client. It doesn't // really make sense here. But this is the legacy server renderer, anyway. // We're going to delete it soon. throw new Error( 'A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.', ); } return result; } export {renderToStringImpl, ReactVersion as version};
23.413462
79
0.687155
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 'react-devtools-shared/src/backend/agent'; import Bridge from 'react-devtools-shared/src/bridge'; import {installHook} from 'react-devtools-shared/src/hook'; import {initBackend} from 'react-devtools-shared/src/backend'; import {installConsoleFunctionsToWindow} from 'react-devtools-shared/src/backend/console'; import {__DEBUG__} from 'react-devtools-shared/src/constants'; import setupNativeStyleEditor from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor'; import {getDefaultComponentFilters} from 'react-devtools-shared/src/utils'; import { initializeUsingCachedSettings, cacheConsolePatchSettings, type DevToolsSettingsManager, } from './cachedSettings'; import type {BackendBridge} from 'react-devtools-shared/src/bridge'; import type {ComponentFilter} from 'react-devtools-shared/src/frontend/types'; import type {DevToolsHook} from 'react-devtools-shared/src/backend/types'; import type {ResolveNativeStyle} from 'react-devtools-shared/src/backend/NativeStyleEditor/setupNativeStyleEditor'; type ConnectOptions = { host?: string, nativeStyleEditorValidAttributes?: $ReadOnlyArray<string>, port?: number, useHttps?: boolean, resolveRNStyle?: ResolveNativeStyle, retryConnectionDelay?: number, isAppActive?: () => boolean, websocket?: ?WebSocket, devToolsSettingsManager: ?DevToolsSettingsManager, }; // Install a global variable to allow patching console early (during injection). // This provides React Native developers with components stacks even if they don't run DevTools. installConsoleFunctionsToWindow(); installHook(window); const hook: ?DevToolsHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; let savedComponentFilters: Array<ComponentFilter> = getDefaultComponentFilters(); function debug(methodName: string, ...args: Array<mixed>) { if (__DEBUG__) { console.log( `%c[core/backend] %c${methodName}`, 'color: teal; font-weight: bold;', 'font-weight: bold;', ...args, ); } } export function connectToDevTools(options: ?ConnectOptions) { if (hook == null) { // DevTools didn't get injected into this page (maybe b'c of the contentType). return; } const { host = 'localhost', nativeStyleEditorValidAttributes, useHttps = false, port = 8097, websocket, resolveRNStyle = (null: $FlowFixMe), retryConnectionDelay = 2000, isAppActive = () => true, devToolsSettingsManager, } = options || {}; const protocol = useHttps ? 'wss' : 'ws'; let retryTimeoutID: TimeoutID | null = null; function scheduleRetry() { if (retryTimeoutID === null) { // Two seconds because RN had issues with quick retries. retryTimeoutID = setTimeout( () => connectToDevTools(options), retryConnectionDelay, ); } } if (devToolsSettingsManager != null) { try { initializeUsingCachedSettings(devToolsSettingsManager); } catch (e) { // If we call a method on devToolsSettingsManager that throws, or if // is invalid data read out, don't throw and don't interrupt initialization console.error(e); } } if (!isAppActive()) { // If the app is in background, maybe retry later. // Don't actually attempt to connect until we're in foreground. scheduleRetry(); return; } let bridge: BackendBridge | null = null; const messageListeners = []; const uri = protocol + '://' + host + ':' + port; // If existing websocket is passed, use it. // This is necessary to support our custom integrations. // See D6251744. const ws = websocket ? websocket : new window.WebSocket(uri); ws.onclose = handleClose; ws.onerror = handleFailed; ws.onmessage = handleMessage; ws.onopen = function () { bridge = new Bridge({ listen(fn) { messageListeners.push(fn); return () => { const index = messageListeners.indexOf(fn); if (index >= 0) { messageListeners.splice(index, 1); } }; }, send(event: string, payload: any, transferable?: Array<any>) { if (ws.readyState === ws.OPEN) { if (__DEBUG__) { debug('wall.send()', event, payload); } ws.send(JSON.stringify({event, payload})); } else { if (__DEBUG__) { debug( 'wall.send()', 'Shutting down bridge because of closed WebSocket connection', ); } if (bridge !== null) { bridge.shutdown(); } scheduleRetry(); } }, }); bridge.addListener( 'updateComponentFilters', (componentFilters: Array<ComponentFilter>) => { // Save filter changes in memory, in case DevTools is reloaded. // In that case, the renderer will already be using the updated values. // We'll lose these in between backend reloads but that can't be helped. savedComponentFilters = componentFilters; }, ); if (devToolsSettingsManager != null && bridge != null) { bridge.addListener('updateConsolePatchSettings', consolePatchSettings => cacheConsolePatchSettings( devToolsSettingsManager, consolePatchSettings, ), ); } // The renderer interface doesn't read saved component filters directly, // because they are generally stored in localStorage within the context of the extension. // Because of this it relies on the extension to pass filters. // In the case of the standalone DevTools being used with a website, // saved filters are injected along with the backend script tag so we shouldn't override them here. // This injection strategy doesn't work for React Native though. // Ideally the backend would save the filters itself, but RN doesn't provide a sync storage solution. // So for now we just fall back to using the default filters... if (window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ == null) { // $FlowFixMe[incompatible-use] found when upgrading Flow bridge.send('overrideComponentFilters', savedComponentFilters); } // TODO (npm-packages) Warn if "isBackendStorageAPISupported" // $FlowFixMe[incompatible-call] found when upgrading Flow const agent = new Agent(bridge); agent.addListener('shutdown', () => { // If we received 'shutdown' from `agent`, we assume the `bridge` is already shutting down, // and that caused the 'shutdown' event on the `agent`, so we don't need to call `bridge.shutdown()` here. hook.emit('shutdown'); }); initBackend(hook, agent, window); // Setup React Native style editor if the environment supports it. if (resolveRNStyle != null || hook.resolveRNStyle != null) { setupNativeStyleEditor( // $FlowFixMe[incompatible-call] found when upgrading Flow bridge, agent, ((resolveRNStyle || hook.resolveRNStyle: any): ResolveNativeStyle), nativeStyleEditorValidAttributes || hook.nativeStyleEditorValidAttributes || null, ); } else { // Otherwise listen to detect if the environment later supports it. // For example, Flipper does not eagerly inject these values. // Instead it relies on the React Native Inspector to lazily inject them. let lazyResolveRNStyle; let lazyNativeStyleEditorValidAttributes; const initAfterTick = () => { if (bridge !== null) { setupNativeStyleEditor( bridge, agent, lazyResolveRNStyle, lazyNativeStyleEditorValidAttributes, ); } }; if (!hook.hasOwnProperty('resolveRNStyle')) { Object.defineProperty( hook, 'resolveRNStyle', ({ enumerable: false, get() { return lazyResolveRNStyle; }, set(value: $FlowFixMe) { lazyResolveRNStyle = value; initAfterTick(); }, }: Object), ); } if (!hook.hasOwnProperty('nativeStyleEditorValidAttributes')) { Object.defineProperty( hook, 'nativeStyleEditorValidAttributes', ({ enumerable: false, get() { return lazyNativeStyleEditorValidAttributes; }, set(value: $FlowFixMe) { lazyNativeStyleEditorValidAttributes = value; initAfterTick(); }, }: Object), ); } } }; function handleClose() { if (__DEBUG__) { debug('WebSocket.onclose'); } if (bridge !== null) { bridge.emit('shutdown'); } scheduleRetry(); } function handleFailed() { if (__DEBUG__) { debug('WebSocket.onerror'); } scheduleRetry(); } function handleMessage(event: MessageEvent) { let data; try { if (typeof event.data === 'string') { data = JSON.parse(event.data); if (__DEBUG__) { debug('WebSocket.onmessage', data); } } else { throw Error(); } } catch (e) { console.error( '[React DevTools] Failed to parse JSON: ' + (event.data: any), ); return; } messageListeners.forEach(fn => { try { fn(data); } catch (error) { // jsc doesn't play so well with tracebacks that go into eval'd code, // so the stack trace here will stop at the `eval()` call. Getting the // message that caused the error is the best we can do for now. console.log('[React DevTools] Error calling listener', data); console.log('error:', error); throw error; } }); } }
30.84984
115
0.629013
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // This file is only used for tests. // It lazily loads the implementation so that we get the correct set of host configs. import ReactVersion from 'shared/ReactVersion'; export {ReactVersion as version}; export function renderToReadableStream() { return require('./src/server/react-dom-server.bun').renderToReadableStream.apply( this, arguments, ); } export function renderToNodeStream() { return require('./src/server/react-dom-server.bun').renderToNodeStream.apply( this, arguments, ); } export function renderToStaticNodeStream() { return require('./src/server/react-dom-server.bun').renderToStaticNodeStream.apply( this, arguments, ); } export function renderToString() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToString.apply( this, arguments, ); } export function renderToStaticMarkup() { return require('./src/server/ReactDOMLegacyServerBrowser').renderToStaticMarkup.apply( this, arguments, ); } export function resume() { return require('./src/server/react-dom-server.bun').resume.apply( this, arguments, ); }
22.945455
88
0.721884
owtf
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; import JumpingCursorTestCase from './JumpingCursorTestCase'; import EmailEnabledAttributesTestCase from './EmailEnabledAttributesTestCase'; import EmailDisabledAttributesTestCase from './EmailDisabledAttributesTestCase'; const React = window.React; function EmailInputs() { return ( <FixtureSet title="Email inputs"> <TestCase title="Spaces in email inputs" description={` Some browsers are trying to remove spaces from email inputs and after doing this place cursor to the beginning. `} affectedBrowsers="Chrome"> <TestCase.Steps> <li>Type space and character</li> <li>Type character, space, character, delete last character</li> </TestCase.Steps> <TestCase.ExpectedResult>Cursor not moving.</TestCase.ExpectedResult> <JumpingCursorTestCase /> </TestCase> <TestCase title="Attributes enabled" description={` Test enabled pattern, maxlength, multiple attributes. `}> <TestCase.Steps> <li>Type after existing text ',b@tt.com'</li> <li>Try to type spaces after typed text</li> </TestCase.Steps> <TestCase.ExpectedResult> Spaces not added. When cursor hovered over input, popup "Please match the requested format." is showed. </TestCase.ExpectedResult> <EmailEnabledAttributesTestCase /> </TestCase> <TestCase title="Attributes disabled" description={` Test disabled maxlength, multiple attributes. `}> <TestCase.Steps> <li>Type after existing text ',b@tt.com'</li> <li>Try to type spaces after typed text</li> </TestCase.Steps> <TestCase.ExpectedResult> Spaces are added freely. When cursor hovered over input, popup "A part following '@' should not contain the symbol ','." is showed. </TestCase.ExpectedResult> <EmailDisabledAttributesTestCase /> </TestCase> </FixtureSet> ); } export default EmailInputs;
30.594203
80
0.639743
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'; describe('forwardRef', () => { let PropTypes; let React; let ReactNoop; let waitForAll; beforeEach(() => { jest.resetModules(); PropTypes = require('prop-types'); React = require('react'); ReactNoop = require('react-noop-renderer'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; }); it('should update refs when switching between children', async () => { function FunctionComponent({forwardedRef, setRefOnDiv}) { return ( <section> <div ref={setRefOnDiv ? forwardedRef : null}>First</div> <span ref={setRefOnDiv ? null : forwardedRef}>Second</span> </section> ); } const RefForwardingComponent = React.forwardRef((props, ref) => ( <FunctionComponent {...props} forwardedRef={ref} /> )); const ref = React.createRef(); ReactNoop.render(<RefForwardingComponent ref={ref} setRefOnDiv={true} />); await waitForAll([]); expect(ref.current.type).toBe('div'); ReactNoop.render(<RefForwardingComponent ref={ref} setRefOnDiv={false} />); await waitForAll([]); expect(ref.current.type).toBe('span'); }); it('should support rendering null', async () => { const RefForwardingComponent = React.forwardRef((props, ref) => null); const ref = React.createRef(); ReactNoop.render(<RefForwardingComponent ref={ref} />); await waitForAll([]); expect(ref.current).toBe(null); }); it('should support rendering null for multiple children', async () => { const RefForwardingComponent = React.forwardRef((props, ref) => null); const ref = React.createRef(); ReactNoop.render( <div> <div /> <RefForwardingComponent ref={ref} /> <div /> </div>, ); await waitForAll([]); expect(ref.current).toBe(null); }); it('should support propTypes and defaultProps', async () => { function FunctionComponent({forwardedRef, optional, required}) { return ( <div ref={forwardedRef}> {optional} {required} </div> ); } const RefForwardingComponent = React.forwardRef( function NamedFunction(props, ref) { return <FunctionComponent {...props} forwardedRef={ref} />; }, ); RefForwardingComponent.propTypes = { optional: PropTypes.string, required: PropTypes.string.isRequired, }; RefForwardingComponent.defaultProps = { optional: 'default', }; const ref = React.createRef(); ReactNoop.render( <RefForwardingComponent ref={ref} optional="foo" required="bar" />, ); await waitForAll([]); expect(ref.current.children).toEqual([ {text: 'foo', hidden: false}, {text: 'bar', hidden: false}, ]); ReactNoop.render(<RefForwardingComponent ref={ref} required="foo" />); await waitForAll([]); expect(ref.current.children).toEqual([ {text: 'default', hidden: false}, {text: 'foo', hidden: false}, ]); expect(() => ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`ForwardRef(NamedFunction)`, but its value is `undefined`.\n' + ' in NamedFunction (at **)', ); }); it('should warn if not provided a callback during creation', () => { expect(() => React.forwardRef(undefined)).toErrorDev( 'forwardRef requires a render function but was given undefined.', {withoutStack: true}, ); expect(() => React.forwardRef(null)).toErrorDev( 'forwardRef requires a render function but was given null.', { withoutStack: true, }, ); expect(() => React.forwardRef('foo')).toErrorDev( 'forwardRef requires a render function but was given string.', {withoutStack: true}, ); }); it('should warn if no render function is provided', () => { expect(React.forwardRef).toErrorDev( 'forwardRef requires a render function but was given undefined.', {withoutStack: true}, ); }); it('should warn if the render function provided has propTypes or defaultProps attributes', () => { function renderWithPropTypes(props, ref) { return null; } renderWithPropTypes.propTypes = {}; function renderWithDefaultProps(props, ref) { return null; } renderWithDefaultProps.defaultProps = {}; expect(() => React.forwardRef(renderWithPropTypes)).toErrorDev( 'forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?', {withoutStack: true}, ); expect(() => React.forwardRef(renderWithDefaultProps)).toErrorDev( 'forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?', {withoutStack: true}, ); }); it('should not warn if the render function provided does not use any parameter', () => { React.forwardRef(function arityOfZero() { return <div ref={arguments[1]} />; }); }); it('should warn if the render function provided does not use the forwarded ref parameter', () => { const arityOfOne = props => <div {...props} />; expect(() => React.forwardRef(arityOfOne)).toErrorDev( 'forwardRef render functions accept exactly two parameters: props and ref. ' + 'Did you forget to use the ref parameter?', {withoutStack: true}, ); }); it('should not warn if the render function provided use exactly two parameters', () => { const arityOfTwo = (props, ref) => <div {...props} ref={ref} />; React.forwardRef(arityOfTwo); }); it('should warn if the render function provided expects to use more than two parameters', () => { const arityOfThree = (props, ref, x) => <div {...props} ref={ref} x={x} />; expect(() => React.forwardRef(arityOfThree)).toErrorDev( 'forwardRef render functions accept exactly two parameters: props and ref. ' + 'Any additional parameter will be undefined.', {withoutStack: true}, ); }); it('should fall back to showing something meaningful if no displayName or name are present', () => { const Component = props => <div {...props} />; const RefForwardingComponent = React.forwardRef((props, ref) => ( <Component {...props} forwardedRef={ref} /> )); RefForwardingComponent.propTypes = { optional: PropTypes.string, required: PropTypes.string.isRequired, }; RefForwardingComponent.defaultProps = { optional: 'default', }; const ref = React.createRef(); expect(() => ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`ForwardRef`, but its value is `undefined`.', // There's no component stack in this warning because the inner function is anonymous. // If we wanted to support this (for the Error frames / source location) // we could do this by updating ReactComponentStackFrame. {withoutStack: true}, ); }); it('should honor a displayName if set on the forwardRef wrapper in warnings', () => { const Component = props => <div {...props} />; const RefForwardingComponent = React.forwardRef(function Inner(props, ref) { <Component {...props} forwardedRef={ref} />; }); RefForwardingComponent.displayName = 'Custom'; RefForwardingComponent.propTypes = { optional: PropTypes.string, required: PropTypes.string.isRequired, }; RefForwardingComponent.defaultProps = { optional: 'default', }; const ref = React.createRef(); expect(() => ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`Custom`, but its value is `undefined`.\n' + ' in Inner (at **)', ); }); it('should pass displayName to an anonymous inner component so it shows up in component stacks', () => { const Component = props => <div {...props} />; const RefForwardingComponent = React.forwardRef((props, ref) => ( <Component {...props} forwardedRef={ref} /> )); RefForwardingComponent.displayName = 'Custom'; RefForwardingComponent.propTypes = { optional: PropTypes.string, required: PropTypes.string.isRequired, }; RefForwardingComponent.defaultProps = { optional: 'default', }; const ref = React.createRef(); expect(() => ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`Custom`, but its value is `undefined`.\n' + ' in Custom (at **)', ); }); it('should honor a displayName in stacks if set on the inner function', () => { const Component = props => <div {...props} />; const inner = (props, ref) => <Component {...props} forwardedRef={ref} />; inner.displayName = 'Inner'; const RefForwardingComponent = React.forwardRef(inner); RefForwardingComponent.propTypes = { optional: PropTypes.string, required: PropTypes.string.isRequired, }; RefForwardingComponent.defaultProps = { optional: 'default', }; const ref = React.createRef(); expect(() => ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`ForwardRef(Inner)`, but its value is `undefined`.\n' + ' in Inner (at **)', ); }); it('should honor a outer displayName when wrapped component and memo component set displayName at the same time.', () => { const Component = props => <div {...props} />; const inner = (props, ref) => <Component {...props} forwardedRef={ref} />; inner.displayName = 'Inner'; const RefForwardingComponent = React.forwardRef(inner); RefForwardingComponent.displayName = 'Outer'; RefForwardingComponent.propTypes = { optional: PropTypes.string, required: PropTypes.string.isRequired, }; RefForwardingComponent.defaultProps = { optional: 'default', }; const ref = React.createRef(); expect(() => ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`Outer`, but its value is `undefined`.\n' + ' in Inner (at **)', ); }); it('should not bailout if forwardRef is not wrapped in memo', async () => { const Component = props => <div {...props} />; let renderCount = 0; const RefForwardingComponent = React.forwardRef((props, ref) => { renderCount++; return <Component {...props} forwardedRef={ref} />; }); const ref = React.createRef(); ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />); await waitForAll([]); expect(renderCount).toBe(1); ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />); await waitForAll([]); expect(renderCount).toBe(2); }); it('should bailout if forwardRef is wrapped in memo', async () => { const Component = props => <div ref={props.forwardedRef} />; let renderCount = 0; const RefForwardingComponent = React.memo( React.forwardRef((props, ref) => { renderCount++; return <Component {...props} forwardedRef={ref} />; }), ); const ref = React.createRef(); ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />); await waitForAll([]); expect(renderCount).toBe(1); expect(ref.current.type).toBe('div'); ReactNoop.render(<RefForwardingComponent ref={ref} optional="foo" />); await waitForAll([]); expect(renderCount).toBe(1); const differentRef = React.createRef(); ReactNoop.render( <RefForwardingComponent ref={differentRef} optional="foo" />, ); await waitForAll([]); expect(renderCount).toBe(2); expect(ref.current).toBe(null); expect(differentRef.current.type).toBe('div'); ReactNoop.render(<RefForwardingComponent ref={ref} optional="bar" />); await waitForAll([]); expect(renderCount).toBe(3); }); it('should custom memo comparisons to compose', async () => { const Component = props => <div ref={props.forwardedRef} />; let renderCount = 0; const RefForwardingComponent = React.memo( React.forwardRef((props, ref) => { renderCount++; return <Component {...props} forwardedRef={ref} />; }), (o, p) => o.a === p.a && o.b === p.b, ); const ref = React.createRef(); ReactNoop.render(<RefForwardingComponent ref={ref} a="0" b="0" c="1" />); await waitForAll([]); expect(renderCount).toBe(1); expect(ref.current.type).toBe('div'); // Changing either a or b rerenders ReactNoop.render(<RefForwardingComponent ref={ref} a="0" b="1" c="1" />); await waitForAll([]); expect(renderCount).toBe(2); // Changing c doesn't rerender ReactNoop.render(<RefForwardingComponent ref={ref} a="0" b="1" c="2" />); await waitForAll([]); expect(renderCount).toBe(2); const ComposedMemo = React.memo( RefForwardingComponent, (o, p) => o.a === p.a && o.c === p.c, ); ReactNoop.render(<ComposedMemo ref={ref} a="0" b="0" c="0" />); await waitForAll([]); expect(renderCount).toBe(3); // Changing just b no longer updates ReactNoop.render(<ComposedMemo ref={ref} a="0" b="1" c="0" />); await waitForAll([]); expect(renderCount).toBe(3); // Changing just a and c updates ReactNoop.render(<ComposedMemo ref={ref} a="2" b="2" c="2" />); await waitForAll([]); expect(renderCount).toBe(4); // Changing just c does not update ReactNoop.render(<ComposedMemo ref={ref} a="2" b="2" c="3" />); await waitForAll([]); expect(renderCount).toBe(4); // Changing ref still rerenders const differentRef = React.createRef(); ReactNoop.render(<ComposedMemo ref={differentRef} a="2" b="2" c="3" />); await waitForAll([]); expect(renderCount).toBe(5); expect(ref.current).toBe(null); expect(differentRef.current.type).toBe('div'); }); it('warns on forwardRef(memo(...))', () => { expect(() => { React.forwardRef( React.memo((props, ref) => { return null; }), ); }).toErrorDev( [ 'Warning: forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).', ], {withoutStack: true}, ); }); });
29.928862
124
0.6227
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('SyntheticFocusEvent', () => { let React; let ReactDOM; let container; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); container = null; }); test('onFocus events have the focus type', () => { const log = []; ReactDOM.render( <button onFocus={event => log.push(`onFocus: ${event.type}`)} onFocusCapture={event => log.push(`onFocusCapture: ${event.type}`)} />, container, ); const button = container.querySelector('button'); button.dispatchEvent( new FocusEvent('focusin', { bubbles: true, cancelable: false, }), ); expect(log).toEqual(['onFocusCapture: focus', 'onFocus: focus']); }); test('onBlur events have the blur type', () => { const log = []; ReactDOM.render( <button onBlur={event => log.push(`onBlur: ${event.type}`)} onBlurCapture={event => log.push(`onBlurCapture: ${event.type}`)} />, container, ); const button = container.querySelector('button'); button.dispatchEvent( new FocusEvent('focusout', { bubbles: true, cancelable: false, }), ); expect(log).toEqual(['onBlurCapture: blur', 'onBlur: blur']); }); });
22.521127
75
0.59257
null
'use strict'; const ncp = require('ncp').ncp; const path = require('path'); const mkdirp = require('mkdirp'); const rimraf = require('rimraf'); const exec = require('child_process').exec; const targz = require('targz'); function asyncCopyTo(from, to) { return asyncMkDirP(path.dirname(to)).then( () => new Promise((resolve, reject) => { ncp(from, to, error => { if (error) { // Wrap to have a useful stack trace. reject(new Error(error)); } else { // Wait for copied files to exist; ncp() sometimes completes prematurely. // For more detail, see github.com/facebook/react/issues/22323 // Also github.com/AvianFlu/ncp/issues/127 setTimeout(resolve, 10); } }); }) ); } function asyncExecuteCommand(command) { return new Promise((resolve, reject) => exec(command, (error, stdout) => { if (error) { reject(error); return; } resolve(stdout); }) ); } function asyncExtractTar(options) { return new Promise((resolve, reject) => targz.decompress(options, error => { if (error) { reject(error); return; } resolve(); }) ); } function asyncMkDirP(filepath) { return new Promise((resolve, reject) => mkdirp(filepath, error => { if (error) { reject(error); return; } resolve(); }) ); } function asyncRimRaf(filepath) { return new Promise((resolve, reject) => rimraf(filepath, error => { if (error) { reject(error); return; } resolve(); }) ); } function resolvePath(filepath) { if (filepath[0] === '~') { return path.join(process.env.HOME, filepath.slice(1)); } else { return path.resolve(filepath); } } module.exports = { asyncCopyTo, resolvePath, asyncExecuteCommand, asyncExtractTar, asyncMkDirP, asyncRimRaf, };
20.064516
85
0.568948
Ethical-Hacking-Scripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import List from './List'; export default List;
18.538462
66
0.6917
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 strict */ export const enableSchedulerDebugging = false; export const enableIsInputPending = false; export const enableProfiling = false; export const enableIsInputPendingContinuous = false; export const frameYieldMs = 5; export const continuousYieldMs = 50; export const maxYieldMs = 300; export const userBlockingPriorityTimeout = 250; export const normalPriorityTimeout = 5000; export const lowPriorityTimeout = 10000;
28.761905
66
0.782051
owtf
'use strict'; const fs = require('fs'); const path = require('path'); const paths = require('./paths'); const chalk = require('chalk'); const resolve = require('resolve'); /** * Get additional module paths based on the baseUrl of a compilerOptions object. * * @param {Object} options */ function getAdditionalModulePaths(options = {}) { const baseUrl = options.baseUrl; if (!baseUrl) { return ''; } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); // We don't need to do anything if `baseUrl` is set to `node_modules`. This is // the default behavior. if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { return null; } // Allow the user set the `baseUrl` to `appSrc`. if (path.relative(paths.appSrc, baseUrlResolved) === '') { return [paths.appSrc]; } // If the path is equal to the root directory we ignore it here. // We don't want to allow importing from the root directly as source files are // not transpiled outside of `src`. We do allow importing them with the // absolute path (e.g. `src/Components/Button.js`) but we set that up with // an alias. if (path.relative(paths.appPath, baseUrlResolved) === '') { return null; } // Otherwise, throw an error. throw new Error( chalk.red.bold( "Your project's `baseUrl` can only be set to `src` or `node_modules`." + ' Create React App does not support other values at this time.' ) ); } /** * Get webpack aliases based on the baseUrl of a compilerOptions object. * * @param {*} options */ function getWebpackAliases(options = {}) { const baseUrl = options.baseUrl; if (!baseUrl) { return {}; } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); if (path.relative(paths.appPath, baseUrlResolved) === '') { return { src: paths.appSrc, }; } } /** * Get jest aliases based on the baseUrl of a compilerOptions object. * * @param {*} options */ function getJestAliases(options = {}) { const baseUrl = options.baseUrl; if (!baseUrl) { return {}; } const baseUrlResolved = path.resolve(paths.appPath, baseUrl); if (path.relative(paths.appPath, baseUrlResolved) === '') { return { '^src/(.*)$': '<rootDir>/src/$1', }; } } function getModules() { // Check if TypeScript is setup const hasTsConfig = fs.existsSync(paths.appTsConfig); const hasJsConfig = fs.existsSync(paths.appJsConfig); if (hasTsConfig && hasJsConfig) { throw new Error( 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.' ); } let config; // If there's a tsconfig.json we assume it's a // TypeScript project and set up the config // based on tsconfig.json if (hasTsConfig) { const ts = require( resolve.sync('typescript', { basedir: paths.appNodeModules, }) ); config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; // Otherwise we'll check if there is jsconfig.json // for non TS projects. } else if (hasJsConfig) { config = require(paths.appJsConfig); } config = config || {}; const options = config.compilerOptions || {}; const additionalModulePaths = getAdditionalModulePaths(options); return { additionalModulePaths: additionalModulePaths, webpackAliases: getWebpackAliases(options), jestAliases: getJestAliases(options), hasTsConfig, }; } module.exports = getModules();
24.49635
125
0.662085
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 {disableLegacyContext} from 'shared/ReactFeatureFlags'; import getComponentNameFromType from 'shared/getComponentNameFromType'; import checkPropTypes from 'shared/checkPropTypes'; let warnedAboutMissingGetChildContext; if (__DEV__) { warnedAboutMissingGetChildContext = ({}: {[string]: boolean}); } export const emptyContextObject: {} = {}; if (__DEV__) { Object.freeze(emptyContextObject); } export function getMaskedContext(type: any, unmaskedContext: Object): Object { if (disableLegacyContext) { return emptyContextObject; } else { const contextTypes = type.contextTypes; if (!contextTypes) { return emptyContextObject; } const context: {[string]: $FlowFixMe} = {}; for (const key in contextTypes) { context[key] = unmaskedContext[key]; } if (__DEV__) { const name = getComponentNameFromType(type) || 'Unknown'; checkPropTypes(contextTypes, context, 'context', name); } return context; } } export function processChildContext( instance: any, type: any, parentContext: Object, childContextTypes: Object, ): Object { if (disableLegacyContext) { return parentContext; } else { // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. if (typeof instance.getChildContext !== 'function') { if (__DEV__) { const componentName = getComponentNameFromType(type) || 'Unknown'; if (!warnedAboutMissingGetChildContext[componentName]) { warnedAboutMissingGetChildContext[componentName] = true; console.error( '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName, ); } } return parentContext; } const childContext = instance.getChildContext(); for (const contextKey in childContext) { if (!(contextKey in childContextTypes)) { throw new Error( `${ getComponentNameFromType(type) || 'Unknown' }.getChildContext(): key "${contextKey}" is not defined in childContextTypes.`, ); } } if (__DEV__) { const name = getComponentNameFromType(type) || 'Unknown'; checkPropTypes(childContextTypes, childContext, 'child context', name); } return {...parentContext, ...childContext}; } }
28.389474
91
0.655321
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {useEffect, useRef} from 'react'; import Button from './Button'; import ButtonIcon from './ButtonIcon'; import Icon from './Icon'; import styles from './SearchInput.css'; type Props = { goToNextResult: () => void, goToPreviousResult: () => void, placeholder: string, search: (text: string) => void, searchIndex: number, searchResultsCount: number, searchText: string, testName?: ?string, }; export default function SearchInput({ goToNextResult, goToPreviousResult, placeholder, search, searchIndex, searchResultsCount, searchText, testName, }: Props): React.Node { const inputRef = useRef<HTMLInputElement | null>(null); const resetSearch = () => search(''); // $FlowFixMe[missing-local-annot] const handleChange = ({currentTarget}) => { search(currentTarget.value); }; // $FlowFixMe[missing-local-annot] const handleKeyPress = ({key, shiftKey}) => { if (key === 'Enter') { if (shiftKey) { goToPreviousResult(); } else { goToNextResult(); } } }; // Auto-focus search input useEffect(() => { if (inputRef.current === null) { return () => {}; } const handleKeyDown = (event: KeyboardEvent) => { const {key, metaKey} = event; if (key === 'f' && metaKey) { if (inputRef.current !== null) { inputRef.current.focus(); event.preventDefault(); event.stopPropagation(); } } }; // It's important to listen to the ownerDocument to support the browser extension. // Here we use portals to render individual tabs (e.g. Profiler), // and the root document might belong to a different window. const ownerDocument = inputRef.current.ownerDocument; ownerDocument.addEventListener('keydown', handleKeyDown); return () => ownerDocument.removeEventListener('keydown', handleKeyDown); }, []); return ( <div className={styles.SearchInput} data-testname={testName}> <Icon className={styles.InputIcon} type="search" /> <input data-testname={testName ? `${testName}-Input` : undefined} className={styles.Input} onChange={handleChange} onKeyPress={handleKeyPress} placeholder={placeholder} ref={inputRef} value={searchText} /> {!!searchText && ( <React.Fragment> <span className={styles.IndexLabel} data-testname={testName ? `${testName}-ResultsCount` : undefined}> {Math.min(searchIndex + 1, searchResultsCount)} |{' '} {searchResultsCount} </span> <div className={styles.LeftVRule} /> <Button data-testname={testName ? `${testName}-PreviousButton` : undefined} disabled={!searchText} onClick={goToPreviousResult} title={ <React.Fragment> Scroll to previous search result (<kbd>Shift</kbd> +{' '} <kbd>Enter</kbd>) </React.Fragment> }> <ButtonIcon type="up" /> </Button> <Button data-testname={testName ? `${testName}-NextButton` : undefined} disabled={!searchText} onClick={goToNextResult} title={ <React.Fragment> Scroll to next search result (<kbd>Enter</kbd>) </React.Fragment> }> <ButtonIcon type="down" /> </Button> <Button data-testname={testName ? `${testName}-ResetButton` : undefined} disabled={!searchText} onClick={resetSearch} title="Reset search"> <ButtonIcon type="close" /> </Button> </React.Fragment> )} </div> ); }
27.8
86
0.580005
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 {ReactNativeType} from './src/ReactNativeTypes'; import * as ReactNative from './src/ReactNativeRenderer'; // Assert that the exports line up with the type we're going to expose. // eslint-disable-next-line ft-flow/no-unused-expressions (ReactNative: ReactNativeType); export * from './src/ReactNativeRenderer';
30.176471
71
0.73913
PenTestScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactContext, Thenable} from 'shared/ReactTypes'; import * as React from 'react'; import {createLRU} from './LRU'; interface Suspender { then(resolve: () => mixed, reject: () => mixed): mixed; } type PendingResult = { status: 0, value: Suspender, }; type ResolvedResult<V> = { status: 1, value: V, }; type RejectedResult = { status: 2, value: mixed, }; type Result<V> = PendingResult | ResolvedResult<V> | RejectedResult; type Resource<I, V> = { read(I): V, preload(I): void, ... }; const Pending = 0; const Resolved = 1; const Rejected = 2; const ReactCurrentDispatcher = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .ReactCurrentDispatcher; function readContext(Context: ReactContext<mixed>) { const dispatcher = ReactCurrentDispatcher.current; if (dispatcher === null) { // This wasn't being minified but we're going to retire this package anyway. // eslint-disable-next-line react-internal/prod-error-codes throw new Error( 'react-cache: read and preload may only be called from within a ' + "component's render. They are not supported in event handlers or " + 'lifecycle methods.', ); } return dispatcher.readContext(Context); } // $FlowFixMe[missing-local-annot] function identityHashFn(input) { if (__DEV__) { if ( typeof input !== 'string' && typeof input !== 'number' && typeof input !== 'boolean' && input !== undefined && input !== null ) { console.error( 'Invalid key type. Expected a string, number, symbol, or boolean, ' + 'but instead received: %s' + '\n\nTo use non-primitive values as keys, you must pass a hash ' + 'function as the second argument to createResource().', input, ); } } return input; } const CACHE_LIMIT = 500; const lru = createLRU<$FlowFixMe>(CACHE_LIMIT); const entries: Map<Resource<any, any>, Map<any, any>> = new Map(); const CacheContext = React.createContext<mixed>(null); function accessResult<I, K, V>( resource: any, fetch: I => Thenable<V>, input: I, key: K, ): Result<V> { let entriesForResource = entries.get(resource); if (entriesForResource === undefined) { entriesForResource = new Map(); entries.set(resource, entriesForResource); } const entry = entriesForResource.get(key); if (entry === undefined) { const thenable = fetch(input); thenable.then( value => { if (newResult.status === Pending) { const resolvedResult: ResolvedResult<V> = (newResult: any); resolvedResult.status = Resolved; resolvedResult.value = value; } }, error => { if (newResult.status === Pending) { const rejectedResult: RejectedResult = (newResult: any); rejectedResult.status = Rejected; rejectedResult.value = error; } }, ); const newResult: PendingResult = { status: Pending, value: thenable, }; const newEntry = lru.add(newResult, deleteEntry.bind(null, resource, key)); entriesForResource.set(key, newEntry); return newResult; } else { return (lru.access(entry): any); } } function deleteEntry(resource: any, key: mixed) { const entriesForResource = entries.get(resource); if (entriesForResource !== undefined) { entriesForResource.delete(key); if (entriesForResource.size === 0) { entries.delete(resource); } } } export function unstable_createResource<I, K: string | number, V>( fetch: I => Thenable<V>, maybeHashInput?: I => K, ): Resource<I, V> { const hashInput: I => K = maybeHashInput !== undefined ? maybeHashInput : (identityHashFn: any); const resource = { read(input: I): V { // react-cache currently doesn't rely on context, but it may in the // future, so we read anyway to prevent access outside of render. readContext(CacheContext); const key = hashInput(input); const result: Result<V> = accessResult(resource, fetch, input, key); switch (result.status) { case Pending: { const suspender = result.value; throw suspender; } case Resolved: { const value = result.value; return value; } case Rejected: { const error = result.value; throw error; } default: // Should be unreachable return (undefined: any); } }, preload(input: I): void { // react-cache currently doesn't rely on context, but it may in the // future, so we read anyway to prevent access outside of render. readContext(CacheContext); const key = hashInput(input); accessResult(resource, fetch, input, key); }, }; return resource; } export function unstable_setGlobalCacheLimit(limit: number) { lru.setLimit(limit); }
25.492228
80
0.626956
owtf
import './modern/index';
12
24
0.68
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; const path = require('path'); const rimraf = require('rimraf'); const webpack = require('webpack'); const isProduction = process.env.NODE_ENV === 'production'; rimraf.sync(path.resolve(__dirname, '../build')); webpack( { mode: isProduction ? 'production' : 'development', devtool: isProduction ? 'source-map' : 'cheap-module-source-map', entry: [path.resolve(__dirname, '../src/index.js')], output: { path: path.resolve(__dirname, '../build'), filename: 'main.js', }, module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/, }, ], }, }, (err, stats) => { if (err) { console.error(err.stack || err); if (err.details) { console.error(err.details); } process.exit(1); } const info = stats.toJson(); if (stats.hasErrors()) { console.log('Finished running webpack with errors.'); info.errors.forEach(e => console.error(e)); process.exit(1); } else { console.log('Finished running webpack.'); } } );
23.388889
69
0.571429
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 */ 'use strict'; export type ErrorMap = {[id: string]: string, ...};
21.583333
66
0.67037
owtf
import * as React from 'react'; import {use, Suspense, useState, startTransition} from 'react'; import ReactDOM from 'react-dom/client'; import {createFromFetch, encodeReply} from 'react-server-dom-esm/client'; const moduleBaseURL = '/src/'; let updateRoot; async function callServer(id, args) { const response = fetch('/', { method: 'POST', headers: { Accept: 'text/x-component', 'rsc-action': id, }, body: await encodeReply(args), }); const {returnValue, root} = await createFromFetch(response, { callServer, moduleBaseURL, }); // Refresh the tree with the new RSC payload. startTransition(() => { updateRoot(root); }); return returnValue; } let data = createFromFetch( fetch('/', { headers: { Accept: 'text/x-component', }, }), { callServer, moduleBaseURL, } ); function Shell({data}) { const [root, setRoot] = useState(use(data)); updateRoot = setRoot; return root; } ReactDOM.hydrateRoot(document, React.createElement(Shell, {data}));
21.06383
73
0.648649
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ const ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: (null: null | Fiber), }; export default ReactCurrentOwner;
20.666667
76
0.695205
owtf
System.config({ paths: { react: '../../../../build/oss-experimental/react/umd/react.development.js', 'react-dom': '../../../../build/oss-experimental/react-dom/umd/react-dom.development.js', schedule: '../../../../build/oss-experimental/scheduler/umd/schedule.development', }, });
30
82
0.605178
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. */ // TODO: this is special because it gets imported during build. // // TODO: 18.0.0 has not been released to NPM; // It exists as a placeholder so that DevTools can support work tag changes between releases. // When we next publish a release, update the matching TODO in backend/renderer.js // TODO: This module is used both by the release scripts and to expose a version // at runtime. We should instead inject the version number as part of the build // process, and use the ReactVersions.js module as the single source of truth. export default '18.2.0';
43
93
0.746988
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. */ // Used as a way to call batchedUpdates when we don't have a reference to // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. // Defaults let batchedUpdatesImpl = function (fn, bookkeeping) { return fn(bookkeeping); }; let discreteUpdatesImpl = function (fn, a, b, c, d) { return fn(a, b, c, d); }; let isInsideEventHandler = false; export function batchedUpdates(fn, bookkeeping) { if (isInsideEventHandler) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. return fn(bookkeeping); } isInsideEventHandler = true; try { return batchedUpdatesImpl(fn, bookkeeping); } finally { isInsideEventHandler = false; } } export function discreteUpdates(fn, a, b, c, d) { const prevIsInsideEventHandler = isInsideEventHandler; isInsideEventHandler = true; try { return discreteUpdatesImpl(fn, a, b, c, d); } finally { isInsideEventHandler = prevIsInsideEventHandler; } } export function setBatchingImplementation( _batchedUpdatesImpl, _discreteUpdatesImpl, ) { batchedUpdatesImpl = _batchedUpdatesImpl; discreteUpdatesImpl = _discreteUpdatesImpl; }
28.018182
80
0.731034
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. * * @flow */ import type {ReactClientValue} from 'react-server/src/ReactFlightServer'; export type ServerReference<T: Function> = T & { $$typeof: symbol, $$id: string, $$bound: null | Array<ReactClientValue>, }; // eslint-disable-next-line no-unused-vars export type ClientReference<T> = { $$typeof: symbol, $$id: string, $$async: boolean, }; const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); export function isClientReference(reference: Object): boolean { return reference.$$typeof === CLIENT_REFERENCE_TAG; } export function isServerReference(reference: Object): boolean { return reference.$$typeof === SERVER_REFERENCE_TAG; } export function registerClientReference<T>( proxyImplementation: any, id: string, exportName: string, ): ClientReference<T> { return registerClientReferenceImpl( proxyImplementation, id + '#' + exportName, false, ); } function registerClientReferenceImpl<T>( proxyImplementation: any, id: string, async: boolean, ): ClientReference<T> { return Object.defineProperties(proxyImplementation, { $$typeof: {value: CLIENT_REFERENCE_TAG}, $$id: {value: id}, $$async: {value: async}, }); } // $FlowFixMe[method-unbinding] const FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] const ArraySlice = Array.prototype.slice; function bind(this: ServerReference<any>): any { // $FlowFixMe[unsupported-syntax] const newFn = FunctionBind.apply(this, arguments); if (this.$$typeof === SERVER_REFERENCE_TAG) { const args = ArraySlice.call(arguments, 1); return Object.defineProperties((newFn: any), { $$typeof: {value: SERVER_REFERENCE_TAG}, $$id: {value: this.$$id}, $$bound: {value: this.$$bound ? this.$$bound.concat(args) : args}, bind: {value: bind}, }); } return newFn; } export function registerServerReference<T>( reference: ServerReference<T>, id: string, exportName: null | string, ): ServerReference<T> { return Object.defineProperties((reference: any), { $$typeof: {value: SERVER_REFERENCE_TAG}, $$id: {value: exportName === null ? id : id + '#' + exportName}, $$bound: {value: null}, bind: {value: bind}, }); } const PROMISE_PROTOTYPE = Promise.prototype; const deepProxyHandlers = { get: function (target: Function, name: string, receiver: Proxy<Function>) { switch (name) { // These names are read by the Flight runtime if you end up using the exports object. case '$$typeof': // These names are a little too common. We should probably have a way to // have the Flight runtime extract the inner target instead. return target.$$typeof; case '$$id': return target.$$id; case '$$async': return target.$$async; case 'name': return target.name; case 'displayName': return undefined; // We need to special case this because createElement reads it if we pass this // reference. case 'defaultProps': return undefined; // Avoid this attempting to be serialized. case 'toJSON': return undefined; case Symbol.toPrimitive: // $FlowFixMe[prop-missing] return Object.prototype[Symbol.toPrimitive]; case 'Provider': throw new Error( `Cannot render a Client Context Provider on the Server. ` + `Instead, you can export a Client Component wrapper ` + `that itself renders a Client Context Provider.`, ); } // eslint-disable-next-line react-internal/safe-string-coercion const expression = String(target.name) + '.' + String(name); throw new Error( `Cannot access ${expression} on the server. ` + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.', ); }, set: function () { throw new Error('Cannot assign to a client module from a server module.'); }, }; const proxyHandlers = { get: function ( target: Function, name: string, receiver: Proxy<Function>, ): $FlowFixMe { switch (name) { // These names are read by the Flight runtime if you end up using the exports object. case '$$typeof': return target.$$typeof; case '$$id': return target.$$id; case '$$async': return target.$$async; case 'name': return target.name; // We need to special case this because createElement reads it if we pass this // reference. case 'defaultProps': return undefined; // Avoid this attempting to be serialized. case 'toJSON': return undefined; case Symbol.toPrimitive: // $FlowFixMe[prop-missing] return Object.prototype[Symbol.toPrimitive]; case '__esModule': // Something is conditionally checking which export to use. We'll pretend to be // an ESM compat module but then we'll check again on the client. const moduleId = target.$$id; target.default = registerClientReferenceImpl( (function () { throw new Error( `Attempted to call the default export of ${moduleId} from the server ` + `but it's on the client. It's not possible to invoke a client function from ` + `the server, it can only be rendered as a Component or passed to props of a ` + `Client Component.`, ); }: any), target.$$id + '#', target.$$async, ); return true; case 'then': if (target.then) { // Use a cached value return target.then; } if (!target.$$async) { // If this module is expected to return a Promise (such as an AsyncModule) then // we should resolve that with a client reference that unwraps the Promise on // the client. const clientReference: ClientReference<any> = registerClientReferenceImpl(({}: any), target.$$id, true); const proxy = new Proxy(clientReference, proxyHandlers); // Treat this as a resolved Promise for React's use() target.status = 'fulfilled'; target.value = proxy; const then = (target.then = registerClientReferenceImpl( (function then(resolve, reject: any) { // Expose to React. return Promise.resolve(resolve(proxy)); }: any), // If this is not used as a Promise but is treated as a reference to a `.then` // export then we should treat it as a reference to that name. target.$$id + '#then', false, )); return then; } else { // Since typeof .then === 'function' is a feature test we'd continue recursing // indefinitely if we return a function. Instead, we return an object reference // if we check further. return undefined; } } let cachedReference = target[name]; if (!cachedReference) { const reference: ClientReference<any> = registerClientReferenceImpl( (function () { throw new Error( // eslint-disable-next-line react-internal/safe-string-coercion `Attempted to call ${String(name)}() from the server but ${String( name, )} is on the client. ` + `It's not possible to invoke a client function from the server, it can ` + `only be rendered as a Component or passed to props of a Client Component.`, ); }: any), target.$$id + '#' + name, target.$$async, ); Object.defineProperty((reference: any), 'name', {value: name}); cachedReference = target[name] = new Proxy(reference, deepProxyHandlers); } return cachedReference; }, getPrototypeOf(target: Function): Object { // Pretend to be a Promise in case anyone asks. return PROMISE_PROTOTYPE; }, set: function (): empty { throw new Error('Cannot assign to a client module from a server module.'); }, }; export function createClientModuleProxy<T>( moduleId: string, ): ClientReference<T> { const clientReference: ClientReference<T> = registerClientReferenceImpl( ({}: any), // Represents the whole Module object instead of a particular import. moduleId, false, ); return new Proxy(clientReference, proxyHandlers); }
32.565385
95
0.62331
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'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; global.AsyncLocalStorage = require('async_hooks').AsyncLocalStorage; let React; let ReactDOM; let ReactDOMFizzServer; describe('ReactDOMFizzServerEdge', () => { beforeEach(() => { jest.resetModules(); jest.useRealTimers(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMFizzServer = require('react-dom/server.edge'); }); async function readResult(stream) { const reader = stream.getReader(); let result = ''; while (true) { const {done, value} = await reader.read(); if (done) { return result; } result += Buffer.from(value).toString('utf8'); } } // https://github.com/facebook/react/issues/27540 it('does not try to write to the stream after it has been closed', async () => { async function preloadLate() { await 1; await 1; // need to wait a few microtasks to get the stream to close before this is called ReactDOM.preconnect('foo'); } function Preload() { preloadLate(); return null; } function App() { return ( <html> <body> <main>hello</main> <Preload /> </body> </html> ); } const stream = await ReactDOMFizzServer.renderToReadableStream(<App />); const result = await readResult(stream); // need to wait a macrotask to let the scheduled work from the preconnect to execute await new Promise(resolve => { setTimeout(resolve, 1); }); expect(result).toMatchInlineSnapshot( `"<!DOCTYPE html><html><head></head><body><main>hello</main></body></html>"`, ); }); });
24.974684
88
0.625549
owtf
import React, {PureComponent, startTransition} from 'react'; import {createRoot} from 'react-dom/client'; import _ from 'lodash'; import Charts from './Charts'; import Clock from './Clock'; import './index.css'; let cachedData = new Map(); class App extends PureComponent { state = { value: '', strategy: 'sync', showDemo: true, showClock: false, }; // Random data for the chart getStreamData(input) { if (cachedData.has(input)) { return cachedData.get(input); } const multiplier = input.length !== 0 ? input.length : 1; const complexity = (parseInt(window.location.search.slice(1), 10) / 100) * 25 || 25; const data = _.range(5).map(t => _.range(complexity * multiplier).map((j, i) => { return { x: j, y: (t + 1) * _.random(0, 255), }; }) ); cachedData.set(input, data); return data; } componentDidMount() { window.addEventListener('keydown', e => { if (e.key.toLowerCase() === '?') { e.preventDefault(); this.setState(state => ({ showClock: !state.showClock, })); } }); } handleChartClick = e => { if (this.state.showDemo) { if (e.shiftKey) { this.setState({showDemo: false}); } return; } if (this.state.strategy !== 'async') { this.setState(state => ({ showDemo: !state.showDemo, })); return; } if (this._ignoreClick) { return; } this._ignoreClick = true; startTransition(() => { this.setState({showDemo: true}, () => { this._ignoreClick = false; }); }); }; debouncedHandleChange = _.debounce(value => { if (this.state.strategy === 'debounced') { this.setState({value: value}); } }, 1000); renderOption(strategy, label) { const {strategy: currentStrategy} = this.state; return ( <label className={strategy === currentStrategy ? 'selected' : null}> <input type="radio" checked={strategy === currentStrategy} onChange={() => this.setState({strategy})} /> {label} </label> ); } handleChange = e => { const value = e.target.value; const {strategy} = this.state; switch (strategy) { case 'sync': this.setState({value}); break; case 'debounced': this.debouncedHandleChange(value); break; case 'async': // TODO: useTransition hook instead. startTransition(() => { this.setState({value}); }); break; default: break; } }; render() { const {showClock} = this.state; const data = this.getStreamData(this.state.value); return ( <div className="container"> <div className="rendering"> {this.renderOption('sync', 'Synchronous')} {this.renderOption('debounced', 'Debounced')} {this.renderOption('async', 'Concurrent')} </div> <input className={'input ' + this.state.strategy} placeholder="longer input → more components and DOM nodes" defaultValue={this.state.input} onChange={this.handleChange} /> <div className="demo" onClick={this.handleChartClick}> {this.state.showDemo && ( <Charts data={data} onClick={this.handleChartClick} /> )} <div style={{display: showClock ? 'block' : 'none'}}> <Clock /> </div> </div> </div> ); } } const container = document.getElementById('root'); const root = createRoot(container); root.render(<App />);
23.986395
74
0.543845
Penetration_Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import type {StackCursor} from './ReactFiberStack'; import type {SuspenseProps, SuspenseState} from './ReactFiberSuspenseComponent'; import type {OffscreenState} from './ReactFiberActivityComponent'; import {enableSuspenseAvoidThisFallback} from 'shared/ReactFeatureFlags'; import {createCursor, push, pop} from './ReactFiberStack'; import {isCurrentTreeHidden} from './ReactFiberHiddenContext'; import {OffscreenComponent} from './ReactWorkTags'; // The Suspense handler is the boundary that should capture if something // suspends, i.e. it's the nearest `catch` block on the stack. const suspenseHandlerStackCursor: StackCursor<Fiber | null> = createCursor(null); // Represents the outermost boundary that is not visible in the current tree. // Everything above this is the "shell". When this is null, it means we're // rendering in the shell of the app. If it's non-null, it means we're rendering // deeper than the shell, inside a new tree that wasn't already visible. // // The main way we use this concept is to determine whether showing a fallback // would result in a desirable or undesirable loading state. Activing a fallback // in the shell is considered an undersirable loading state, because it would // mean hiding visible (albeit stale) content in the current tree — we prefer to // show the stale content, rather than switch to a fallback. But showing a // fallback in a new tree is fine, because there's no stale content to // prefer instead. let shellBoundary: Fiber | null = null; export function getShellBoundary(): Fiber | null { return shellBoundary; } export function pushPrimaryTreeSuspenseHandler(handler: Fiber): void { // TODO: Pass as argument const current = handler.alternate; const props: SuspenseProps = handler.pendingProps; // Shallow Suspense context fields, like ForceSuspenseFallback, should only be // propagated a single level. For example, when ForceSuspenseFallback is set, // it should only force the nearest Suspense boundary into fallback mode. pushSuspenseListContext( handler, setDefaultShallowSuspenseListContext(suspenseStackCursor.current), ); // Experimental feature: Some Suspense boundaries are marked as having an // undesirable fallback state. These have special behavior where we only // activate the fallback if there's no other boundary on the stack that we can // use instead. if ( enableSuspenseAvoidThisFallback && props.unstable_avoidThisFallback === true && // If an avoided boundary is already visible, it behaves identically to // a regular Suspense boundary. (current === null || isCurrentTreeHidden()) ) { if (shellBoundary === null) { // We're rendering in the shell. There's no parent Suspense boundary that // can provide a desirable fallback state. We'll use this boundary. push(suspenseHandlerStackCursor, handler, handler); // However, because this is not a desirable fallback, the children are // still considered part of the shell. So we intentionally don't assign // to `shellBoundary`. } else { // There's already a parent Suspense boundary that can provide a desirable // fallback state. Prefer that one. const handlerOnStack = suspenseHandlerStackCursor.current; push(suspenseHandlerStackCursor, handlerOnStack, handler); } return; } // TODO: If the parent Suspense handler already suspended, there's no reason // to push a nested Suspense handler, because it will get replaced by the // outer fallback, anyway. Consider this as a future optimization. push(suspenseHandlerStackCursor, handler, handler); if (shellBoundary === null) { if (current === null || isCurrentTreeHidden()) { // This boundary is not visible in the current UI. shellBoundary = handler; } else { const prevState: SuspenseState = current.memoizedState; if (prevState !== null) { // This boundary is showing a fallback in the current UI. shellBoundary = handler; } } } } export function pushFallbackTreeSuspenseHandler(fiber: Fiber): void { // We're about to render the fallback. If something in the fallback suspends, // it's akin to throwing inside of a `catch` block. This boundary should not // capture. Reuse the existing handler on the stack. reuseSuspenseHandlerOnStack(fiber); } export function pushOffscreenSuspenseHandler(fiber: Fiber): void { if (fiber.tag === OffscreenComponent) { // A SuspenseList context is only pushed here to avoid a push/pop mismatch. // Reuse the current value on the stack. // TODO: We can avoid needing to push here by by forking popSuspenseHandler // into separate functions for Suspense and Offscreen. pushSuspenseListContext(fiber, suspenseStackCursor.current); push(suspenseHandlerStackCursor, fiber, fiber); if (shellBoundary !== null) { // A parent boundary is showing a fallback, so we've already rendered // deeper than the shell. } else { const current = fiber.alternate; if (current !== null) { const prevState: OffscreenState = current.memoizedState; if (prevState !== null) { // This is the first boundary in the stack that's already showing // a fallback. So everything outside is considered the shell. shellBoundary = fiber; } } } } else { // This is a LegacyHidden component. reuseSuspenseHandlerOnStack(fiber); } } export function reuseSuspenseHandlerOnStack(fiber: Fiber) { pushSuspenseListContext(fiber, suspenseStackCursor.current); push(suspenseHandlerStackCursor, getSuspenseHandler(), fiber); } export function getSuspenseHandler(): Fiber | null { return suspenseHandlerStackCursor.current; } export function popSuspenseHandler(fiber: Fiber): void { pop(suspenseHandlerStackCursor, fiber); if (shellBoundary === fiber) { // Popping back into the shell. shellBoundary = null; } popSuspenseListContext(fiber); } // SuspenseList context // TODO: Move to a separate module? We may change the SuspenseList // implementation to hide/show in the commit phase, anyway. export opaque type SuspenseContext = number; export opaque type SubtreeSuspenseContext: SuspenseContext = number; export opaque type ShallowSuspenseContext: SuspenseContext = number; const DefaultSuspenseContext: SuspenseContext = 0b00; const SubtreeSuspenseContextMask: SuspenseContext = 0b01; // ForceSuspenseFallback can be used by SuspenseList to force newly added // items into their fallback state during one of the render passes. export const ForceSuspenseFallback: ShallowSuspenseContext = 0b10; export const suspenseStackCursor: StackCursor<SuspenseContext> = createCursor( DefaultSuspenseContext, ); export function hasSuspenseListContext( parentContext: SuspenseContext, flag: SuspenseContext, ): boolean { return (parentContext & flag) !== 0; } export function setDefaultShallowSuspenseListContext( parentContext: SuspenseContext, ): SuspenseContext { return parentContext & SubtreeSuspenseContextMask; } export function setShallowSuspenseListContext( parentContext: SuspenseContext, shallowContext: ShallowSuspenseContext, ): SuspenseContext { return (parentContext & SubtreeSuspenseContextMask) | shallowContext; } export function pushSuspenseListContext( fiber: Fiber, newContext: SuspenseContext, ): void { push(suspenseStackCursor, newContext, fiber); } export function popSuspenseListContext(fiber: Fiber): void { pop(suspenseStackCursor, fiber); }
37.294118
80
0.742158
PenetrationTestingScripts
const semver = require('semver'); const fs = require('fs'); const ReactVersionSrc = fs.readFileSync(require.resolve('shared/ReactVersion')); const reactVersion = /export default '([^']+)';/.exec(ReactVersionSrc)[1]; const config = { use: { headless: true, browserName: 'chromium', launchOptions: { // This bit of delay gives async React time to render // and DevTools operations to be sent across the bridge. slowMo: 100, }, url: process.env.REACT_VERSION ? 'http://localhost:8080/e2e-regression.html' : 'http://localhost:8080/e2e.html', react_version: process.env.REACT_VERSION ? semver.coerce(process.env.REACT_VERSION).version : reactVersion, trace: 'retain-on-failure', }, // Some of our e2e tests can be flaky. Retry tests to make sure the error isn't transient retries: 3, }; module.exports = config;
30.714286
91
0.668546
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 */ /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ const supportedInputTypes: {[key: string]: true | void, ...} = { color: true, date: true, datetime: true, 'datetime-local': true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true, }; function isTextInputElement(elem: ?HTMLElement): boolean { const nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[((elem: any): HTMLInputElement).type]; } if (nodeName === 'textarea') { return true; } return false; } export default isTextInputElement;
20.347826
114
0.663609
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import typeof ReactTestRenderer from 'react-test-renderer'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {Context} from 'react-devtools-shared/src/devtools/views/Profiler/ProfilerContext'; import type {DispatcherContext} from 'react-devtools-shared/src/devtools/views/Components/TreeContext'; import type Store from 'react-devtools-shared/src/devtools/store'; describe('ProfilerContext', () => { let React; let ReactDOM; let TestRenderer: ReactTestRenderer; let bridge: FrontendBridge; let legacyRender; let store: Store; let utils; let BridgeContext; let ProfilerContext; let ProfilerContextController; let StoreContext; let TreeContextController; let TreeDispatcherContext; let TreeStateContext; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); legacyRender = utils.legacyRender; bridge = global.bridge; store = global.store; store.collapseNodesByDefault = false; store.recordChangeDescriptions = true; React = require('react'); ReactDOM = require('react-dom'); TestRenderer = utils.requireTestRenderer(); BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext; ProfilerContext = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContext; ProfilerContextController = require('react-devtools-shared/src/devtools/views/Profiler/ProfilerContext').ProfilerContextController; StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext; TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController; TreeDispatcherContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeDispatcherContext; TreeStateContext = require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeStateContext; }); const Contexts = ({ children = null, defaultSelectedElementID = null, defaultSelectedElementIndex = null, }: any) => ( <BridgeContext.Provider value={bridge}> <StoreContext.Provider value={store}> <TreeContextController defaultSelectedElementID={defaultSelectedElementID} defaultSelectedElementIndex={defaultSelectedElementIndex}> <ProfilerContextController>{children}</ProfilerContextController> </TreeContextController> </StoreContext.Provider> </BridgeContext.Provider> ); it('updates updates profiling support based on the attached roots', async () => { const Component = () => null; let context: Context = ((null: any): Context); function ContextReader() { context = React.useContext(ProfilerContext); return null; } await utils.actAsync(() => { TestRenderer.create( <Contexts> <ContextReader /> </Contexts>, ); }); expect(context.supportsProfiling).toBe(false); const containerA = document.createElement('div'); const containerB = document.createElement('div'); await utils.actAsync(() => legacyRender(<Component />, containerA)); expect(context.supportsProfiling).toBe(true); await utils.actAsync(() => legacyRender(<Component />, containerB)); await utils.actAsync(() => ReactDOM.unmountComponentAtNode(containerA)); expect(context.supportsProfiling).toBe(true); await utils.actAsync(() => ReactDOM.unmountComponentAtNode(containerB)); expect(context.supportsProfiling).toBe(false); }); it('should gracefully handle an empty profiling session (with no recorded commits)', async () => { const Example = () => null; utils.act(() => legacyRender(<Example />, document.createElement('div'))); let context: Context = ((null: any): Context); function ContextReader() { context = React.useContext(ProfilerContext); return null; } // Profile but don't record any updates. await utils.actAsync(() => store.profilerStore.startProfiling()); await utils.actAsync(() => { TestRenderer.create( <Contexts> <ContextReader /> </Contexts>, ); }); expect(context).not.toBeNull(); expect(context.didRecordCommits).toBe(false); expect(context.isProcessingData).toBe(false); expect(context.isProfiling).toBe(true); expect(context.profilingData).toBe(null); await utils.actAsync(() => store.profilerStore.stopProfiling()); expect(context).not.toBeNull(); expect(context.didRecordCommits).toBe(false); expect(context.isProcessingData).toBe(false); expect(context.isProfiling).toBe(false); expect(context.profilingData).toBe(null); }); it('should auto-select the root ID matching the Components tab selection if it has profiling data', async () => { const Parent = () => <Child />; const Child = () => null; const containerOne = document.createElement('div'); const containerTwo = document.createElement('div'); utils.act(() => legacyRender(<Parent />, containerOne)); utils.act(() => legacyRender(<Parent />, containerTwo)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Parent> <Child> [root] ▾ <Parent> <Child> `); // Profile and record updates to both roots. await utils.actAsync(() => store.profilerStore.startProfiling()); await utils.actAsync(() => legacyRender(<Parent />, containerOne)); await utils.actAsync(() => legacyRender(<Parent />, containerTwo)); await utils.actAsync(() => store.profilerStore.stopProfiling()); let context: Context = ((null: any): Context); function ContextReader() { context = React.useContext(ProfilerContext); return null; } // Select an element within the second root. await utils.actAsync(() => TestRenderer.create( <Contexts defaultSelectedElementID={store.getElementIDAtIndex(3)} defaultSelectedElementIndex={3}> <ContextReader /> </Contexts>, ), ); expect(context).not.toBeNull(); expect(context.rootID).toBe( store.getRootIDForElement(((store.getElementIDAtIndex(3): any): number)), ); }); it('should not select the root ID matching the Components tab selection if it has no profiling data', async () => { const Parent = () => <Child />; const Child = () => null; const containerOne = document.createElement('div'); const containerTwo = document.createElement('div'); utils.act(() => legacyRender(<Parent />, containerOne)); utils.act(() => legacyRender(<Parent />, containerTwo)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Parent> <Child> [root] ▾ <Parent> <Child> `); // Profile and record updates to only the first root. await utils.actAsync(() => store.profilerStore.startProfiling()); await utils.actAsync(() => legacyRender(<Parent />, containerOne)); await utils.actAsync(() => store.profilerStore.stopProfiling()); let context: Context = ((null: any): Context); function ContextReader() { context = React.useContext(ProfilerContext); return null; } // Select an element within the second root. await utils.actAsync(() => TestRenderer.create( <Contexts defaultSelectedElementID={store.getElementIDAtIndex(3)} defaultSelectedElementIndex={3}> <ContextReader /> </Contexts>, ), ); // Verify the default profiling root is the first one. expect(context).not.toBeNull(); expect(context.rootID).toBe( store.getRootIDForElement(((store.getElementIDAtIndex(0): any): number)), ); }); it('should maintain root selection between profiling sessions so long as there is data for that root', async () => { const Parent = () => <Child />; const Child = () => null; const containerA = document.createElement('div'); const containerB = document.createElement('div'); utils.act(() => legacyRender(<Parent />, containerA)); utils.act(() => legacyRender(<Parent />, containerB)); expect(store).toMatchInlineSnapshot(` [root] ▾ <Parent> <Child> [root] ▾ <Parent> <Child> `); // Profile and record updates. await utils.actAsync(() => store.profilerStore.startProfiling()); await utils.actAsync(() => legacyRender(<Parent />, containerA)); await utils.actAsync(() => legacyRender(<Parent />, containerB)); await utils.actAsync(() => store.profilerStore.stopProfiling()); let context: Context = ((null: any): Context); let dispatch: DispatcherContext = ((null: any): DispatcherContext); let selectedElementID = null; function ContextReader() { context = React.useContext(ProfilerContext); dispatch = React.useContext(TreeDispatcherContext); selectedElementID = React.useContext(TreeStateContext).selectedElementID; return null; } const id = ((store.getElementIDAtIndex(3): any): number); // Select an element within the second root. await utils.actAsync(() => TestRenderer.create( <Contexts defaultSelectedElementID={id} defaultSelectedElementIndex={3}> <ContextReader /> </Contexts>, ), ); expect(selectedElementID).toBe(id); // Profile and record more updates to both roots await utils.actAsync(() => store.profilerStore.startProfiling()); await utils.actAsync(() => legacyRender(<Parent />, containerA)); await utils.actAsync(() => legacyRender(<Parent />, containerB)); await utils.actAsync(() => store.profilerStore.stopProfiling()); const otherID = ((store.getElementIDAtIndex(0): any): number); // Change the selected element within a the Components tab. utils.act(() => dispatch({type: 'SELECT_ELEMENT_AT_INDEX', payload: 0})); // Verify that the initial Profiler root selection is maintained. expect(selectedElementID).toBe(otherID); expect(context).not.toBeNull(); expect(context.rootID).toBe(store.getRootIDForElement(id)); }); it('should sync selected element in the Components tab too, provided the element is a match', async () => { const GrandParent = ({includeChild}) => ( <Parent includeChild={includeChild} /> ); const Parent = ({includeChild}) => (includeChild ? <Child /> : null); const Child = () => null; const container = document.createElement('div'); utils.act(() => legacyRender(<GrandParent includeChild={true} />, container), ); expect(store).toMatchInlineSnapshot(` [root] ▾ <GrandParent> ▾ <Parent> <Child> `); const parentID = ((store.getElementIDAtIndex(1): any): number); const childID = ((store.getElementIDAtIndex(2): any): number); // Profile and record updates. await utils.actAsync(() => store.profilerStore.startProfiling()); await utils.actAsync(() => legacyRender(<GrandParent includeChild={true} />, container), ); await utils.actAsync(() => legacyRender(<GrandParent includeChild={false} />, container), ); await utils.actAsync(() => store.profilerStore.stopProfiling()); expect(store).toMatchInlineSnapshot(` [root] ▾ <GrandParent> <Parent> `); let context: Context = ((null: any): Context); let selectedElementID = null; function ContextReader() { context = React.useContext(ProfilerContext); selectedElementID = React.useContext(TreeStateContext).selectedElementID; return null; } await utils.actAsync(() => TestRenderer.create( <Contexts> <ContextReader /> </Contexts>, ), ); expect(selectedElementID).toBeNull(); // Select an element in the Profiler tab and verify that the selection is synced to the Components tab. await utils.actAsync(() => context.selectFiber(parentID, 'Parent')); expect(selectedElementID).toBe(parentID); // Select an unmounted element and verify no Components tab selection doesn't change. await utils.actAsync(() => context.selectFiber(childID, 'Child')); expect(selectedElementID).toBe(parentID); }); });
33.344262
118
0.662662
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 { __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, } = require('ReactDOM'); module.exports = __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactBrowserEventEmitter;
23.5
78
0.716113
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 {AsyncLocalStorage} from 'async_hooks'; import type {Request} from 'react-server/src/ReactFlightServer'; export * from 'react-server-dom-esm/src/ReactFlightServerConfigESMBundler'; export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM'; export const supportsRequestStorage = true; export const requestStorage: AsyncLocalStorage<Request> = new AsyncLocalStorage(); export * from '../ReactFlightServerConfigDebugNoop';
30.047619
75
0.769585
null
'use strict'; const Lighthouse = require('lighthouse'); const chromeLauncher = require('chrome-launcher'); const stats = require('stats-analysis'); const config = require('lighthouse/lighthouse-core/config/perf-config'); const spawn = require('child_process').spawn; const os = require('os'); const timesToRun = 10; function wait(val) { return new Promise(resolve => setTimeout(resolve, val)); } async function runScenario(benchmark, chrome) { const port = chrome.port; const results = await Lighthouse( `http://localhost:8080/${benchmark}/`, { output: 'json', port, }, config ); const perfMarkings = results.lhr.audits['user-timings'].details.items; const entries = perfMarkings .filter(({timingType}) => timingType !== 'Mark') .map(({duration, name}) => ({ entry: name, time: duration, })); entries.push({ entry: 'First Meaningful Paint', time: results.lhr.audits['first-meaningful-paint'].rawValue, }); return entries; } function bootstrap(data) { const len = data.length; const arr = Array(len); for (let j = 0; j < len; j++) { arr[j] = data[(Math.random() * len) | 0]; } return arr; } function calculateStandardErrorOfMean(data) { const means = []; for (let i = 0; i < 10000; i++) { means.push(stats.mean(bootstrap(data))); } return stats.stdev(means); } function calculateAverages(runs) { const data = []; const averages = []; runs.forEach((entries, x) => { entries.forEach(({entry, time}, i) => { if (i >= averages.length) { data.push([time]); averages.push({ entry, mean: 0, sem: 0, }); } else { data[i].push(time); if (x === runs.length - 1) { const dataWithoutOutliers = stats.filterMADoutliers(data[i]); averages[i].mean = stats.mean(dataWithoutOutliers); averages[i].sem = calculateStandardErrorOfMean(data[i]); } } }); }); return averages; } async function initChrome() { const platform = os.platform(); if (platform === 'linux') { process.env.XVFBARGS = '-screen 0, 1024x768x16'; process.env.LIGHTHOUSE_CHROMIUM_PATH = 'chromium-browser'; const child = spawn('xvfb start', [{detached: true, stdio: ['ignore']}]); child.unref(); // wait for chrome to load then continue await wait(3000); return child; } } async function launchChrome(headless) { return await chromeLauncher.launch({ chromeFlags: [headless ? '--headless' : ''], }); } async function runBenchmark(benchmark, headless) { const results = { runs: [], averages: [], }; await initChrome(); for (let i = 0; i < timesToRun; i++) { let chrome = await launchChrome(headless); results.runs.push(await runScenario(benchmark, chrome)); // add a delay or sometimes it confuses lighthouse and it hangs await wait(500); try { await chrome.kill(); } catch (e) {} } results.averages = calculateAverages(results.runs); return results; } module.exports = runBenchmark;
22.603053
77
0.617923
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Cache; let getCacheSignal; let Scheduler; let assertLog; let act; let Suspense; let Activity; let useCacheRefresh; let startTransition; let useState; let cache; let getTextCache; let textCaches; let seededCache; describe('ReactCache', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Cache = React.unstable_Cache; Scheduler = require('scheduler'); act = require('internal-test-utils').act; Suspense = React.Suspense; cache = React.cache; Activity = React.unstable_Activity; getCacheSignal = React.unstable_getCacheSignal; useCacheRefresh = React.unstable_useCacheRefresh; startTransition = React.startTransition; useState = React.useState; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; textCaches = []; seededCache = null; if (gate(flags => flags.enableCache)) { getTextCache = cache(() => { 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 textCache = seededCache; seededCache = null; return textCache; } const data = new Map(); const version = textCaches.length + 1; const textCache = { version, data, resolve(text) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, cleanupScheduled: false, }; data.set(text, newRecord); } else if (record.status === 'pending') { record.value.resolve(); } }, reject(text, error) { const record = data.get(text); if (record === undefined) { const newRecord = { status: 'rejected', value: error, cleanupScheduled: false, }; data.set(text, newRecord); } else if (record.status === 'pending') { record.value.reject(); } }, }; textCaches.push(textCache); return textCache; }); } }); function readText(text) { const signal = getCacheSignal ? getCacheSignal() : null; const textCache = getTextCache(); const record = textCache.data.get(text); if (record !== undefined) { if (!record.cleanupScheduled) { // This record was seeded prior to the abort signal being available: // schedule a cleanup function for it. // TODO: Add ability to cleanup entries seeded w useCacheRefresh() record.cleanupScheduled = true; if (getCacheSignal) { signal.addEventListener('abort', () => { Scheduler.log(`Cache cleanup: ${text} [v${textCache.version}]`); }); } } switch (record.status) { case 'pending': throw record.value; case 'rejected': throw record.value; case 'resolved': return textCache.version; } } else { Scheduler.log(`Cache miss! [${text}]`); let resolve; let reject; const thenable = new Promise((res, rej) => { resolve = res; reject = rej; }).then( value => { if (newRecord.status === 'pending') { newRecord.status = 'resolved'; newRecord.value = value; } }, error => { if (newRecord.status === 'pending') { newRecord.status = 'rejected'; newRecord.value = error; } }, ); thenable.resolve = resolve; thenable.reject = reject; const newRecord = { status: 'pending', value: thenable, cleanupScheduled: true, }; textCache.data.set(text, newRecord); if (getCacheSignal) { signal.addEventListener('abort', () => { Scheduler.log(`Cache cleanup: ${text} [v${textCache.version}]`); }); } 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 = getTextCache(); } seededCache.resolve(text); } function resolveMostRecentTextCache(text) { if (textCaches.length === 0) { throw Error('Cache does not exist.'); } else { // Resolve the most recently created cache. An older cache can by // resolved with `textCaches[index].resolve(text)`. textCaches[textCaches.length - 1].resolve(text); } } // @gate enableCacheElement && enableCache test('render Cache component', async () => { const root = ReactNoop.createRoot(); await act(() => { root.render(<Cache>Hi</Cache>); }); expect(root).toMatchRenderedOutput('Hi'); }); // @gate enableCacheElement && enableCache test('mount new data', async () => { const root = ReactNoop.createRoot(); await act(() => { root.render( <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" /> </Suspense> </Cache>, ); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A']); expect(root).toMatchRenderedOutput('A'); await act(() => { root.render('Bye'); }); // no cleanup: cache is still retained at the root assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCache test('root acts as implicit cache boundary', async () => { const root = ReactNoop.createRoot(); await act(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" /> </Suspense>, ); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A']); expect(root).toMatchRenderedOutput('A'); await act(() => { root.render('Bye'); }); // no cleanup: cache is still retained at the root assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('multiple new Cache boundaries in the same mount share the same, fresh root cache', async () => { function App() { return ( <> <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" /> </Suspense> </Cache> <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" /> </Suspense> </Cache> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App showMore={false} />); }); // Even though there are two new <Cache /> trees, they should share the same // data cache. So there should be only a single cache miss for A. assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A', 'A']); expect(root).toMatchRenderedOutput('AA'); await act(() => { root.render('Bye'); }); // no cleanup: cache is still retained at the root assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('multiple new Cache boundaries in the same update share the same, fresh cache', async () => { function App({showMore}) { return showMore ? ( <> <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" /> </Suspense> </Cache> <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" /> </Suspense> </Cache> </> ) : ( '(empty)' ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App showMore={false} />); }); assertLog([]); expect(root).toMatchRenderedOutput('(empty)'); await act(() => { root.render(<App showMore={true} />); }); // Even though there are two new <Cache /> trees, they should share the same // data cache. So there should be only a single cache miss for A. assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A', 'A']); expect(root).toMatchRenderedOutput('AA'); await act(() => { root.render('Bye'); }); // cleanup occurs for the cache shared by the inner cache boundaries (which // are not shared w the root because they were added in an update) // note that no cache is created for the root since the cache is never accessed assertLog(['Cache cleanup: A [v1]']); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test( 'nested cache boundaries share the same cache as the root during ' + 'the initial render', async () => { function App() { return ( <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" /> <Cache> <AsyncText text="A" /> </Cache> </Suspense> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); // Even though there is a nested <Cache /> boundary, it should share the same // data cache as the root. So there should be only a single cache miss for A. assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A', 'A']); expect(root).toMatchRenderedOutput('AA'); await act(() => { root.render('Bye'); }); // no cleanup: cache is still retained at the root assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }, ); // @gate enableCacheElement && enableCache test('new content inside an existing Cache boundary should re-use already cached data', async () => { function App({showMore}) { return ( <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText showVersion={true} text="A" /> </Suspense> {showMore ? ( <Suspense fallback={<Text text="Loading..." />}> <AsyncText showVersion={true} text="A" /> </Suspense> ) : null} </Cache> ); } const root = ReactNoop.createRoot(); await act(() => { seedNextTextCache('A'); root.render(<App showMore={false} />); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Add a new cache boundary await act(() => { root.render(<App showMore={true} />); }); assertLog([ 'A [v1]', // New tree should use already cached data 'A [v1]', ]); expect(root).toMatchRenderedOutput('A [v1]A [v1]'); await act(() => { root.render('Bye'); }); // no cleanup: cache is still retained at the root assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('a new Cache boundary uses fresh cache', async () => { // The only difference from the previous test is that the "Show More" // content is wrapped in a nested <Cache /> boundary function App({showMore}) { return ( <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText showVersion={true} text="A" /> </Suspense> {showMore ? ( <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText showVersion={true} text="A" /> </Suspense> </Cache> ) : null} </Cache> ); } const root = ReactNoop.createRoot(); await act(() => { seedNextTextCache('A'); root.render(<App showMore={false} />); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Add a new cache boundary await act(() => { root.render(<App showMore={true} />); }); assertLog([ 'A [v1]', // New tree should load fresh data. 'Cache miss! [A]', 'Loading...', ]); expect(root).toMatchRenderedOutput('A [v1]Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v2]']); expect(root).toMatchRenderedOutput('A [v1]A [v2]'); // Replace all the children: this should retain the root Cache instance, // but cleanup the separate cache instance created for the fresh cache // boundary await act(() => { root.render('Bye!'); }); // Cleanup occurs for the *second* cache instance: the first is still // referenced by the root assertLog(['Cache cleanup: A [v2]']); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test('inner/outer cache boundaries uses the same cache instance on initial render', async () => { const root = ReactNoop.createRoot(); function App() { return ( <Cache> <Suspense fallback={<Text text="Loading shell..." />}> {/* The shell reads A */} <Shell> {/* The inner content reads both A and B */} <Suspense fallback={<Text text="Loading content..." />}> <Cache> <Content /> </Cache> </Suspense> </Shell> </Suspense> </Cache> ); } function Shell({children}) { readText('A'); return ( <> <div> <Text text="Shell" /> </div> <div>{children}</div> </> ); } function Content() { readText('A'); readText('B'); return <Text text="Content" />; } await act(() => { root.render(<App />); }); assertLog(['Cache miss! [A]', 'Loading shell...']); expect(root).toMatchRenderedOutput('Loading shell...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog([ 'Shell', // There's a cache miss for B, because it hasn't been read yet. But not // A, because it was cached when we rendered the shell. 'Cache miss! [B]', 'Loading content...', ]); expect(root).toMatchRenderedOutput( <> <div>Shell</div> <div>Loading content...</div> </>, ); await act(() => { resolveMostRecentTextCache('B'); }); assertLog(['Content']); expect(root).toMatchRenderedOutput( <> <div>Shell</div> <div>Content</div> </>, ); await act(() => { root.render('Bye'); }); // no cleanup: cache is still retained at the root assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('inner/ outer cache boundaries added in the same update use the same cache instance', async () => { const root = ReactNoop.createRoot(); function App({showMore}) { return showMore ? ( <Cache> <Suspense fallback={<Text text="Loading shell..." />}> {/* The shell reads A */} <Shell> {/* The inner content reads both A and B */} <Suspense fallback={<Text text="Loading content..." />}> <Cache> <Content /> </Cache> </Suspense> </Shell> </Suspense> </Cache> ) : ( '(empty)' ); } function Shell({children}) { readText('A'); return ( <> <div> <Text text="Shell" /> </div> <div>{children}</div> </> ); } function Content() { readText('A'); readText('B'); return <Text text="Content" />; } await act(() => { root.render(<App showMore={false} />); }); assertLog([]); expect(root).toMatchRenderedOutput('(empty)'); await act(() => { root.render(<App showMore={true} />); }); assertLog(['Cache miss! [A]', 'Loading shell...']); expect(root).toMatchRenderedOutput('Loading shell...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog([ 'Shell', // There's a cache miss for B, because it hasn't been read yet. But not // A, because it was cached when we rendered the shell. 'Cache miss! [B]', 'Loading content...', ]); expect(root).toMatchRenderedOutput( <> <div>Shell</div> <div>Loading content...</div> </>, ); await act(() => { resolveMostRecentTextCache('B'); }); assertLog(['Content']); expect(root).toMatchRenderedOutput( <> <div>Shell</div> <div>Content</div> </>, ); await act(() => { root.render('Bye'); }); assertLog(['Cache cleanup: A [v1]', 'Cache cleanup: B [v1]']); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCache test('refresh a cache boundary', async () => { let refresh; function App() { refresh = useCacheRefresh(); return <AsyncText showVersion={true} text="A" />; } // Mount initial data const root = ReactNoop.createRoot(); await act(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <App /> </Suspense>, ); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Refresh for new data. await act(() => { startTransition(() => refresh()); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('A [v1]'); await act(() => { resolveMostRecentTextCache('A'); }); // Note that the version has updated if (getCacheSignal) { assertLog(['A [v2]', 'Cache cleanup: A [v1]']); } else { assertLog(['A [v2]']); } expect(root).toMatchRenderedOutput('A [v2]'); await act(() => { root.render('Bye'); }); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('refresh the root cache', async () => { let refresh; function App() { refresh = useCacheRefresh(); return <AsyncText showVersion={true} text="A" />; } // Mount initial data const root = ReactNoop.createRoot(); await act(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <App /> </Suspense>, ); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Refresh for new data. await act(() => { startTransition(() => refresh()); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('A [v1]'); await act(() => { resolveMostRecentTextCache('A'); }); // Note that the version has updated, and the previous cache is cleared assertLog(['A [v2]', 'Cache cleanup: A [v1]']); expect(root).toMatchRenderedOutput('A [v2]'); await act(() => { root.render('Bye'); }); // the original root cache already cleaned up when the refresh completed assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('refresh the root cache without a transition', async () => { let refresh; function App() { refresh = useCacheRefresh(); return <AsyncText showVersion={true} text="A" />; } // Mount initial data const root = ReactNoop.createRoot(); await act(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <App /> </Suspense>, ); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Refresh for new data. await act(() => { refresh(); }); assertLog([ 'Cache miss! [A]', 'Loading...', // The v1 cache can be cleaned up since everything that references it has // been replaced by a fallback. When the boundary switches back to visible // it will use the v2 cache. 'Cache cleanup: A [v1]', ]); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); // Note that the version has updated, and the previous cache is cleared assertLog(['A [v2]']); expect(root).toMatchRenderedOutput('A [v2]'); await act(() => { root.render('Bye'); }); // the original root cache already cleaned up when the refresh completed assertLog([]); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('refresh a cache with seed data', async () => { let refreshWithSeed; function App() { const refresh = useCacheRefresh(); const [seed, setSeed] = useState({fn: null}); if (seed.fn) { seed.fn(); seed.fn = null; } refreshWithSeed = fn => { setSeed({fn}); refresh(); }; return <AsyncText showVersion={true} text="A" />; } // Mount initial data const root = ReactNoop.createRoot(); await act(() => { root.render( <Cache> <Suspense fallback={<Text text="Loading..." />}> <App /> </Suspense> </Cache>, ); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Refresh for new data. await act(() => { // Refresh the cache with seeded data, like you would receive from a // server mutation. // TODO: Seeding multiple typed textCaches. Should work by calling `refresh` // multiple times with different key/value pairs startTransition(() => refreshWithSeed(() => { const textCache = getTextCache(); textCache.resolve('A'); }), ); }); // The root should re-render without a cache miss. // The cache is not cleared up yet, since it's still reference by the root assertLog(['A [v2]']); expect(root).toMatchRenderedOutput('A [v2]'); await act(() => { root.render('Bye'); }); // the refreshed cache boundary is unmounted and cleans up assertLog(['Cache cleanup: A [v2]']); expect(root).toMatchRenderedOutput('Bye'); }); // @gate enableCacheElement && enableCache test('refreshing a parent cache also refreshes its children', async () => { let refreshShell; function RefreshShell() { refreshShell = useCacheRefresh(); return null; } function App({showMore}) { return ( <Cache> <RefreshShell /> <Suspense fallback={<Text text="Loading..." />}> <AsyncText showVersion={true} text="A" /> </Suspense> {showMore ? ( <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText showVersion={true} text="A" /> </Suspense> </Cache> ) : null} </Cache> ); } const root = ReactNoop.createRoot(); await act(() => { seedNextTextCache('A'); root.render(<App showMore={false} />); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Add a new cache boundary await act(() => { seedNextTextCache('A'); root.render(<App showMore={true} />); }); assertLog([ 'A [v1]', // New tree should load fresh data. 'A [v2]', ]); expect(root).toMatchRenderedOutput('A [v1]A [v2]'); // Now refresh the shell. This should also cause the "Show More" contents to // refresh, since its cache is nested inside the outer one. await act(() => { startTransition(() => refreshShell()); }); assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']); expect(root).toMatchRenderedOutput('A [v1]A [v2]'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog([ 'A [v3]', 'A [v3]', // once the refresh completes the inner showMore boundary frees its previous // cache instance, since it is now using the refreshed parent instance. 'Cache cleanup: A [v2]', ]); expect(root).toMatchRenderedOutput('A [v3]A [v3]'); await act(() => { root.render('Bye!'); }); // Unmounting children releases the refreshed cache instance only; the root // still retains the original cache instance used for the first render assertLog(['Cache cleanup: A [v3]']); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test( 'refreshing a cache boundary does not refresh the other boundaries ' + 'that mounted at the same time (i.e. the ones that share the same cache)', async () => { let refreshFirstBoundary; function RefreshFirstBoundary() { refreshFirstBoundary = useCacheRefresh(); return null; } function App({showMore}) { return showMore ? ( <> <Cache> <Suspense fallback={<Text text="Loading..." />}> <RefreshFirstBoundary /> <AsyncText showVersion={true} text="A" /> </Suspense> </Cache> <Cache> <Suspense fallback={<Text text="Loading..." />}> <AsyncText showVersion={true} text="A" /> </Suspense> </Cache> </> ) : null; } // First mount the initial shell without the nested boundaries. This is // necessary for this test because we want the two inner boundaries to be // treated like sibling providers that happen to share an underlying // cache, as opposed to consumers of the root-level cache. const root = ReactNoop.createRoot(); await act(() => { root.render(<App showMore={false} />); }); // Now reveal the boundaries. In a real app this would be a navigation. await act(() => { root.render(<App showMore={true} />); }); // Even though there are two new <Cache /> trees, they should share the same // data cache. So there should be only a single cache miss for A. assertLog(['Cache miss! [A]', 'Loading...', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]', 'A [v1]']); expect(root).toMatchRenderedOutput('A [v1]A [v1]'); // Refresh the first boundary. It should not refresh the second boundary, // even though they previously shared the same underlying cache. await act(async () => { await refreshFirstBoundary(); }); assertLog(['Cache miss! [A]', 'Loading...']); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v2]']); expect(root).toMatchRenderedOutput('A [v2]A [v1]'); // Unmount children: this should clear *both* cache instances: // the root doesn't have a cache instance (since it wasn't accessed // during the initial render, and all subsequent cache accesses were within // a fresh boundary). Therefore this causes cleanup for both the fresh cache // instance in the refreshed first boundary and cleanup for the non-refreshed // sibling boundary. await act(() => { root.render('Bye!'); }); assertLog(['Cache cleanup: A [v2]', 'Cache cleanup: A [v1]']); expect(root).toMatchRenderedOutput('Bye!'); }, ); // @gate enableCacheElement && enableCache test( 'mount a new Cache boundary in a sibling while simultaneously ' + 'resolving a Suspense boundary', async () => { function App({showMore}) { return ( <> {showMore ? ( <Suspense fallback={<Text text="Loading..." />}> <Cache> <AsyncText showVersion={true} text="A" /> </Cache> </Suspense> ) : null} <Suspense fallback={<Text text="Loading..." />}> <Cache> {' '} <AsyncText showVersion={true} text="A" />{' '} <AsyncText showVersion={true} text="B" /> </Cache> </Suspense> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App showMore={false} />); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { // This will resolve the content in the first cache resolveMostRecentTextCache('A'); resolveMostRecentTextCache('B'); // And mount the second tree, which includes new content root.render(<App showMore={true} />); }); assertLog([ // The new tree should use a fresh cache 'Cache miss! [A]', 'Loading...', // The other tree uses the cached responses. This demonstrates that the // requests are not dropped. 'A [v1]', 'B [v1]', ]); expect(root).toMatchRenderedOutput('Loading... A [v1] B [v1]'); // Now resolve the second tree await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v2]']); expect(root).toMatchRenderedOutput('A [v2] A [v1] B [v1]'); await act(() => { root.render('Bye!'); }); // Unmounting children releases both cache boundaries, but the original // cache instance (used by second boundary) is still referenced by the root. // only the second cache instance is freed. assertLog(['Cache cleanup: A [v2]']); expect(root).toMatchRenderedOutput('Bye!'); }, ); // @gate enableCacheElement && enableCache test('cache pool is cleared once transitions that depend on it commit their shell', async () => { function Child({text}) { return ( <Cache> <AsyncText showVersion={true} text={text} /> </Cache> ); } const root = ReactNoop.createRoot(); await act(() => { root.render( <Suspense fallback={<Text text="Loading..." />}>(empty)</Suspense>, ); }); assertLog([]); expect(root).toMatchRenderedOutput('(empty)'); await act(() => { startTransition(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <Child text="A" /> </Suspense>, ); }); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('(empty)'); await act(() => { startTransition(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <Child text="A" /> <Child text="A" /> </Suspense>, ); }); }); assertLog([ // No cache miss, because it uses the pooled cache 'Loading...', ]); expect(root).toMatchRenderedOutput('(empty)'); // Resolve the request await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]', 'A [v1]']); expect(root).toMatchRenderedOutput('A [v1]A [v1]'); // Now do another transition await act(() => { startTransition(() => { root.render( <Suspense fallback={<Text text="Loading..." />}> <Child text="A" /> <Child text="A" /> <Child text="A" /> </Suspense>, ); }); }); assertLog([ // First two children use the old cache because they already finished 'A [v1]', 'A [v1]', // The new child uses a fresh cache 'Cache miss! [A]', 'Loading...', ]); expect(root).toMatchRenderedOutput('A [v1]A [v1]'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]', 'A [v1]', 'A [v2]']); expect(root).toMatchRenderedOutput('A [v1]A [v1]A [v2]'); // Unmount children: the first text cache instance is created only after the root // commits, so both fresh cache instances are released by their cache boundaries, // cleaning up v1 (used for the first two children which render together) and // v2 (used for the third boundary added later). await act(() => { root.render('Bye!'); }); assertLog(['Cache cleanup: A [v1]', 'Cache cleanup: A [v2]']); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test('cache pool is not cleared by arbitrary commits', async () => { function App() { return ( <> <ShowMore /> <Unrelated /> </> ); } let showMore; function ShowMore() { const [shouldShow, _showMore] = useState(false); showMore = () => _showMore(true); return ( <> <Suspense fallback={<Text text="Loading..." />}> {shouldShow ? ( <Cache> <AsyncText showVersion={true} text="A" /> </Cache> ) : null} </Suspense> </> ); } let updateUnrelated; function Unrelated() { const [count, _updateUnrelated] = useState(0); updateUnrelated = _updateUnrelated; return <Text text={String(count)} />; } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['0']); expect(root).toMatchRenderedOutput('0'); await act(() => { startTransition(() => { showMore(); }); }); assertLog(['Cache miss! [A]', 'Loading...']); expect(root).toMatchRenderedOutput('0'); await act(() => { updateUnrelated(1); }); assertLog([ '1', // Happens to re-render the fallback. Doesn't need to, but not relevant // to this test. 'Loading...', ]); expect(root).toMatchRenderedOutput('1'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]1'); // Unmount children: the first text cache instance is created only after initial // render after calling showMore(). This instance is cleaned up when that boundary // is unmounted. Bc root cache instance is never accessed, the inner cache // boundary ends up at v1. await act(() => { root.render('Bye!'); }); assertLog(['Cache cleanup: A [v1]']); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test('cache boundary uses a fresh cache when its key changes', async () => { const root = ReactNoop.createRoot(); seedNextTextCache('A'); await act(() => { root.render( <Suspense fallback="Loading..."> <Cache key="A"> <AsyncText showVersion={true} text="A" /> </Cache> </Suspense>, ); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); seedNextTextCache('B'); await act(() => { root.render( <Suspense fallback="Loading..."> <Cache key="B"> <AsyncText showVersion={true} text="B" /> </Cache> </Suspense>, ); }); assertLog(['B [v2]']); expect(root).toMatchRenderedOutput('B [v2]'); // Unmount children: the fresh cache instance for B cleans up since the cache boundary // is the only owner, while the original cache instance (for A) is still retained by // the root. await act(() => { root.render('Bye!'); }); assertLog(['Cache cleanup: B [v2]']); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test('overlapping transitions after an initial mount use the same fresh cache', async () => { const root = ReactNoop.createRoot(); await act(() => { root.render( <Suspense fallback="Loading..."> <Cache key="A"> <AsyncText showVersion={true} text="A" /> </Cache> </Suspense>, ); }); assertLog(['Cache miss! [A]']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // After a mount, subsequent transitions use a fresh cache await act(() => { startTransition(() => { root.render( <Suspense fallback="Loading..."> <Cache key="B"> <AsyncText showVersion={true} text="B" /> </Cache> </Suspense>, ); }); }); assertLog(['Cache miss! [B]']); expect(root).toMatchRenderedOutput('A [v1]'); // Update to a different text and with a different key for the cache // boundary: this should still use the fresh cache instance created // for the earlier transition await act(() => { startTransition(() => { root.render( <Suspense fallback="Loading..."> <Cache key="C"> <AsyncText showVersion={true} text="C" /> </Cache> </Suspense>, ); }); }); assertLog(['Cache miss! [C]']); expect(root).toMatchRenderedOutput('A [v1]'); await act(() => { resolveMostRecentTextCache('C'); }); assertLog(['C [v2]']); expect(root).toMatchRenderedOutput('C [v2]'); // Unmount children: the fresh cache used for the updates is freed, while the // original cache (with A) is still retained at the root. await act(() => { root.render('Bye!'); }); assertLog(['Cache cleanup: B [v2]', 'Cache cleanup: C [v2]']); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test('overlapping updates after an initial mount use the same fresh cache', async () => { const root = ReactNoop.createRoot(); await act(() => { root.render( <Suspense fallback="Loading..."> <Cache key="A"> <AsyncText showVersion={true} text="A" /> </Cache> </Suspense>, ); }); assertLog(['Cache miss! [A]']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('A'); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // After a mount, subsequent updates use a fresh cache await act(() => { root.render( <Suspense fallback="Loading..."> <Cache key="B"> <AsyncText showVersion={true} text="B" /> </Cache> </Suspense>, ); }); assertLog(['Cache miss! [B]']); expect(root).toMatchRenderedOutput('Loading...'); // A second update uses the same fresh cache: even though this is a new // Cache boundary, the render uses the fresh cache from the pending update. await act(() => { root.render( <Suspense fallback="Loading..."> <Cache key="C"> <AsyncText showVersion={true} text="C" /> </Cache> </Suspense>, ); }); assertLog(['Cache miss! [C]']); expect(root).toMatchRenderedOutput('Loading...'); await act(() => { resolveMostRecentTextCache('C'); }); assertLog(['C [v2]']); expect(root).toMatchRenderedOutput('C [v2]'); // Unmount children: the fresh cache used for the updates is freed, while the // original cache (with A) is still retained at the root. await act(() => { root.render('Bye!'); }); assertLog(['Cache cleanup: B [v2]', 'Cache cleanup: C [v2]']); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test('cleans up cache only used in an aborted transition', async () => { const root = ReactNoop.createRoot(); seedNextTextCache('A'); await act(() => { root.render( <Suspense fallback="Loading..."> <Cache key="A"> <AsyncText showVersion={true} text="A" /> </Cache> </Suspense>, ); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); // Start a transition from A -> B..., which should create a fresh cache // for the new cache boundary (bc of the different key) await act(() => { startTransition(() => { root.render( <Suspense fallback="Loading..."> <Cache key="B"> <AsyncText showVersion={true} text="B" /> </Cache> </Suspense>, ); }); }); assertLog(['Cache miss! [B]']); expect(root).toMatchRenderedOutput('A [v1]'); // ...but cancel by transitioning "back" to A (which we never really left) await act(() => { startTransition(() => { root.render( <Suspense fallback="Loading..."> <Cache key="A"> <AsyncText showVersion={true} text="A" /> </Cache> </Suspense>, ); }); }); assertLog(['A [v1]', 'Cache cleanup: B [v2]']); expect(root).toMatchRenderedOutput('A [v1]'); // Unmount children: ... await act(() => { root.render('Bye!'); }); assertLog([]); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test.skip('if a root cache refresh never commits its fresh cache is released', async () => { const root = ReactNoop.createRoot(); let refresh; function Example({text}) { refresh = useCacheRefresh(); return <AsyncText showVersion={true} text={text} />; } seedNextTextCache('A'); await act(() => { root.render( <Suspense fallback="Loading..."> <Example text="A" /> </Suspense>, ); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); await act(() => { startTransition(() => { refresh(); }); }); assertLog(['Cache miss! [A]']); expect(root).toMatchRenderedOutput('A [v1]'); await act(() => { root.render('Bye!'); }); assertLog([ // TODO: the v1 cache should *not* be cleaned up, it is still retained by the root // The following line is presently yielded but should not be: // 'Cache cleanup: A [v1]', // TODO: the v2 cache *should* be cleaned up, it was created for the abandoned refresh // The following line is presently not yielded but should be: 'Cache cleanup: A [v2]', ]); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableCacheElement && enableCache test.skip('if a cache boundary refresh never commits its fresh cache is released', async () => { const root = ReactNoop.createRoot(); let refresh; function Example({text}) { refresh = useCacheRefresh(); return <AsyncText showVersion={true} text={text} />; } seedNextTextCache('A'); await act(() => { root.render( <Suspense fallback="Loading..."> <Cache> <Example text="A" /> </Cache> </Suspense>, ); }); assertLog(['A [v1]']); expect(root).toMatchRenderedOutput('A [v1]'); await act(() => { startTransition(() => { refresh(); }); }); assertLog(['Cache miss! [A]']); expect(root).toMatchRenderedOutput('A [v1]'); // Unmount the boundary before the refresh can complete await act(() => { root.render('Bye!'); }); assertLog([ // TODO: the v2 cache *should* be cleaned up, it was created for the abandoned refresh // The following line is presently not yielded but should be: 'Cache cleanup: A [v2]', ]); expect(root).toMatchRenderedOutput('Bye!'); }); // @gate enableActivity // @gate enableCache test('prerender a new cache boundary inside an Activity tree', async () => { function App({prerenderMore}) { return ( <Activity mode="hidden"> <div> {prerenderMore ? ( <Cache> <AsyncText text="More" /> </Cache> ) : null} </div> </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App prerenderMore={false} />); }); assertLog([]); expect(root).toMatchRenderedOutput(<div hidden={true} />); seedNextTextCache('More'); await act(() => { root.render(<App prerenderMore={true} />); }); assertLog(['More']); expect(root).toMatchRenderedOutput(<div hidden={true}>More</div>); }); // @gate enableCache it('cache objects and primitive arguments and a mix of them', async () => { const root = ReactNoop.createRoot(); const types = cache((a, b) => ({a: typeof a, b: typeof b})); function Print({a, b}) { return types(a, b).a + ' ' + types(a, b).b + ' '; } function Same({a, b}) { const x = types(a, b); const y = types(a, b); return (x === y).toString() + ' '; } function FlippedOrder({a, b}) { return (types(a, b) === types(b, a)).toString() + ' '; } function FewerArgs({a, b}) { return (types(a, b) === types(a)).toString() + ' '; } function MoreArgs({a, b}) { return (types(a) === types(a, b)).toString() + ' '; } await act(() => { root.render( <> <Print a="e" b="f" /> <Same a="a" b="b" /> <FlippedOrder a="c" b="d" /> <FewerArgs a="e" b="f" /> <MoreArgs a="g" b="h" /> </>, ); }); expect(root).toMatchRenderedOutput('string string true false false false '); await act(() => { root.render( <> <Print a="e" b={null} /> <Same a="a" b={null} /> <FlippedOrder a="c" b={null} /> <FewerArgs a="e" b={null} /> <MoreArgs a="g" b={null} /> </>, ); }); expect(root).toMatchRenderedOutput('string object true false false false '); const obj = {}; await act(() => { root.render( <> <Print a="e" b={obj} /> <Same a="a" b={obj} /> <FlippedOrder a="c" b={obj} /> <FewerArgs a="e" b={obj} /> <MoreArgs a="g" b={obj} /> </>, ); }); expect(root).toMatchRenderedOutput('string object true false false false '); const sameObj = {}; await act(() => { root.render( <> <Print a={sameObj} b={sameObj} /> <Same a={sameObj} b={sameObj} /> <FlippedOrder a={sameObj} b={sameObj} /> <FewerArgs a={sameObj} b={sameObj} /> <MoreArgs a={sameObj} b={sameObj} /> </>, ); }); expect(root).toMatchRenderedOutput('object object true true false false '); const objA = {}; const objB = {}; await act(() => { root.render( <> <Print a={objA} b={objB} /> <Same a={objA} b={objB} /> <FlippedOrder a={objA} b={objB} /> <FewerArgs a={objA} b={objB} /> <MoreArgs a={objA} b={objB} /> </>, ); }); expect(root).toMatchRenderedOutput('object object true false false false '); const sameSymbol = Symbol(); await act(() => { root.render( <> <Print a={sameSymbol} b={sameSymbol} /> <Same a={sameSymbol} b={sameSymbol} /> <FlippedOrder a={sameSymbol} b={sameSymbol} /> <FewerArgs a={sameSymbol} b={sameSymbol} /> <MoreArgs a={sameSymbol} b={sameSymbol} /> </>, ); }); expect(root).toMatchRenderedOutput('symbol symbol true true false false '); const notANumber = +'nan'; await act(() => { root.render( <> <Print a={1} b={notANumber} /> <Same a={1} b={notANumber} /> <FlippedOrder a={1} b={notANumber} /> <FewerArgs a={1} b={notANumber} /> <MoreArgs a={1} b={notANumber} /> </>, ); }); expect(root).toMatchRenderedOutput('number number true false false false '); }); // @gate enableCache it('cached functions that throw should cache the error', async () => { const root = ReactNoop.createRoot(); const throws = cache(v => { throw new Error(v); }); let x; let y; let z; function Test() { try { throws(1); } catch (e) { x = e; } try { throws(1); } catch (e) { y = e; } try { throws(2); } catch (e) { z = e; } return 'Blank'; } await act(() => { root.render(<Test />); }); expect(x).toBe(y); expect(z).not.toBe(x); }); });
27.841387
106
0.537482
null
#!/usr/bin/env node 'use strict'; const chalk = require('chalk'); const {exec} = require('child-process-promise'); const {readFileSync, writeFileSync} = require('fs'); const {readJsonSync, writeJsonSync} = require('fs-extra'); const inquirer = require('inquirer'); const {join, relative} = require('path'); const semver = require('semver'); const { CHANGELOG_PATH, DRY_RUN, MANIFEST_PATHS, PACKAGE_PATHS, PULL_REQUEST_BASE_URL, RELEASE_SCRIPT_TOKEN, ROOT_PATH, } = require('./configuration'); const { checkNPMPermissions, clear, confirmContinue, execRead, } = require('./utils'); // This is the primary control function for this script. async function main() { clear(); await checkNPMPermissions(); const sha = await getPreviousCommitSha(); const [shortCommitLog, formattedCommitLog] = await getCommitLog(sha); console.log(''); console.log( 'This release includes the following commits:', chalk.gray(shortCommitLog) ); console.log(''); const releaseType = await getReleaseType(); const path = join(ROOT_PATH, PACKAGE_PATHS[0]); const previousVersion = readJsonSync(path).version; const {major, minor, patch} = semver(previousVersion); const nextVersion = releaseType === 'minor' ? `${major}.${minor + 1}.0` : `${major}.${minor}.${patch + 1}`; updateChangelog(nextVersion, formattedCommitLog); await reviewChangelogPrompt(); updatePackageVersions(previousVersion, nextVersion); updateManifestVersions(previousVersion, nextVersion); console.log(''); console.log( `Packages and manifests have been updated from version ${chalk.bold( previousVersion )} to ${chalk.bold(nextVersion)}` ); console.log(''); await commitPendingChanges(previousVersion, nextVersion); printFinalInstructions(); } async function commitPendingChanges(previousVersion, nextVersion) { console.log(''); console.log('Committing revision and changelog.'); console.log(chalk.dim(' git add .')); console.log( chalk.dim( ` git commit -m "React DevTools ${previousVersion} -> ${nextVersion}"` ) ); if (!DRY_RUN) { await exec(` git add . git commit -m "React DevTools ${previousVersion} -> ${nextVersion}" `); } console.log(''); console.log(`Please push this commit before continuing:`); console.log(` ${chalk.bold.green('git push')}`); await confirmContinue(); } async function getCommitLog(sha) { let shortLog = ''; let formattedLog = ''; const hasGh = await hasGithubCLI(); const rawLog = await execRead(` git log --topo-order --pretty=format:'%s' ${sha}...HEAD -- packages/react-devtools* `); const lines = rawLog.split('\n'); for (let i = 0; i < lines.length; i++) { const line = lines[i].replace(/^\[devtools\] */i, ''); const match = line.match(/(.+) \(#([0-9]+)\)/); if (match !== null) { const title = match[1]; const pr = match[2]; let username; if (hasGh) { const response = await execRead( `gh api /repos/facebook/react/pulls/${pr}` ); const {user} = JSON.parse(response); username = `[${user.login}](${user.html_url})`; } else { username = '[USERNAME](https://github.com/USERNAME)'; } formattedLog += `\n* ${title} (${username} in [#${pr}](${PULL_REQUEST_BASE_URL}${pr}))`; shortLog += `\n* ${title}`; } else { formattedLog += `\n* ${line}`; shortLog += `\n* ${line}`; } } return [shortLog, formattedLog]; } async function hasGithubCLI() { try { await exec('which gh'); return true; } catch (_) {} return false; } async function getPreviousCommitSha() { const choices = []; const lines = await execRead(` git log --max-count=5 --topo-order --pretty=format:'%H:::%s:::%as' HEAD -- ${join( ROOT_PATH, PACKAGE_PATHS[0] )} `); lines.split('\n').forEach((line, index) => { const [hash, message, date] = line.split(':::'); choices.push({ name: `${chalk.bold(hash)} ${chalk.dim(date)} ${message}`, value: hash, short: date, }); }); const {sha} = await inquirer.prompt([ { type: 'list', name: 'sha', message: 'Which of the commits above marks the last DevTools release?', choices, default: choices[0].value, }, ]); return sha; } async function getReleaseType() { const {releaseType} = await inquirer.prompt([ { type: 'list', name: 'releaseType', message: 'Which type of release is this?', choices: [ { name: 'Minor (new user facing functionality)', value: 'minor', short: 'Minor', }, {name: 'Patch (bug fixes only)', value: 'patch', short: 'Patch'}, ], default: 'patch', }, ]); return releaseType; } function printFinalInstructions() { const buildAndTestcriptPath = join(__dirname, 'build-and-test.js'); const pathToPrint = relative(process.cwd(), buildAndTestcriptPath); console.log(''); console.log('Continue by running the build-and-test script:'); console.log(chalk.bold.green(' ' + pathToPrint)); } async function reviewChangelogPrompt() { console.log(''); console.log( 'The changelog has been updated with commits since the previous release:' ); console.log(` ${chalk.bold(CHANGELOG_PATH)}`); console.log(''); console.log('Please review the new changelog text for the following:'); console.log(' 1. Filter out any non-user-visible changes (e.g. typo fixes)'); console.log(' 2. Organize the list into Features vs Bugfixes'); console.log(' 3. Combine related PRs into a single bullet list'); console.log( ' 4. Replacing the "USERNAME" placeholder text with the GitHub username(s)' ); console.log(''); console.log(` ${chalk.bold.green(`open ${CHANGELOG_PATH}`)}`); await confirmContinue(); } function updateChangelog(nextVersion, commitLog) { const path = join(ROOT_PATH, CHANGELOG_PATH); const oldChangelog = readFileSync(path, 'utf8'); const [beginning, end] = oldChangelog.split(RELEASE_SCRIPT_TOKEN); const dateString = new Date().toLocaleDateString('en-us', { year: 'numeric', month: 'long', day: 'numeric', }); const header = `---\n\n### ${nextVersion}\n${dateString}`; const newChangelog = `${beginning}${RELEASE_SCRIPT_TOKEN}\n\n${header}\n${commitLog}${end}`; console.log(chalk.dim(' Updating changelog: ' + CHANGELOG_PATH)); if (!DRY_RUN) { writeFileSync(path, newChangelog); } } function updateManifestVersions(previousVersion, nextVersion) { MANIFEST_PATHS.forEach(partialPath => { const path = join(ROOT_PATH, partialPath); const json = readJsonSync(path); json.version = nextVersion; if (json.hasOwnProperty('version_name')) { json.version_name = nextVersion; } console.log(chalk.dim(' Updating manifest JSON: ' + partialPath)); if (!DRY_RUN) { writeJsonSync(path, json, {spaces: 2}); } }); } function updatePackageVersions(previousVersion, nextVersion) { PACKAGE_PATHS.forEach(partialPath => { const path = join(ROOT_PATH, partialPath); const json = readJsonSync(path); json.version = nextVersion; for (let key in json.dependencies) { if (key.startsWith('react-devtools')) { const version = json.dependencies[key]; json.dependencies[key] = version.replace(previousVersion, nextVersion); } } console.log(chalk.dim(' Updating package JSON: ' + partialPath)); if (!DRY_RUN) { writeJsonSync(path, json, {spaces: 2}); } }); } main();
25.522648
94
0.631192
cybersecurity-penetration-testing
import {clientRenderBoundary} from './ReactDOMFizzInstructionSetInlineSource'; // This is a string so Closure's advanced compilation mode doesn't mangle it. // eslint-disable-next-line dot-notation window['$RX'] = clientRenderBoundary;
38.666667
78
0.793249
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export default class UnsupportedBridgeOperationError extends Error { constructor(message: string) { super(message); // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace) { Error.captureStackTrace(this, UnsupportedBridgeOperationError); } this.name = 'UnsupportedBridgeOperationError'; } }
25.681818
89
0.723549
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 */ throw new Error('Use react-server-dom-turbopack/client instead.');
23.727273
66
0.708487
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-client/src/ReactFlightClientConfigBrowser'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigBundlerWebpack'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigBundlerWebpackServer'; export * from 'react-server-dom-webpack/src/ReactFlightClientConfigTargetWebpackServer'; export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export const usedWithSSR = true;
39
89
0.790297
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "ComponentUsingHooksIndirectly", { enumerable: true, get: function () { return _ComponentUsingHooksIndirectly.Component; } }); Object.defineProperty(exports, "ComponentWithCustomHook", { enumerable: true, get: function () { return _ComponentWithCustomHook.Component; } }); Object.defineProperty(exports, "ComponentWithExternalCustomHooks", { enumerable: true, get: function () { return _ComponentWithExternalCustomHooks.Component; } }); Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", { enumerable: true, get: function () { return _ComponentWithMultipleHooksPerLine.Component; } }); Object.defineProperty(exports, "ComponentWithNestedHooks", { enumerable: true, get: function () { return _ComponentWithNestedHooks.Component; } }); Object.defineProperty(exports, "ContainingStringSourceMappingURL", { enumerable: true, get: function () { return _ContainingStringSourceMappingURL.Component; } }); Object.defineProperty(exports, "Example", { enumerable: true, get: function () { return _Example.Component; } }); Object.defineProperty(exports, "InlineRequire", { enumerable: true, get: function () { return _InlineRequire.Component; } }); Object.defineProperty(exports, "useTheme", { enumerable: true, get: function () { return _useTheme.default; } }); exports.ToDoList = void 0; var _ComponentUsingHooksIndirectly = require("./ComponentUsingHooksIndirectly"); var _ComponentWithCustomHook = require("./ComponentWithCustomHook"); var _ComponentWithExternalCustomHooks = require("./ComponentWithExternalCustomHooks"); var _ComponentWithMultipleHooksPerLine = require("./ComponentWithMultipleHooksPerLine"); var _ComponentWithNestedHooks = require("./ComponentWithNestedHooks"); var _ContainingStringSourceMappingURL = require("./ContainingStringSourceMappingURL"); var _Example = require("./Example"); var _InlineRequire = require("./InlineRequire"); var ToDoList = _interopRequireWildcard(require("./ToDoList")); exports.ToDoList = ToDoList; var _useTheme = _interopRequireDefault(require("./useTheme")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } //# sourceMappingURL=index.js.map?foo=bar&param=some_value
36.325843
743
0.727793
PenetrationTestingScripts
module.exports = require('./dist/backend');
21.5
43
0.704545
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. * * @format * @flow strict-local */ 'use strict'; const ReactFeatureFlags = { debugRenderPhaseSideEffects: false, }; module.exports = ReactFeatureFlags;
18.444444
66
0.716332
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 type EventSystemFlags = number; export const IS_EVENT_HANDLE_NON_MANAGED_NODE = 1; export const IS_NON_DELEGATED = 1 << 1; export const IS_CAPTURE_PHASE = 1 << 2; export const IS_PASSIVE = 1 << 3; export const IS_LEGACY_FB_SUPPORT_MODE = 1 << 4; export const SHOULD_NOT_DEFER_CLICK_FOR_FB_SUPPORT_MODE = IS_LEGACY_FB_SUPPORT_MODE | IS_CAPTURE_PHASE; // We do not want to defer if the event system has already been // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when // we call willDeferLaterForLegacyFBSupport, thus not bailing out // will result in endless cycles like an infinite loop. // We also don't want to defer during event replaying. export const SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;
34.892857
73
0.738048
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; let JSDOM; let Stream; let React; let ReactDOM; let ReactDOMClient; let ReactDOMFizzServer; let document; let writable; let container; let buffer = ''; let hasErrored = false; let fatalError = undefined; let waitForAll; describe('ReactDOM HostSingleton', () => { beforeEach(() => { jest.resetModules(); JSDOM = require('jsdom').JSDOM; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMFizzServer = require('react-dom/server'); Stream = require('stream'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; // Test Environment const jsdom = new JSDOM( '<!DOCTYPE html><html><head></head><body><div id="container">', { runScripts: 'dangerously', }, ); document = jsdom.window.document; container = document.getElementById('container'); buffer = ''; hasErrored = false; writable = new Stream.PassThrough(); writable.setEncoding('utf8'); writable.on('data', chunk => { buffer += chunk; }); writable.on('error', error => { hasErrored = true; fatalError = error; }); }); async function actIntoEmptyDocument(callback) { await callback(); // Await one turn around the event loop. // This assumes that we'll flush everything we have so far. await new Promise(resolve => { setImmediate(resolve); }); if (hasErrored) { throw fatalError; } const bufferedContent = buffer; buffer = ''; const jsdom = new JSDOM(bufferedContent, { runScripts: 'dangerously', }); document = jsdom.window.document; container = document; } function getVisibleChildren(element) { const children = []; let node = element.firstChild; while (node) { if (node.nodeType === 1) { const el: Element = (node: any); if ( (el.tagName !== 'SCRIPT' && el.tagName !== 'TEMPLATE' && el.tagName !== 'template' && !el.hasAttribute('hidden') && !el.hasAttribute('aria-hidden')) || el.hasAttribute('data-meaningful') ) { const props = {}; const attributes = node.attributes; for (let i = 0; i < attributes.length; i++) { if ( attributes[i].name === 'id' && attributes[i].value.includes(':') ) { // We assume this is a React added ID that's a non-visual implementation detail. continue; } props[attributes[i].name] = attributes[i].value; } props.children = getVisibleChildren(node); children.push(React.createElement(node.tagName.toLowerCase(), props)); } } else if (node.nodeType === 3) { children.push(node.data); } node = node.nextSibling; } return children.length === 0 ? undefined : children.length === 1 ? children[0] : children; } // @gate enableFloat it('warns if you render the same singleton twice at the same time', async () => { const root = ReactDOMClient.createRoot(document); root.render( <html> <head lang="en"> <title>Hello</title> </head> <body /> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head lang="en"> <title>Hello</title> </head> <body /> </html>, ); root.render( <html> <head lang="en"> <title>Hello</title> </head> <head lang="es" data-foo="foo"> <title>Hola</title> </head> <body /> </html>, ); await expect(async () => { await waitForAll([]); }).toErrorDev( 'Warning: You are mounting a new head component when a previous one has not first unmounted. It is an error to render more than one head component at a time and attributes and children of these components will likely fail in unpredictable ways. Please only render a single instance of <head> and if you need to mount a new one, ensure any previous ones have unmounted first', ); expect(getVisibleChildren(document)).toEqual( <html> <head lang="es" data-foo="foo"> <title>Hola</title> <title>Hello</title> </head> <body /> </html>, ); root.render( <html> {null} {null} <head lang="fr"> <title>Bonjour</title> </head> <body /> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head lang="fr"> <title>Bonjour</title> </head> <body /> </html>, ); root.render( <html> <head lang="en"> <title>Hello</title> </head> <body /> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head lang="en"> <title>Hello</title> </head> <body /> </html>, ); }); // @gate enableFloat it('renders into html, head, and body persistently so the node identities never change and extraneous styles are retained', async () => { // Server render some html that will get replaced with a client render await actIntoEmptyDocument(() => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream( <html data-foo="foo"> <head data-bar="bar"> <link rel="stylesheet" href="resource" /> <title>a server title</title> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> </head> <body data-baz="baz"> <div>hello world</div> <style> {` body: { background-color: red; }`} </style> <div>goodbye</div> </body> </html>, ); pipe(writable); }); expect(getVisibleChildren(document)).toEqual( <html data-foo="foo"> <head data-bar="bar"> <title>a server title</title> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> </head> <body data-baz="baz"> <div>hello world</div> <style> {` body: { background-color: red; }`} </style> <div>goodbye</div> </body> </html>, ); const {documentElement, head, body} = document; const persistentElements = [documentElement, head, body]; // Render into the document completely different html. Observe that styles // are retained as are html, body, and head referential identities. Because this was // server rendered and we are not hydrating we lose the semantic placement of the original // head contents and everything gets preprended. In a future update we might emit an insertion // edge from the server and make client rendering reslilient to interstitial placement const root = ReactDOMClient.createRoot(document); root.render( <html data-client-foo="foo"> <head> <title>a client title</title> </head> <body data-client-baz="baz"> <div>hello client</div> </body> </html>, ); await waitForAll([]); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); // Similar to Hydration we don't reset attributes on the instance itself even on a fresh render. expect(getVisibleChildren(document)).toEqual( <html data-client-foo="foo"> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> <title>a client title</title> </head> <body data-client-baz="baz"> <style> {` body: { background-color: red; }`} </style> <div>hello client</div> </body> </html>, ); // Render new children and assert they append in the correct locations root.render( <html data-client-foo="foo"> <head> <title>a client title</title> <meta /> </head> <body data-client-baz="baz"> <p>hello client again</p> <div>hello client</div> </body> </html>, ); await waitForAll([]); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); expect(getVisibleChildren(document)).toEqual( <html data-client-foo="foo"> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> <title>a client title</title> <meta /> </head> <body data-client-baz="baz"> <style> {` body: { background-color: red; }`} </style> <p>hello client again</p> <div>hello client</div> </body> </html>, ); // Remove some children root.render( <html data-client-foo="foo"> <head> <title>a client title</title> </head> <body data-client-baz="baz"> <p>hello client again</p> </body> </html>, ); await waitForAll([]); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); expect(getVisibleChildren(document)).toEqual( <html data-client-foo="foo"> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> <title>a client title</title> </head> <body data-client-baz="baz"> <style> {` body: { background-color: red; }`} </style> <p>hello client again</p> </body> </html>, ); // Remove a persistent component // @TODO figure out whether to clean up attributes. restoring them is likely // not possible. root.render( <html data-client-foo="foo"> <head> <title>a client title</title> </head> </html>, ); await waitForAll([]); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); expect(getVisibleChildren(document)).toEqual( <html data-client-foo="foo"> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> <title>a client title</title> </head> <body> <style> {` body: { background-color: red; }`} </style> </body> </html>, ); // unmount the root root.unmount(); await waitForAll([]); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> </head> <body> <style> {` body: { background-color: red; }`} </style> </body> </html>, ); // Now let's hydrate the document with known mismatching content // We assert that the identities of html, head, and body still haven't changed // and that the embedded styles are still retained const hydrationErrors = []; let hydrateRoot = ReactDOMClient.hydrateRoot( document, <html data-client-foo="foo"> <head> <title>a client title</title> </head> <body data-client-baz="baz"> <div>hello client</div> </body> </html>, { onRecoverableError(error, errorInfo) { hydrationErrors.push([ error.message, errorInfo.componentStack ? errorInfo.componentStack.split('\n')[1].trim() : null, ]); }, }, ); await expect(async () => { await waitForAll([]); }).toErrorDev( [ `Warning: Expected server HTML to contain a matching <div> in <body>. in div (at **) in body (at **) in html (at **)`, `Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>.`, ], {withoutStack: 1}, ); expect(hydrationErrors).toEqual([ [ 'Hydration failed because the initial UI does not match what was rendered on the server.', 'at div', ], [ 'There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.', null, ], ]); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); expect(getVisibleChildren(document)).toEqual( <html data-client-foo="foo"> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> <title>a client title</title> </head> <body data-client-baz="baz"> <style> {` body: { background-color: red; }`} </style> <div>hello client</div> </body> </html>, ); // Reset the tree hydrationErrors.length = 0; hydrateRoot.unmount(); // Now we try hydrating again with matching nodes and we ensure // the retained styles are bound to the hydrated fibers const link = document.querySelector('link[rel="stylesheet"]'); const style = document.querySelector('style'); hydrateRoot = ReactDOMClient.hydrateRoot( document, <html data-client-foo="foo"> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> </head> <body data-client-baz="baz"> <style> {` body: { background-color: red; }`} </style> </body> </html>, { onRecoverableError(error, errorInfo) { hydrationErrors.push([ error.message, errorInfo.componentStack ? errorInfo.componentStack.split('\n')[1].trim() : null, ]); }, }, ); expect(hydrationErrors).toEqual([]); await waitForAll([]); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); expect([link, style]).toEqual([ document.querySelector('link[rel="stylesheet"]'), document.querySelector('style'), ]); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="resource" /> <link rel="stylesheet" href="3rdparty" /> <link rel="stylesheet" href="3rdparty2" /> </head> <body> <style> {` body: { background-color: red; }`} </style> </body> </html>, ); // We unmount a final time and observe that still we retain our persistent nodes // but they style contents which matched in hydration is removed hydrateRoot.unmount(); expect(persistentElements).toEqual([ document.documentElement, document.head, document.body, ]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body /> </html>, ); }); // This test is not supported in this implementation. If we reintroduce insertion edge we should revisit xit('is able to maintain insertions in head and body between tree-adjacent Nodes', async () => { // Server render some html and hydrate on the client await actIntoEmptyDocument(() => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream( <html> <head> <title>title</title> </head> <body> <div>hello</div> </body> </html>, ); pipe(writable); }); const root = ReactDOMClient.hydrateRoot( document, <html> <head> <title>title</title> </head> <body> <div>hello</div> </body> </html>, ); await waitForAll([]); // We construct and insert some artificial stylesheets mimicing what a 3rd party script might do // In the future we could hydrate with these already in the document but the rules are restrictive // still so it would fail and fall back to client rendering const [a, b, c, d, e, f, g, h] = 'abcdefgh'.split('').map(letter => { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = letter; return link; }); const head = document.head; const title = head.firstChild; head.insertBefore(a, title); head.insertBefore(b, title); head.appendChild(c); head.appendChild(d); const bodyContent = document.body.firstChild; const body = document.body; body.insertBefore(e, bodyContent); body.insertBefore(f, bodyContent); body.appendChild(g); body.appendChild(h); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="a" /> <link rel="stylesheet" href="b" /> <title>title</title> <link rel="stylesheet" href="c" /> <link rel="stylesheet" href="d" /> </head> <body> <link rel="stylesheet" href="e" /> <link rel="stylesheet" href="f" /> <div>hello</div> <link rel="stylesheet" href="g" /> <link rel="stylesheet" href="h" /> </body> </html>, ); // Unmount head and change children of body root.render( <html> {null} <body> <div>hello</div> <div>world</div> </body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="a" /> <link rel="stylesheet" href="b" /> <link rel="stylesheet" href="c" /> <link rel="stylesheet" href="d" /> </head> <body> <link rel="stylesheet" href="e" /> <link rel="stylesheet" href="f" /> <div>hello</div> <div>world</div> <link rel="stylesheet" href="g" /> <link rel="stylesheet" href="h" /> </body> </html>, ); // Mount new head and unmount body root.render( <html> <head> <title>a new title</title> </head> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head> <title>a new title</title> <link rel="stylesheet" href="a" /> <link rel="stylesheet" href="b" /> <link rel="stylesheet" href="c" /> <link rel="stylesheet" href="d" /> </head> <body> <link rel="stylesheet" href="e" /> <link rel="stylesheet" href="f" /> <link rel="stylesheet" href="g" /> <link rel="stylesheet" href="h" /> </body> </html>, ); }); it('clears persistent head and body when html is the container', async () => { await actIntoEmptyDocument(() => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream( <html> <head> <link rel="stylesheet" href="headbefore" /> <title>this should be removed</title> <link rel="stylesheet" href="headafter" /> <script data-meaningful="">true</script> </head> <body> <link rel="stylesheet" href="bodybefore" /> <div>this should be removed</div> <link rel="stylesheet" href="bodyafter" /> <script data-meaningful="">true</script> </body> </html>, ); pipe(writable); }); container = document.documentElement; const root = ReactDOMClient.createRoot(container); root.render( <> <head> <title>something new</title> </head> <body> <div>something new</div> </body> </>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="headbefore" /> <link rel="stylesheet" href="headafter" /> <script data-meaningful="">true</script> <title>something new</title> </head> <body> <link rel="stylesheet" href="bodybefore" /> <link rel="stylesheet" href="bodyafter" /> <script data-meaningful="">true</script> <div>something new</div> </body> </html>, ); }); it('clears persistent head when it is the container', async () => { await actIntoEmptyDocument(() => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream( <html> <head> <link rel="stylesheet" href="before" /> <title>this should be removed</title> <link rel="stylesheet" href="after" /> </head> <body /> </html>, ); pipe(writable); }); container = document.head; const root = ReactDOMClient.createRoot(container); root.render(<title>something new</title>); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head> <link rel="stylesheet" href="before" /> <link rel="stylesheet" href="after" /> <title>something new</title> </head> <body /> </html>, ); }); // @gate enableFloat it('clears persistent body when it is the container', async () => { await actIntoEmptyDocument(() => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream( <html> <head /> <body> <link rel="stylesheet" href="before" /> <div>this should be removed</div> <link rel="stylesheet" href="after" /> </body> </html>, ); pipe(writable); }); container = document.body; const root = ReactDOMClient.createRoot(container); root.render(<div>something new</div>); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body> <link rel="stylesheet" href="before" /> <link rel="stylesheet" href="after" /> <div>something new</div> </body> </html>, ); }); it('renders single Text children into HostSingletons correctly', async () => { await actIntoEmptyDocument(() => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream( <html> <head /> <body>foo</body> </html>, ); pipe(writable); }); let root = ReactDOMClient.hydrateRoot( document, <html> <head /> <body>foo</body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>foo</body> </html>, ); root.render( <html> <head /> <body>bar</body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>bar</body> </html>, ); root.unmount(); root = ReactDOMClient.createRoot(document); root.render( <html> <head /> <body>baz</body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>baz</body> </html>, ); }); it('supports going from single text child to many children back to single text child in body', async () => { const root = ReactDOMClient.createRoot(document); root.render( <html> <head /> <body>foo</body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>foo</body> </html>, ); root.render( <html> <head /> <body> <div>foo</div> </body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body> <div>foo</div> </body> </html>, ); root.render( <html> <head /> <body>foo</body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>foo</body> </html>, ); root.render( <html> <head /> <body> <div>foo</div> </body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body> <div>foo</div> </body> </html>, ); }); it('allows for hydrating without a head', async () => { await actIntoEmptyDocument(() => { const {pipe} = ReactDOMFizzServer.renderToPipeableStream( <html> <body>foo</body> </html>, ); pipe(writable); }); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>foo</body> </html>, ); ReactDOMClient.hydrateRoot( document, <html> <body>foo</body> </html>, ); await waitForAll([]); expect(getVisibleChildren(document)).toEqual( <html> <head /> <body>foo</body> </html>, ); }); // https://github.com/facebook/react/issues/26128 it('(#26128) does not throw when rendering at body', async () => { ReactDOM.render(<div />, document.body); }); // https://github.com/facebook/react/issues/26128 it('(#26128) does not throw when rendering at <html>', async () => { ReactDOM.render(<body />, document.documentElement); }); // https://github.com/facebook/react/issues/26128 it('(#26128) does not throw when rendering at document', async () => { ReactDOM.render(<html />, document); }); });
26.342547
381
0.531213
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 minimist = require('minimist'); const runESLint = require('../eslint'); async function main() { console.log('Linting changed files...'); // eslint-disable-next-line no-unused-vars const {_, ...cliOptions} = minimist(process.argv.slice(2)); if (await runESLint({onlyChanged: true, ...cliOptions})) { console.log('Lint passed for changed files.'); } else { console.log('Lint failed for changed files.'); process.exit(1); } } main();
23.035714
66
0.669643
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 * as acorn from 'acorn-loose'; type ResolveContext = { conditions: Array<string>, parentURL: string | void, }; type ResolveFunction = ( string, ResolveContext, ResolveFunction, ) => {url: string} | Promise<{url: string}>; type GetSourceContext = { format: string, }; type GetSourceFunction = ( string, GetSourceContext, GetSourceFunction, ) => Promise<{source: Source}>; type TransformSourceContext = { format: string, url: string, }; type TransformSourceFunction = ( Source, TransformSourceContext, TransformSourceFunction, ) => Promise<{source: Source}>; type LoadContext = { conditions: Array<string>, format: string | null | void, importAssertions: Object, }; type LoadFunction = ( string, LoadContext, LoadFunction, ) => Promise<{format: string, shortCircuit?: boolean, source: Source}>; type Source = string | ArrayBuffer | Uint8Array; let warnedAboutConditionsFlag = false; let stashedGetSource: null | GetSourceFunction = null; let stashedResolve: null | ResolveFunction = null; export async function resolve( specifier: string, context: ResolveContext, defaultResolve: ResolveFunction, ): Promise<{url: string}> { // We stash this in case we end up needing to resolve export * statements later. stashedResolve = defaultResolve; if (!context.conditions.includes('react-server')) { context = { ...context, conditions: [...context.conditions, 'react-server'], }; if (!warnedAboutConditionsFlag) { warnedAboutConditionsFlag = true; // eslint-disable-next-line react-internal/no-production-logging console.warn( 'You did not run Node.js with the `--conditions react-server` flag. ' + 'Any "react-server" override will only work with ESM imports.', ); } } return await defaultResolve(specifier, context, defaultResolve); } export async function getSource( url: string, context: GetSourceContext, defaultGetSource: GetSourceFunction, ): Promise<{source: Source}> { // We stash this in case we end up needing to resolve export * statements later. stashedGetSource = defaultGetSource; return defaultGetSource(url, context, defaultGetSource); } function addLocalExportedNames(names: Map<string, string>, node: any) { switch (node.type) { case 'Identifier': names.set(node.name, node.name); return; case 'ObjectPattern': for (let i = 0; i < node.properties.length; i++) addLocalExportedNames(names, node.properties[i]); return; case 'ArrayPattern': for (let i = 0; i < node.elements.length; i++) { const element = node.elements[i]; if (element) addLocalExportedNames(names, element); } return; case 'Property': addLocalExportedNames(names, node.value); return; case 'AssignmentPattern': addLocalExportedNames(names, node.left); return; case 'RestElement': addLocalExportedNames(names, node.argument); return; case 'ParenthesizedExpression': addLocalExportedNames(names, node.expression); return; } } function transformServerModule( source: string, body: any, url: string, loader: LoadFunction, ): string { // If the same local name is exported more than once, we only need one of the names. const localNames: Map<string, string> = new Map(); const localTypes: Map<string, string> = new Map(); for (let i = 0; i < body.length; i++) { const node = body[i]; switch (node.type) { case 'ExportAllDeclaration': // If export * is used, the other file needs to explicitly opt into "use server" too. break; case 'ExportDefaultDeclaration': if (node.declaration.type === 'Identifier') { localNames.set(node.declaration.name, 'default'); } else if (node.declaration.type === 'FunctionDeclaration') { if (node.declaration.id) { localNames.set(node.declaration.id.name, 'default'); localTypes.set(node.declaration.id.name, 'function'); } else { // TODO: This needs to be rewritten inline because it doesn't have a local name. } } continue; case 'ExportNamedDeclaration': if (node.declaration) { if (node.declaration.type === 'VariableDeclaration') { const declarations = node.declaration.declarations; for (let j = 0; j < declarations.length; j++) { addLocalExportedNames(localNames, declarations[j].id); } } else { const name = node.declaration.id.name; localNames.set(name, name); if (node.declaration.type === 'FunctionDeclaration') { localTypes.set(name, 'function'); } } } if (node.specifiers) { const specifiers = node.specifiers; for (let j = 0; j < specifiers.length; j++) { const specifier = specifiers[j]; localNames.set(specifier.local.name, specifier.exported.name); } } continue; } } if (localNames.size === 0) { return source; } let newSrc = source + '\n\n;'; newSrc += 'import {registerServerReference} from "react-server-dom-esm/server";\n'; localNames.forEach(function (exported, local) { if (localTypes.get(local) !== 'function') { // We first check if the export is a function and if so annotate it. newSrc += 'if (typeof ' + local + ' === "function") '; } newSrc += 'registerServerReference(' + local + ','; newSrc += JSON.stringify(url) + ','; newSrc += JSON.stringify(exported) + ');\n'; }); return newSrc; } function addExportNames(names: Array<string>, node: any) { switch (node.type) { case 'Identifier': names.push(node.name); return; case 'ObjectPattern': for (let i = 0; i < node.properties.length; i++) addExportNames(names, node.properties[i]); return; case 'ArrayPattern': for (let i = 0; i < node.elements.length; i++) { const element = node.elements[i]; if (element) addExportNames(names, element); } return; case 'Property': addExportNames(names, node.value); return; case 'AssignmentPattern': addExportNames(names, node.left); return; case 'RestElement': addExportNames(names, node.argument); return; case 'ParenthesizedExpression': addExportNames(names, node.expression); return; } } function resolveClientImport( specifier: string, parentURL: string, ): {url: string} | Promise<{url: string}> { // Resolve an import specifier as if it was loaded by the client. This doesn't use // the overrides that this loader does but instead reverts to the default. // This resolution algorithm will not necessarily have the same configuration // as the actual client loader. It should mostly work and if it doesn't you can // always convert to explicit exported names instead. const conditions = ['node', 'import']; if (stashedResolve === null) { throw new Error( 'Expected resolve to have been called before transformSource', ); } return stashedResolve(specifier, {conditions, parentURL}, stashedResolve); } async function parseExportNamesInto( body: any, names: Array<string>, parentURL: string, loader: LoadFunction, ): Promise<void> { for (let i = 0; i < body.length; i++) { const node = body[i]; switch (node.type) { case 'ExportAllDeclaration': if (node.exported) { addExportNames(names, node.exported); continue; } else { const {url} = await resolveClientImport(node.source.value, parentURL); const {source} = await loader( url, {format: 'module', conditions: [], importAssertions: {}}, loader, ); if (typeof source !== 'string') { throw new Error('Expected the transformed source to be a string.'); } let childBody; try { childBody = acorn.parse(source, { ecmaVersion: '2024', sourceType: 'module', }).body; } catch (x) { // eslint-disable-next-line react-internal/no-production-logging console.error('Error parsing %s %s', url, x.message); continue; } await parseExportNamesInto(childBody, names, url, loader); continue; } case 'ExportDefaultDeclaration': names.push('default'); continue; case 'ExportNamedDeclaration': if (node.declaration) { if (node.declaration.type === 'VariableDeclaration') { const declarations = node.declaration.declarations; for (let j = 0; j < declarations.length; j++) { addExportNames(names, declarations[j].id); } } else { addExportNames(names, node.declaration.id); } } if (node.specifiers) { const specifiers = node.specifiers; for (let j = 0; j < specifiers.length; j++) { addExportNames(names, specifiers[j].exported); } } continue; } } } async function transformClientModule( body: any, url: string, loader: LoadFunction, ): Promise<string> { const names: Array<string> = []; await parseExportNamesInto(body, names, url, loader); if (names.length === 0) { return ''; } let newSrc = 'import {registerClientReference} from "react-server-dom-esm/server";\n'; for (let i = 0; i < names.length; i++) { const name = names[i]; if (name === 'default') { newSrc += 'export default '; newSrc += 'registerClientReference(function() {'; newSrc += 'throw new Error(' + JSON.stringify( `Attempted to call the default export of ${url} from the server` + `but it's on the client. It's not possible to invoke a client function from ` + `the server, it can only be rendered as a Component or passed to props of a` + `Client Component.`, ) + ');'; } else { newSrc += 'export const ' + name + ' = '; newSrc += 'registerClientReference(function() {'; newSrc += 'throw new Error(' + JSON.stringify( `Attempted to call ${name}() from the server but ${name} is on the client. ` + `It's not possible to invoke a client function from the server, it can ` + `only be rendered as a Component or passed to props of a Client Component.`, ) + ');'; } newSrc += '},'; newSrc += JSON.stringify(url) + ','; newSrc += JSON.stringify(name) + ');\n'; } return newSrc; } async function loadClientImport( url: string, defaultTransformSource: TransformSourceFunction, ): Promise<{format: string, shortCircuit?: boolean, source: Source}> { if (stashedGetSource === null) { throw new Error( 'Expected getSource to have been called before transformSource', ); } // TODO: Validate that this is another module by calling getFormat. const {source} = await stashedGetSource( url, {format: 'module'}, stashedGetSource, ); const result = await defaultTransformSource( source, {format: 'module', url}, defaultTransformSource, ); return {format: 'module', source: result.source}; } async function transformModuleIfNeeded( source: string, url: string, loader: LoadFunction, ): Promise<string> { // Do a quick check for the exact string. If it doesn't exist, don't // bother parsing. if ( source.indexOf('use client') === -1 && source.indexOf('use server') === -1 ) { return source; } let body; try { body = acorn.parse(source, { ecmaVersion: '2024', sourceType: 'module', }).body; } catch (x) { // eslint-disable-next-line react-internal/no-production-logging console.error('Error parsing %s %s', url, x.message); return source; } let useClient = false; let useServer = false; for (let i = 0; i < body.length; i++) { const node = body[i]; if (node.type !== 'ExpressionStatement' || !node.directive) { break; } if (node.directive === 'use client') { useClient = true; } if (node.directive === 'use server') { useServer = true; } } if (!useClient && !useServer) { return source; } if (useClient && useServer) { throw new Error( 'Cannot have both "use client" and "use server" directives in the same file.', ); } if (useClient) { return transformClientModule(body, url, loader); } return transformServerModule(source, body, url, loader); } export async function transformSource( source: Source, context: TransformSourceContext, defaultTransformSource: TransformSourceFunction, ): Promise<{source: Source}> { const transformed = await defaultTransformSource( source, context, defaultTransformSource, ); if (context.format === 'module') { const transformedSource = transformed.source; if (typeof transformedSource !== 'string') { throw new Error('Expected source to have been transformed to a string.'); } const newSrc = await transformModuleIfNeeded( transformedSource, context.url, (url: string, ctx: LoadContext, defaultLoad: LoadFunction) => { return loadClientImport(url, defaultTransformSource); }, ); return {source: newSrc}; } return transformed; } export async function load( url: string, context: LoadContext, defaultLoad: LoadFunction, ): Promise<{format: string, shortCircuit?: boolean, source: Source}> { const result = await defaultLoad(url, context, defaultLoad); if (result.format === 'module') { if (typeof result.source !== 'string') { throw new Error('Expected source to have been loaded into a string.'); } const newSrc = await transformModuleIfNeeded( result.source, url, defaultLoad, ); return {format: 'module', source: newSrc}; } return result; }
28.681818
93
0.622137
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; function initModules() { // Reset warning cache. jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); // Make them available to the helpers. return { ReactDOM, ReactDOMServer, ReactTestUtils, }; } const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('React.Fragment', () => { itRenders('a fragment with one child', async render => { const e = await render( <> <div>text1</div> </>, ); const parent = e.parentNode; expect(parent.childNodes[0].tagName).toBe('DIV'); }); itRenders('a fragment with several children', async render => { const Header = props => { return <p>header</p>; }; const Footer = props => { return ( <> <h2>footer</h2> <h3>about</h3> </> ); }; const e = await render( <> <div>text1</div> <span>text2</span> <Header /> <Footer /> </>, ); const parent = e.parentNode; expect(parent.childNodes[0].tagName).toBe('DIV'); expect(parent.childNodes[1].tagName).toBe('SPAN'); expect(parent.childNodes[2].tagName).toBe('P'); expect(parent.childNodes[3].tagName).toBe('H2'); expect(parent.childNodes[4].tagName).toBe('H3'); }); itRenders('a nested fragment', async render => { const e = await render( <> <> <div>text1</div> </> <span>text2</span> <> <> <> {null} <p /> </> {false} </> </> </>, ); const parent = e.parentNode; expect(parent.childNodes[0].tagName).toBe('DIV'); expect(parent.childNodes[1].tagName).toBe('SPAN'); expect(parent.childNodes[2].tagName).toBe('P'); }); itRenders('an empty fragment', async render => { expect( ( await render( <div> <React.Fragment /> </div>, ) ).firstChild, ).toBe(null); }); }); });
23.109244
93
0.539052
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 */ export {prerender, version} from './src/server/react-dom-server.edge';
24.090909
70
0.701818
owtf
/** @license React v15.7.0 * react-jsx-runtime.production.min.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var f=require("react"),g=60103;exports.Fragment=60107;if("function"===typeof Symbol&&Symbol.for){var h=Symbol.for;g=h("react.element");exports.Fragment=h("react.fragment")}var m=require("react/lib/ReactCurrentOwner"),n=Object.prototype.hasOwnProperty,p={key:!0,ref:!0,__self:!0,__source:!0}; function q(c,a,k){var b,d={},e=null,l=null;void 0!==k&&(e=""+k);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(l=a.ref);for(b in a)n.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:g,type:c,key:e,ref:l,props:d,_owner:m.current}}exports.jsx=q;exports.jsxs=q;
81.545455
345
0.684675
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'; describe('onlyChild', () => { let React; let WrapComponent; beforeEach(() => { React = require('react'); WrapComponent = class extends React.Component { render() { return ( <div> {React.Children.only(this.props.children, this.props.mapFn, this)} </div> ); } }; }); it('should fail when passed two children', () => { expect(function () { const instance = ( <WrapComponent> <div /> <span /> </WrapComponent> ); React.Children.only(instance.props.children); }).toThrow(); }); it('should fail when passed nully values', () => { expect(function () { const instance = <WrapComponent>{null}</WrapComponent>; React.Children.only(instance.props.children); }).toThrow(); expect(function () { const instance = <WrapComponent>{undefined}</WrapComponent>; React.Children.only(instance.props.children); }).toThrow(); }); it('should fail when key/value objects', () => { expect(function () { const instance = <WrapComponent>{[<span key="abc" />]}</WrapComponent>; React.Children.only(instance.props.children); }).toThrow(); }); it('should not fail when passed interpolated single child', () => { expect(function () { const instance = <WrapComponent>{<span />}</WrapComponent>; React.Children.only(instance.props.children); }).not.toThrow(); }); it('should return the only child', () => { const instance = ( <WrapComponent> <span /> </WrapComponent> ); expect(React.Children.only(instance.props.children)).toEqual(<span />); }); });
24.407895
78
0.587047
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 { AnyNativeEvent, EventTypes, } from './legacy-events/PluginModuleType'; import type {TopLevelType} from './legacy-events/TopLevelEventTypes'; import SyntheticEvent from './legacy-events/SyntheticEvent'; // Module provided by RN: import {ReactNativeViewConfigRegistry} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; import accumulateInto from './legacy-events/accumulateInto'; import getListener from './ReactNativeGetListener'; import forEachAccumulated from './legacy-events/forEachAccumulated'; import {HostComponent} from 'react-reconciler/src/ReactWorkTags'; const {customBubblingEventTypes, customDirectEventTypes} = ReactNativeViewConfigRegistry; // Start of inline: the below functions were inlined from // EventPropagator.js, as they deviated from ReactDOM's newer // implementations. // $FlowFixMe[missing-local-annot] function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) { const registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } // $FlowFixMe[missing-local-annot] function accumulateDirectionalDispatches(inst, phase, event) { if (__DEV__) { if (!inst) { console.error('Dispatching inst must not be null'); } } const listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, listener, ); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } // $FlowFixMe[missing-local-annot] function getParent(inst) { do { inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); if (inst) { return inst; } return null; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ export function traverseTwoPhase( inst: Object, fn: Function, arg: Function, skipBubbling: boolean, ) { const path = []; while (inst) { path.push(inst); inst = getParent(inst); } let i; for (i = path.length; i-- > 0; ) { fn(path[i], 'captured', arg); } if (skipBubbling) { // Dispatch on target only fn(path[0], 'bubbled', arg); } else { for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } } // $FlowFixMe[missing-local-annot] function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase( event._targetInst, accumulateDirectionalDispatches, event, false, ); } } // $FlowFixMe[missing-local-annot] function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } // $FlowFixMe[missing-local-annot] function accumulateCapturePhaseDispatches(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { traverseTwoPhase( event._targetInst, accumulateDirectionalDispatches, event, true, ); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches( inst: Object, ignoredDirection: ?boolean, event: Object, ): void { if (inst && event && event.dispatchConfig.registrationName) { const registrationName = event.dispatchConfig.registrationName; const listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto( event._dispatchListeners, listener, ); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event: Object) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateDirectDispatches(events: ?(Array<Object> | Object)) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } // End of inline type PropagationPhases = 'bubbled' | 'captured'; const ReactNativeBridgeEventPlugin = { eventTypes: ({}: EventTypes), extractEvents: function ( topLevelType: TopLevelType, targetInst: null | Object, nativeEvent: AnyNativeEvent, nativeEventTarget: null | Object, ): ?Object { if (targetInst == null) { // Probably a node belonging to another renderer's tree. return null; } const bubbleDispatchConfig = customBubblingEventTypes[topLevelType]; const directDispatchConfig = customDirectEventTypes[topLevelType]; if (!bubbleDispatchConfig && !directDispatchConfig) { throw new Error( // $FlowFixMe[incompatible-type] - Flow doesn't like this string coercion because DOMTopLevelEventType is opaque `Unsupported top level event type "${topLevelType}" dispatched`, ); } const event = SyntheticEvent.getPooled( bubbleDispatchConfig || directDispatchConfig, targetInst, nativeEvent, nativeEventTarget, ); if (bubbleDispatchConfig) { const skipBubbling = event != null && event.dispatchConfig.phasedRegistrationNames != null && event.dispatchConfig.phasedRegistrationNames.skipBubbling; if (skipBubbling) { accumulateCapturePhaseDispatches(event); } else { accumulateTwoPhaseDispatches(event); } } else if (directDispatchConfig) { accumulateDirectDispatches(event); } else { return null; } return event; }, }; export default ReactNativeBridgeEventPlugin;
28.059908
120
0.706741
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 */ /* global Bun */ type BunReadableStreamController = ReadableStreamController & { end(): mixed, write(data: Chunk | BinaryChunk): void, error(error: Error): void, }; export type Destination = BunReadableStreamController; export type PrecomputedChunk = string; export opaque type Chunk = string; export type BinaryChunk = $ArrayBufferView; export function scheduleWork(callback: () => void) { callback(); } export function flushBuffered(destination: Destination) { // WHATWG Streams do not yet have a way to flush the underlying // transform streams. https://github.com/whatwg/streams/issues/960 } export function beginWriting(destination: Destination) {} export function writeChunk( destination: Destination, chunk: PrecomputedChunk | Chunk | BinaryChunk, ): void { if (chunk.length === 0) { return; } destination.write(chunk); } export function writeChunkAndReturn( destination: Destination, chunk: PrecomputedChunk | Chunk | BinaryChunk, ): boolean { return !!destination.write(chunk); } export function completeWriting(destination: Destination) {} export function close(destination: Destination) { destination.end(); } export function stringToChunk(content: string): Chunk { return content; } export function stringToPrecomputedChunk(content: string): PrecomputedChunk { return content; } export function typedArrayToBinaryChunk( content: $ArrayBufferView, ): BinaryChunk { // TODO: Does this needs to be cloned if it's transferred in enqueue()? return content; } export function clonePrecomputedChunk( chunk: PrecomputedChunk, ): PrecomputedChunk { return chunk; } export function byteLengthOfChunk(chunk: Chunk | PrecomputedChunk): number { return Buffer.byteLength(chunk, 'utf8'); } export function byteLengthOfBinaryChunk(chunk: BinaryChunk): number { return chunk.byteLength; } export function closeWithError(destination: Destination, error: mixed): void { if (typeof destination.error === 'function') { // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. destination.error(error); } else { // Earlier implementations doesn't support this method. In that environment you're // supposed to throw from a promise returned but we don't return a promise in our // approach. We could fork this implementation but this is environment is an edge // case to begin with. It's even less common to run this in an older environment. // Even then, this is not where errors are supposed to happen and they get reported // to a global callback in addition to this anyway. So it's fine just to close this. destination.close(); } } export function createFastHash(input: string): string | number { return Bun.hash(input); }
27.352381
101
0.740591
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags'; import typeof * as ExportsType from './ReactFeatureFlags.native-fb'; // NOTE: There are no flags, currently. Uncomment the stuff below if we add one. // Re-export dynamic flags from the internal module. Intentionally using * // because this import is compiled to a `require` call. import * as dynamicFlags from 'ReactNativeInternalFeatureFlags'; // We destructure each value before re-exporting to avoid a dynamic look-up on // the exports object every time a flag is read. export const { alwaysThrottleRetries, enableDeferRootSchedulingToMicrotask, enableUnifiedSyncLane, enableUseRefAccessWarning, passChildrenWhenCloningPersistedNodes, useMicrotasksForSchedulingInFabric, } = dynamicFlags; // The rest of the flags are static for better dead code elimination. export const disableModulePatternComponents = true; export const enableDebugTracing = false; export const enableAsyncDebugInfo = false; export const enableSchedulingProfiler = __PROFILE__; export const enableProfilerTimer = __PROFILE__; export const enableProfilerCommitHooks = __PROFILE__; export const enableProfilerNestedUpdatePhase = __PROFILE__; export const enableProfilerNestedUpdateScheduledHook = false; export const enableUpdaterTracking = __PROFILE__; export const enableCache = false; export const enableLegacyCache = false; export const enableCacheElement = true; export const enableFetchInstrumentation = false; export const enableFormActions = true; // Doesn't affect Native export const enableBinaryFlight = true; export const enableTaint = true; export const enablePostpone = false; export const enableSchedulerDebugging = false; export const debugRenderPhaseSideEffectsForStrictMode = true; export const disableJavaScriptURLs = false; export const disableCommentsAsDOMContainers = true; export const disableInputAttributeSyncing = false; export const disableIEWorkarounds = true; export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__; export const enableScopeAPI = false; export const enableCreateEventHandleAPI = false; export const enableSuspenseCallback = false; export const disableLegacyContext = false; export const enableTrustedTypesIntegration = false; export const disableTextareaChildren = false; export const enableSuspenseAvoidThisFallback = false; export const enableSuspenseAvoidThisFallbackFizz = false; export const enableCPUSuspense = true; export const enableUseMemoCacheHook = true; export const enableUseEffectEventHook = false; export const enableClientRenderFallbackOnTextMismatch = true; export const enableComponentStackLocations = false; export const enableLegacyFBSupport = false; export const enableFilterEmptyStringAttributesDOM = false; export const enableGetInspectorDataForInstanceInProduction = true; export const enableRetryLaneExpiration = false; export const retryLaneExpirationMs = 5000; export const syncLaneExpirationMs = 250; export const transitionLaneExpirationMs = 5000; export const createRootStrictEffectsByDefault = false; export const disableSchedulerTimeoutInWorkLoop = false; export const enableLazyContextPropagation = false; export const enableLegacyHidden = true; export const forceConcurrentByDefaultForTesting = false; export const allowConcurrentByDefault = true; export const enableCustomElementPropertySupport = false; export const consoleManagedByDevToolsDuringStrictMode = false; export const enableServerContext = false; export const enableTransitionTracing = false; export const enableFloat = true; export const useModernStrictMode = false; export const enableDO_NOT_USE_disableStrictPassiveEffect = false; export const enableFizzExternalRuntime = false; export const enableAsyncActions = false; export const enableUseDeferredValueInitialArg = true; // Flow magic to verify the exports of this file match the original version. ((((null: any): ExportsType): FeatureFlagsType): ExportsType);
40.049505
80
0.822919
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {Fragment, useCallback} from 'react'; import Icon from './Icon'; import styles from './TabBar.css'; import Tooltip from './Components/reach-ui/tooltip'; import type {IconType} from './Icon'; type TabInfo = { icon: IconType, id: string, label: string, title?: string, }; export type Props = { currentTab: any, disabled?: boolean, id: string, selectTab: (tabID: any) => void, tabs: Array<TabInfo | null>, type: 'navigation' | 'profiler' | 'settings', }; export default function TabBar({ currentTab, disabled = false, id: groupName, selectTab, tabs, type, }: Props): React.Node { if (!tabs.some(tab => tab !== null && tab.id === currentTab)) { const firstTab = ((tabs.find(tab => tab !== null): any): TabInfo); selectTab(firstTab.id); } const onChange = useCallback( ({currentTarget}: $FlowFixMe) => selectTab(currentTarget.value), [selectTab], ); const handleKeyDown = useCallback((event: $FlowFixMe) => { switch (event.key) { case 'ArrowDown': case 'ArrowLeft': case 'ArrowRight': case 'ArrowUp': event.stopPropagation(); break; default: break; } }, []); let iconSizeClassName; let tabLabelClassName; let tabSizeClassName; switch (type) { case 'navigation': iconSizeClassName = styles.IconSizeNavigation; tabLabelClassName = styles.TabLabelNavigation; tabSizeClassName = styles.TabSizeNavigation; break; case 'profiler': iconSizeClassName = styles.IconSizeProfiler; tabLabelClassName = styles.TabLabelProfiler; tabSizeClassName = styles.TabSizeProfiler; break; case 'settings': iconSizeClassName = styles.IconSizeSettings; tabLabelClassName = styles.TabLabelSettings; tabSizeClassName = styles.TabSizeSettings; break; default: throw Error(`Unsupported type "${type}"`); } return ( <Fragment> {tabs.map(tab => { if (tab === null) { return <div key="VRule" className={styles.VRule} />; } const {icon, id, label, title} = tab; let button = ( <label className={[ tabSizeClassName, disabled ? styles.TabDisabled : styles.Tab, !disabled && currentTab === id ? styles.TabCurrent : '', ].join(' ')} data-testname={`TabBarButton-${id}`} key={id} onKeyDown={handleKeyDown} onMouseDown={() => selectTab(id)}> <input type="radio" className={styles.Input} checked={currentTab === id} disabled={disabled} name={groupName} value={id} onChange={onChange} /> <Icon className={`${ disabled ? styles.IconDisabled : '' } ${iconSizeClassName}`} type={icon} /> <span className={tabLabelClassName}>{label}</span> </label> ); if (title) { button = ( <Tooltip key={id} label={title}> {button} </Tooltip> ); } return button; })} </Fragment> ); }
23.879433
70
0.560878
PenTesting
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-webpack-client.node.unbundled.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-webpack-client.node.unbundled.development.js'); }
33.125
101
0.720588
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 { Layout as LayoutBackend, Style as StyleBackend, } from 'react-devtools-shared/src/backend/NativeStyleEditor/types'; export type Layout = LayoutBackend; export type Style = StyleBackend; export type StyleAndLayout = { layout: LayoutBackend | null, style: StyleBackend | null, };
23.095238
67
0.730693
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local */ 'use strict'; import {type ViewConfig} from './ReactNativeTypes'; // Event configs export const customBubblingEventTypes = {}; export const customDirectEventTypes = {}; const viewConfigCallbacks = new Map(); const viewConfigs = new Map(); function processEventTypes(viewConfig: ViewConfig): void { const {bubblingEventTypes, directEventTypes} = viewConfig; if (__DEV__) { if (bubblingEventTypes != null && directEventTypes != null) { for (const topLevelType in directEventTypes) { if (bubblingEventTypes[topLevelType] != null) { throw new Error( `Event cannot be both direct and bubbling: ${topLevelType}`, ); } } } } if (bubblingEventTypes != null) { for (const topLevelType in bubblingEventTypes) { if (customBubblingEventTypes[topLevelType] == null) { customBubblingEventTypes[topLevelType] = bubblingEventTypes[topLevelType]; } } } if (directEventTypes != null) { for (const topLevelType in directEventTypes) { if (customDirectEventTypes[topLevelType] == null) { customDirectEventTypes[topLevelType] = directEventTypes[topLevelType]; } } } } /** * Registers a native view/component by name. * A callback is provided to load the view config from UIManager. * The callback is deferred until the view is actually rendered. */ export function register(name: string, callback: () => ViewConfig): string { if (viewConfigCallbacks.has(name)) { throw new Error(`Tried to register two views with the same name ${name}`); } if (typeof callback !== 'function') { throw new Error( `View config getter callback for component \`${name}\` must be a function (received \`${ callback === null ? 'null' : typeof callback }\`)`, ); } viewConfigCallbacks.set(name, callback); return name; } /** * Retrieves a config for the specified view. * If this is the first time the view has been used, * This configuration will be lazy-loaded from UIManager. */ export function get(name: string): ViewConfig { let viewConfig; if (!viewConfigs.has(name)) { const callback = viewConfigCallbacks.get(name); if (typeof callback !== 'function') { throw new Error( `View config getter callback for component \`${name}\` must be a function (received \`${ callback === null ? 'null' : typeof callback }\`).${ typeof name[0] === 'string' && /[a-z]/.test(name[0]) ? ' Make sure to start component names with a capital letter.' : '' }`, ); } viewConfig = callback(); processEventTypes(viewConfig); viewConfigs.set(name, viewConfig); // Clear the callback after the config is set so that // we don't mask any errors during registration. viewConfigCallbacks.set(name, null); } else { viewConfig = viewConfigs.get(name); } if (!viewConfig) { throw new Error(`View config not found for name ${name}`); } return viewConfig; }
27.79646
96
0.649247
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 */ export interface Rect { bottom: number; height: number; left: number; right: number; top: number; width: number; } // Get the window object for the document that a node belongs to, // or return null if it cannot be found (node not attached to DOM, // etc). export function getOwnerWindow(node: HTMLElement): typeof window | null { if (!node.ownerDocument) { return null; } return node.ownerDocument.defaultView; } // Get the iframe containing a node, or return null if it cannot // be found (node not within iframe, etc). export function getOwnerIframe(node: HTMLElement): HTMLElement | null { const nodeWindow = getOwnerWindow(node); if (nodeWindow) { return nodeWindow.frameElement; } return null; } // Get a bounding client rect for a node, with an // offset added to compensate for its border. export function getBoundingClientRectWithBorderOffset(node: HTMLElement): Rect { const dimensions = getElementDimensions(node); return mergeRectOffsets([ node.getBoundingClientRect(), { top: dimensions.borderTop, left: dimensions.borderLeft, bottom: dimensions.borderBottom, right: dimensions.borderRight, // This width and height won't get used by mergeRectOffsets (since this // is not the first rect in the array), but we set them so that this // object type checks as a ClientRect. width: 0, height: 0, }, ]); } // Add together the top, left, bottom, and right properties of // each ClientRect, but keep the width and height of the first one. export function mergeRectOffsets(rects: Array<Rect>): Rect { return rects.reduce((previousRect, rect) => { if (previousRect == null) { return rect; } return { top: previousRect.top + rect.top, left: previousRect.left + rect.left, width: previousRect.width, height: previousRect.height, bottom: previousRect.bottom + rect.bottom, right: previousRect.right + rect.right, }; }); } // Calculate a boundingClientRect for a node relative to boundaryWindow, // taking into account any offsets caused by intermediate iframes. export function getNestedBoundingClientRect( node: HTMLElement, boundaryWindow: typeof window, ): Rect { const ownerIframe = getOwnerIframe(node); if (ownerIframe && ownerIframe !== boundaryWindow) { const rects: Array<Rect | ClientRect> = [node.getBoundingClientRect()]; let currentIframe: null | HTMLElement = ownerIframe; let onlyOneMore = false; while (currentIframe) { const rect = getBoundingClientRectWithBorderOffset(currentIframe); rects.push(rect); currentIframe = getOwnerIframe(currentIframe); if (onlyOneMore) { break; } // We don't want to calculate iframe offsets upwards beyond // the iframe containing the boundaryWindow, but we // need to calculate the offset relative to the boundaryWindow. if (currentIframe && getOwnerWindow(currentIframe) === boundaryWindow) { onlyOneMore = true; } } return mergeRectOffsets(rects); } else { return node.getBoundingClientRect(); } } export function getElementDimensions(domElement: Element): { borderBottom: number, borderLeft: number, borderRight: number, borderTop: number, marginBottom: number, marginLeft: number, marginRight: number, marginTop: number, paddingBottom: number, paddingLeft: number, paddingRight: number, paddingTop: number, } { const calculatedStyle = window.getComputedStyle(domElement); return { borderLeft: parseInt(calculatedStyle.borderLeftWidth, 10), borderRight: parseInt(calculatedStyle.borderRightWidth, 10), borderTop: parseInt(calculatedStyle.borderTopWidth, 10), borderBottom: parseInt(calculatedStyle.borderBottomWidth, 10), marginLeft: parseInt(calculatedStyle.marginLeft, 10), marginRight: parseInt(calculatedStyle.marginRight, 10), marginTop: parseInt(calculatedStyle.marginTop, 10), marginBottom: parseInt(calculatedStyle.marginBottom, 10), paddingLeft: parseInt(calculatedStyle.paddingLeft, 10), paddingRight: parseInt(calculatedStyle.paddingRight, 10), paddingTop: parseInt(calculatedStyle.paddingTop, 10), paddingBottom: parseInt(calculatedStyle.paddingBottom, 10), }; }
30.957447
80
0.713873
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 isArray from 'shared/isArray'; import { DefaultEventPriority, type EventPriority, } from 'react-reconciler/src/ReactEventPriorities'; export type Type = string; export type Props = Object; export type Container = { children: Array<Instance | TextInstance>, createNodeMock: Function, tag: 'CONTAINER', }; export type Instance = { type: string, props: Object, isHidden: boolean, children: Array<Instance | TextInstance>, internalInstanceHandle: Object, rootContainerInstance: Container, tag: 'INSTANCE', }; export type TextInstance = { text: string, isHidden: boolean, tag: 'TEXT', }; export type HydratableInstance = Instance | TextInstance; export type PublicInstance = Instance | TextInstance; export type HostContext = Object; export type UpdatePayload = Object; export type ChildSet = void; // Unused export type TimeoutHandle = TimeoutID; export type NoTimeout = -1; export type EventResponder = any; export type RendererInspectionConfig = $ReadOnly<{}>; export type TransitionStatus = mixed; export * from 'react-reconciler/src/ReactFiberConfigWithNoPersistence'; export * from 'react-reconciler/src/ReactFiberConfigWithNoHydration'; export * from 'react-reconciler/src/ReactFiberConfigWithNoTestSelectors'; export * from 'react-reconciler/src/ReactFiberConfigWithNoMicrotasks'; export * from 'react-reconciler/src/ReactFiberConfigWithNoResources'; export * from 'react-reconciler/src/ReactFiberConfigWithNoSingletons'; const NO_CONTEXT = {}; const nodeToInstanceMap = new WeakMap<any, Instance>(); if (__DEV__) { Object.freeze(NO_CONTEXT); } export function getPublicInstance(inst: Instance | TextInstance): $FlowFixMe { switch (inst.tag) { case 'INSTANCE': const createNodeMock = inst.rootContainerInstance.createNodeMock; const mockNode = createNodeMock({ type: inst.type, props: inst.props, }); if (typeof mockNode === 'object' && mockNode !== null) { nodeToInstanceMap.set(mockNode, inst); } return mockNode; default: return inst; } } export function appendChild( parentInstance: Instance | Container, child: Instance | TextInstance, ): void { if (__DEV__) { if (!isArray(parentInstance.children)) { console.error( 'An invalid container has been provided. ' + 'This may indicate that another renderer is being used in addition to the test renderer. ' + '(For example, ReactDOM.createPortal inside of a ReactTestRenderer tree.) ' + 'This is not supported.', ); } } const index = parentInstance.children.indexOf(child); if (index !== -1) { parentInstance.children.splice(index, 1); } parentInstance.children.push(child); } export function insertBefore( parentInstance: Instance | Container, 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); parentInstance.children.splice(beforeIndex, 0, child); } export function removeChild( parentInstance: Instance | Container, child: Instance | TextInstance, ): void { const index = parentInstance.children.indexOf(child); parentInstance.children.splice(index, 1); } export function clearContainer(container: Container): void { container.children.splice(0); } export function getRootHostContext( rootContainerInstance: Container, ): HostContext { return NO_CONTEXT; } export function getChildHostContext( parentHostContext: HostContext, type: string, ): HostContext { return NO_CONTEXT; } export function prepareForCommit(containerInfo: Container): null | Object { // noop return null; } export function resetAfterCommit(containerInfo: Container): void { // noop } export function createInstance( type: string, props: Props, rootContainerInstance: Container, hostContext: Object, internalInstanceHandle: Object, ): Instance { return { type, props, isHidden: false, children: [], internalInstanceHandle, rootContainerInstance, tag: 'INSTANCE', }; } export function appendInitialChild( parentInstance: Instance, child: Instance | TextInstance, ): void { const index = parentInstance.children.indexOf(child); if (index !== -1) { parentInstance.children.splice(index, 1); } parentInstance.children.push(child); } export function finalizeInitialChildren( testElement: Instance, type: string, props: Props, rootContainerInstance: Container, hostContext: Object, ): boolean { return false; } export function shouldSetTextContent(type: string, props: Props): boolean { return false; } export function createTextInstance( text: string, rootContainerInstance: Container, hostContext: Object, internalInstanceHandle: Object, ): TextInstance { return { text, isHidden: false, tag: 'TEXT', }; } export function getCurrentEventPriority(): EventPriority { return DefaultEventPriority; } export function shouldAttemptEagerTransition(): boolean { return false; } export const isPrimaryRenderer = false; export const warnsIfNotActing = true; export const scheduleTimeout = setTimeout; export const cancelTimeout = clearTimeout; export const noTimeout = -1; // ------------------- // Mutation // ------------------- export const supportsMutation = true; export function commitUpdate( instance: Instance, updatePayload: null | {...}, type: string, oldProps: Props, newProps: Props, internalInstanceHandle: Object, ): void { instance.type = type; instance.props = newProps; } export function commitMount( instance: Instance, type: string, newProps: Props, internalInstanceHandle: Object, ): void { // noop } export function commitTextUpdate( textInstance: TextInstance, oldText: string, newText: string, ): void { textInstance.text = newText; } export function resetTextContent(testElement: Instance): void { // noop } export const appendChildToContainer = appendChild; export const insertInContainerBefore = insertBefore; export const removeChildFromContainer = removeChild; export function hideInstance(instance: Instance): void { instance.isHidden = true; } export function hideTextInstance(textInstance: TextInstance): void { textInstance.isHidden = true; } export function unhideInstance(instance: Instance, props: Props): void { instance.isHidden = false; } export function unhideTextInstance( textInstance: TextInstance, text: string, ): void { textInstance.isHidden = false; } export function getInstanceFromNode(mockNode: Object): Object | null { const instance = nodeToInstanceMap.get(mockNode); if (instance !== undefined) { return instance.internalInstanceHandle; } return null; } export function beforeActiveInstanceBlur(internalInstanceHandle: Object) { // noop } export function afterActiveInstanceBlur() { // noop } export function preparePortalMount(portalInstance: Instance): void { // noop } export function prepareScopeUpdate(scopeInstance: Object, inst: Object): void { nodeToInstanceMap.set(scopeInstance, inst); } export function getInstanceFromScope(scopeInstance: Object): null | Object { return nodeToInstanceMap.get(scopeInstance) || null; } export function detachDeletedInstance(node: Instance): void { // noop } export function logRecoverableError(error: mixed): void { // noop } export function requestPostPaintCallback(callback: (time: number) => void) { // noop } export function maySuspendCommit(type: Type, props: Props): boolean { return false; } export function preloadInstance(type: Type, props: Props): boolean { // Return true to indicate it's already loaded return true; } export function startSuspendingCommit(): void {} export function suspendInstance(type: Type, props: Props): void {} export function waitForCommitToBeReady(): null { return null; } export const NotPendingTransition: TransitionStatus = null;
23.410029
102
0.729877
Python-Penetration-Testing-Cookbook
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); const isDarkMode = useIsDarkMode(); const { foo } = useFoo(); (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 27, columnNumber: 7 } }, "Foo: ", foo), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const [isDarkMode] = (0, _react.useState)(false); (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return isDarkMode; } function useFoo() { (0, _react.useDebugValue)('foo'); return { foo: true }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhDdXN0b21Ib29rLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiLCJpc0RhcmtNb2RlIiwidXNlSXNEYXJrTW9kZSIsImZvbyIsInVzZUZvbyIsImhhbmRsZUNsaWNrIiwidXNlRWZmZWN0Q3JlYXRlIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7Ozs7Ozs7O0FBRUEsU0FBQUEsU0FBQSxHQUFBO0FBQ0EsUUFBQSxDQUFBQyxLQUFBLEVBQUFDLFFBQUEsSUFBQSxxQkFBQSxDQUFBLENBQUE7QUFDQSxRQUFBQyxVQUFBLEdBQUFDLGFBQUEsRUFBQTtBQUNBLFFBQUE7QUFBQUMsSUFBQUE7QUFBQSxNQUFBQyxNQUFBLEVBQUE7QUFFQSx3QkFBQSxNQUFBLENBQ0E7QUFDQSxHQUZBLEVBRUEsRUFGQTs7QUFJQSxRQUFBQyxXQUFBLEdBQUEsTUFBQUwsUUFBQSxDQUFBRCxLQUFBLEdBQUEsQ0FBQSxDQUFBOztBQUVBLHNCQUNBLHlFQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLG9CQUFBRSxVQUFBLENBREEsZUFFQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFBQUYsS0FBQSxDQUZBLGVBR0E7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FBQUksR0FBQSxDQUhBLGVBSUE7QUFBQSxJQUFBLE9BQUEsRUFBQUUsV0FBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFKQSxDQURBO0FBUUE7O0FBRUEsU0FBQUgsYUFBQSxHQUFBO0FBQ0EsUUFBQSxDQUFBRCxVQUFBLElBQUEscUJBQUEsS0FBQSxDQUFBO0FBRUEsd0JBQUEsU0FBQUssZUFBQSxHQUFBLENBQ0E7QUFDQSxHQUZBLEVBRUEsRUFGQTtBQUlBLFNBQUFMLFVBQUE7QUFDQTs7QUFFQSxTQUFBRyxNQUFBLEdBQUE7QUFDQSw0QkFBQSxLQUFBO0FBQ0EsU0FBQTtBQUFBRCxJQUFBQSxHQUFBLEVBQUE7QUFBQSxHQUFBO0FBQ0EiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlRGVidWdWYWx1ZSwgdXNlRWZmZWN0LCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBbY291bnQsIHNldENvdW50XSA9IHVzZVN0YXRlKDApO1xuICBjb25zdCBpc0RhcmtNb2RlID0gdXNlSXNEYXJrTW9kZSgpO1xuICBjb25zdCB7Zm9vfSA9IHVzZUZvbygpO1xuXG4gIHVzZUVmZmVjdCgoKSA9PiB7XG4gICAgLy8gLi4uXG4gIH0sIFtdKTtcblxuICBjb25zdCBoYW5kbGVDbGljayA9ICgpID0+IHNldENvdW50KGNvdW50ICsgMSk7XG5cbiAgcmV0dXJuIChcbiAgICA8PlxuICAgICAgPGRpdj5EYXJrIG1vZGU/IHtpc0RhcmtNb2RlfTwvZGl2PlxuICAgICAgPGRpdj5Db3VudDoge2NvdW50fTwvZGl2PlxuICAgICAgPGRpdj5Gb286IHtmb299PC9kaXY+XG4gICAgICA8YnV0dG9uIG9uQ2xpY2s9e2hhbmRsZUNsaWNrfT5VcGRhdGUgY291bnQ8L2J1dHRvbj5cbiAgICA8Lz5cbiAgKTtcbn1cblxuZnVuY3Rpb24gdXNlSXNEYXJrTW9kZSgpIHtcbiAgY29uc3QgW2lzRGFya01vZGVdID0gdXNlU3RhdGUoZmFsc2UpO1xuXG4gIHVzZUVmZmVjdChmdW5jdGlvbiB1c2VFZmZlY3RDcmVhdGUoKSB7XG4gICAgLy8gSGVyZSBpcyB3aGVyZSB3ZSBtYXkgbGlzdGVuIHRvIGEgXCJ0aGVtZVwiIGV2ZW50Li4uXG4gIH0sIFtdKTtcblxuICByZXR1cm4gaXNEYXJrTW9kZTtcbn1cblxuZnVuY3Rpb24gdXNlRm9vKCkge1xuICB1c2VEZWJ1Z1ZhbHVlKCdmb28nKTtcbiAgcmV0dXJuIHtmb286IHRydWV9O1xufVxuIl19
74.617647
2,660
0.818518
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactNoop; let Scheduler; let PropTypes; let waitForAll; let waitFor; let waitForThrow; let assertLog; describe('ReactIncremental', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); PropTypes = require('prop-types'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForThrow = InternalTestUtils.waitForThrow; assertLog = InternalTestUtils.assertLog; }); // Note: This is based on a similar component we use in www. We can delete // once the extra div wrapper is no longer necessary. function LegacyHiddenDiv({children, mode}) { return ( <div hidden={mode === 'hidden'}> <React.unstable_LegacyHidden mode={mode === 'hidden' ? 'unstable-defer-without-hiding' : mode}> {children} </React.unstable_LegacyHidden> </div> ); } it('should render a simple component', async () => { function Bar() { return <div>Hello World</div>; } function Foo() { return <Bar isBar={true} />; } ReactNoop.render(<Foo />); await waitForAll([]); }); it('should render a simple component, in steps if needed', async () => { function Bar() { Scheduler.log('Bar'); return ( <span> <div>Hello World</div> </span> ); } function Foo() { Scheduler.log('Foo'); return [<Bar key="a" isBar={true} />, <Bar key="b" isBar={true} />]; } React.startTransition(() => { ReactNoop.render(<Foo />, () => Scheduler.log('callback')); }); // Do one step of work. await waitFor(['Foo']); // Do the rest of the work. await waitForAll(['Bar', 'Bar', 'callback']); }); it('updates a previous render', async () => { function Header() { Scheduler.log('Header'); return <h1>Hi</h1>; } function Content(props) { Scheduler.log('Content'); return <div>{props.children}</div>; } function Footer() { Scheduler.log('Footer'); return <footer>Bye</footer>; } const header = <Header />; const footer = <Footer />; function Foo(props) { Scheduler.log('Foo'); return ( <div> {header} <Content>{props.text}</Content> {footer} </div> ); } ReactNoop.render(<Foo text="foo" />, () => Scheduler.log('renderCallbackCalled'), ); await waitForAll([ 'Foo', 'Header', 'Content', 'Footer', 'renderCallbackCalled', ]); ReactNoop.render(<Foo text="bar" />, () => Scheduler.log('firstRenderCallbackCalled'), ); ReactNoop.render(<Foo text="bar" />, () => Scheduler.log('secondRenderCallbackCalled'), ); // TODO: Test bail out of host components. This is currently unobservable. // Since this is an update, it should bail out and reuse the work from // Header and Content. await waitForAll([ 'Foo', 'Content', 'firstRenderCallbackCalled', 'secondRenderCallbackCalled', ]); }); it('can cancel partially rendered work and restart', async () => { function Bar(props) { Scheduler.log('Bar'); return <div>{props.children}</div>; } function Foo(props) { Scheduler.log('Foo'); return ( <div> <Bar>{props.text}</Bar> <Bar>{props.text}</Bar> </div> ); } // Init ReactNoop.render(<Foo text="foo" />); await waitForAll(['Foo', 'Bar', 'Bar']); React.startTransition(() => { ReactNoop.render(<Foo text="bar" />); }); // Flush part of the work await waitFor(['Foo', 'Bar']); // This will abort the previous work and restart ReactNoop.flushSync(() => ReactNoop.render(null)); React.startTransition(() => { ReactNoop.render(<Foo text="baz" />); }); // Flush part of the new work await waitFor(['Foo', 'Bar']); // Flush the rest of the work which now includes the low priority await waitForAll(['Bar']); }); it('should call callbacks even if updates are aborted', async () => { let inst; class Foo extends React.Component { constructor(props) { super(props); this.state = { text: 'foo', text2: 'foo', }; inst = this; } render() { return ( <div> <div>{this.state.text}</div> <div>{this.state.text2}</div> </div> ); } } ReactNoop.render(<Foo />); await waitForAll([]); React.startTransition(() => { inst.setState( () => { Scheduler.log('setState1'); return {text: 'bar'}; }, () => Scheduler.log('callback1'), ); }); // Flush part of the work await waitFor(['setState1']); // This will abort the previous work and restart ReactNoop.flushSync(() => ReactNoop.render(<Foo />)); React.startTransition(() => { inst.setState( () => { Scheduler.log('setState2'); return {text2: 'baz'}; }, () => Scheduler.log('callback2'), ); }); // Flush the rest of the work which now includes the low priority await waitForAll(['setState1', 'setState2', 'callback1', 'callback2']); expect(inst.state).toEqual({text: 'bar', text2: 'baz'}); }); // @gate www it('can deprioritize unfinished work and resume it later', async () => { function Bar(props) { Scheduler.log('Bar'); return <div>{props.children}</div>; } function Middle(props) { Scheduler.log('Middle'); return <span>{props.children}</span>; } function Foo(props) { Scheduler.log('Foo'); return ( <div> <Bar>{props.text}</Bar> <LegacyHiddenDiv mode="hidden"> <Middle>{props.text}</Middle> </LegacyHiddenDiv> <Bar>{props.text}</Bar> <LegacyHiddenDiv mode="hidden"> <Middle>Footer</Middle> </LegacyHiddenDiv> </div> ); } // Init ReactNoop.render(<Foo text="foo" />); await waitForAll(['Foo', 'Bar', 'Bar', 'Middle', 'Middle']); // Render part of the work. This should be enough to flush everything except // the middle which has lower priority. ReactNoop.render(<Foo text="bar" />); await waitFor(['Foo', 'Bar', 'Bar']); // Flush only the remaining work await waitForAll(['Middle', 'Middle']); }); // @gate www it('can deprioritize a tree from without dropping work', async () => { function Bar(props) { Scheduler.log('Bar'); return <div>{props.children}</div>; } function Middle(props) { Scheduler.log('Middle'); return <span>{props.children}</span>; } function Foo(props) { Scheduler.log('Foo'); return ( <div> <Bar>{props.text}</Bar> <LegacyHiddenDiv mode="hidden"> <Middle>{props.text}</Middle> </LegacyHiddenDiv> <Bar>{props.text}</Bar> <LegacyHiddenDiv mode="hidden"> <Middle>Footer</Middle> </LegacyHiddenDiv> </div> ); } // Init ReactNoop.flushSync(() => { ReactNoop.render(<Foo text="foo" />); }); assertLog(['Foo', 'Bar', 'Bar']); await waitForAll(['Middle', 'Middle']); // Render the high priority work (everything except the hidden trees). ReactNoop.flushSync(() => { ReactNoop.render(<Foo text="foo" />); }); assertLog(['Foo', 'Bar', 'Bar']); // The hidden content was deprioritized from high to low priority. A low // priority callback should have been scheduled. Flush it now. await waitForAll(['Middle', 'Middle']); }); xit('can resume work in a subtree even when a parent bails out', async () => { function Bar(props) { Scheduler.log('Bar'); return <div>{props.children}</div>; } function Tester() { // This component is just here to ensure that the bail out is // in fact in effect in the expected place for this test. Scheduler.log('Tester'); return <div />; } function Middle(props) { Scheduler.log('Middle'); return <span>{props.children}</span>; } const middleContent = ( <aaa> <Tester /> <bbb hidden={true}> <ccc> <Middle>Hi</Middle> </ccc> </bbb> </aaa> ); function Foo(props) { Scheduler.log('Foo'); return ( <div> <Bar>{props.text}</Bar> {middleContent} <Bar>{props.text}</Bar> </div> ); } // Init ReactNoop.render(<Foo text="foo" />); ReactNoop.flushDeferredPri(52); assertLog(['Foo', 'Bar', 'Tester', 'Bar']); // We're now rendering an update that will bail out on updating middle. ReactNoop.render(<Foo text="bar" />); ReactNoop.flushDeferredPri(45 + 5); assertLog(['Foo', 'Bar', 'Bar']); // Flush the rest to make sure that the bailout didn't block this work. await waitForAll(['Middle']); }); xit('can resume work in a bailed subtree within one pass', async () => { function Bar(props) { Scheduler.log('Bar'); return <div>{props.children}</div>; } class Tester extends React.Component { shouldComponentUpdate() { return false; } render() { // This component is just here to ensure that the bail out is // in fact in effect in the expected place for this test. Scheduler.log('Tester'); return <div />; } } function Middle(props) { Scheduler.log('Middle'); return <span>{props.children}</span>; } // Should content not just bail out on current, not workInProgress? class Content extends React.Component { shouldComponentUpdate() { return false; } render() { return [ <Tester key="a" unused={this.props.unused} />, <bbb key="b" hidden={true}> <ccc> <Middle>Hi</Middle> </ccc> </bbb>, ]; } } function Foo(props) { Scheduler.log('Foo'); return ( <div hidden={props.text === 'bar'}> <Bar>{props.text}</Bar> <Content unused={props.text} /> <Bar>{props.text}</Bar> </div> ); } // Init ReactNoop.render(<Foo text="foo" />); ReactNoop.flushDeferredPri(52 + 5); assertLog(['Foo', 'Bar', 'Tester', 'Bar']); // Make a quick update which will create a low pri tree on top of the // already low pri tree. ReactNoop.render(<Foo text="bar" />); ReactNoop.flushDeferredPri(15); assertLog(['Foo']); // At this point, middle will bail out but it has not yet fully rendered. // Since that is the same priority as its parent tree. This should render // as a single batch. Therefore, it is correct that Middle should be in the // middle. If it occurs after the two "Bar" components then it was flushed // after them which is not correct. await waitForAll(['Bar', 'Middle', 'Bar']); // Let us try this again without fully finishing the first time. This will // create a hanging subtree that is reconciling at the normal priority. ReactNoop.render(<Foo text="foo" />); ReactNoop.flushDeferredPri(40); assertLog(['Foo', 'Bar']); // This update will create a tree that aborts that work and down-prioritizes // it. If the priority levels aren't down-prioritized correctly this may // abort rendering of the down-prioritized content. ReactNoop.render(<Foo text="bar" />); await waitForAll(['Foo', 'Bar', 'Bar']); }); xit('can resume mounting a class component', async () => { let foo; class Parent extends React.Component { shouldComponentUpdate() { return false; } render() { return <Foo prop={this.props.prop} />; } } class Foo extends React.Component { constructor(props) { super(props); // Test based on a www bug where props was null on resume Scheduler.log('Foo constructor: ' + props.prop); } render() { foo = this; Scheduler.log('Foo'); return <Bar />; } } function Bar() { Scheduler.log('Bar'); return <div />; } ReactNoop.render(<Parent prop="foo" />); ReactNoop.flushDeferredPri(20); assertLog(['Foo constructor: foo', 'Foo']); foo.setState({value: 'bar'}); await waitForAll(['Foo', 'Bar']); }); xit('reuses the same instance when resuming a class instance', async () => { let foo; class Parent extends React.Component { shouldComponentUpdate() { return false; } render() { return <Foo prop={this.props.prop} />; } } let constructorCount = 0; class Foo extends React.Component { constructor(props) { super(props); // Test based on a www bug where props was null on resume Scheduler.log('constructor: ' + props.prop); constructorCount++; } UNSAFE_componentWillMount() { Scheduler.log('componentWillMount: ' + this.props.prop); } UNSAFE_componentWillReceiveProps() { Scheduler.log('componentWillReceiveProps: ' + this.props.prop); } componentDidMount() { Scheduler.log('componentDidMount: ' + this.props.prop); } UNSAFE_componentWillUpdate() { Scheduler.log('componentWillUpdate: ' + this.props.prop); } componentDidUpdate() { Scheduler.log('componentDidUpdate: ' + this.props.prop); } render() { foo = this; Scheduler.log('render: ' + this.props.prop); return <Bar />; } } function Bar() { Scheduler.log('Foo did complete'); return <div />; } ReactNoop.render(<Parent prop="foo" />); ReactNoop.flushDeferredPri(25); assertLog([ 'constructor: foo', 'componentWillMount: foo', 'render: foo', 'Foo did complete', ]); foo.setState({value: 'bar'}); await waitForAll([]); expect(constructorCount).toEqual(1); assertLog([ 'componentWillMount: foo', 'render: foo', 'Foo did complete', 'componentDidMount: foo', ]); }); xit('can reuse work done after being preempted', async () => { function Bar(props) { Scheduler.log('Bar'); return <div>{props.children}</div>; } function Middle(props) { Scheduler.log('Middle'); return <span>{props.children}</span>; } const middleContent = ( <div> <Middle>Hello</Middle> <Bar>-</Bar> <Middle>World</Middle> </div> ); const step0 = ( <div> <Middle>Hi</Middle> <Bar>{'Foo'}</Bar> <Middle>There</Middle> </div> ); function Foo(props) { Scheduler.log('Foo'); return ( <div> <Bar>{props.text2}</Bar> <div hidden={true}>{props.step === 0 ? step0 : middleContent}</div> </div> ); } // Init ReactNoop.render(<Foo text="foo" text2="foo" step={0} />); ReactNoop.flushDeferredPri(55 + 25 + 5 + 5); // We only finish the higher priority work. So the low pri content // has not yet finished mounting. assertLog(['Foo', 'Bar', 'Middle', 'Bar']); // Interrupt the rendering with a quick update. This should not touch the // middle content. ReactNoop.render(<Foo text="foo" text2="bar" step={0} />); await waitForAll([]); // We've now rendered the entire tree but we didn't have to redo the work // done by the first Middle and Bar already. assertLog(['Foo', 'Bar', 'Middle']); // Make a quick update which will schedule low priority work to // update the middle content. ReactNoop.render(<Foo text="bar" text2="bar" step={1} />); ReactNoop.flushDeferredPri(30 + 25 + 5); assertLog(['Foo', 'Bar']); // The middle content is now pending rendering... ReactNoop.flushDeferredPri(30 + 5); assertLog(['Middle', 'Bar']); // but we'll interrupt it to render some higher priority work. // The middle content will bailout so it remains untouched. ReactNoop.render(<Foo text="foo" text2="bar" step={1} />); ReactNoop.flushDeferredPri(30); assertLog(['Foo', 'Bar']); // Since we did nothing to the middle subtree during the interruption, // we should be able to reuse the reconciliation work that we already did // without restarting. await waitForAll(['Middle']); }); xit('can reuse work that began but did not complete, after being preempted', async () => { let child; let sibling; function GreatGrandchild() { Scheduler.log('GreatGrandchild'); return <div />; } function Grandchild() { Scheduler.log('Grandchild'); return <GreatGrandchild />; } class Child extends React.Component { state = {step: 0}; render() { child = this; Scheduler.log('Child'); return <Grandchild />; } } class Sibling extends React.Component { render() { Scheduler.log('Sibling'); sibling = this; return <div />; } } function Parent() { Scheduler.log('Parent'); return [ // The extra div is necessary because when Parent bails out during the // high priority update, its progressedPriority is set to high. // So its direct children cannot be reused when we resume at // low priority. I think this would be fixed by changing // pendingWorkPriority and progressedPriority to be the priority of // the children only, not including the fiber itself. <div key="a"> <Child /> </div>, <Sibling key="b" />, ]; } ReactNoop.render(<Parent />); await waitForAll([]); // Begin working on a low priority update to Child, but stop before // GreatGrandchild. Child and Grandchild begin but don't complete. child.setState({step: 1}); ReactNoop.flushDeferredPri(30); assertLog(['Child', 'Grandchild']); // Interrupt the current low pri work with a high pri update elsewhere in // the tree. ReactNoop.flushSync(() => { sibling.setState({}); }); assertLog(['Sibling']); // Continue the low pri work. The work on Child and GrandChild was memoized // so they should not be worked on again. await waitForAll([ // No Child // No Grandchild 'GreatGrandchild', ]); }); xit('can reuse work if shouldComponentUpdate is false, after being preempted', async () => { function Bar(props) { Scheduler.log('Bar'); return <div>{props.children}</div>; } class Middle extends React.Component { shouldComponentUpdate(nextProps) { return this.props.children !== nextProps.children; } render() { Scheduler.log('Middle'); return <span>{this.props.children}</span>; } } class Content extends React.Component { shouldComponentUpdate(nextProps) { return this.props.step !== nextProps.step; } render() { Scheduler.log('Content'); return ( <div> <Middle>{this.props.step === 0 ? 'Hi' : 'Hello'}</Middle> <Bar>{this.props.step === 0 ? this.props.text : '-'}</Bar> <Middle>{this.props.step === 0 ? 'There' : 'World'}</Middle> </div> ); } } function Foo(props) { Scheduler.log('Foo'); return ( <div> <Bar>{props.text}</Bar> <div hidden={true}> <Content step={props.step} text={props.text} /> </div> </div> ); } // Init ReactNoop.render(<Foo text="foo" step={0} />); await waitForAll(['Foo', 'Bar', 'Content', 'Middle', 'Bar', 'Middle']); // Make a quick update which will schedule low priority work to // update the middle content. ReactNoop.render(<Foo text="bar" step={1} />); ReactNoop.flushDeferredPri(30 + 5); assertLog(['Foo', 'Bar']); // The middle content is now pending rendering... ReactNoop.flushDeferredPri(30 + 25 + 5); assertLog(['Content', 'Middle', 'Bar']); // One more Middle left. // but we'll interrupt it to render some higher priority work. // The middle content will bailout so it remains untouched. ReactNoop.render(<Foo text="foo" step={1} />); ReactNoop.flushDeferredPri(30); assertLog(['Foo', 'Bar']); // Since we did nothing to the middle subtree during the interruption, // we should be able to reuse the reconciliation work that we already did // without restarting. await waitForAll(['Middle']); }); it('memoizes work even if shouldComponentUpdate returns false', async () => { class Foo extends React.Component { shouldComponentUpdate(nextProps) { // this.props is the memoized props. So this should return true for // every update except the first one. const shouldUpdate = this.props.step !== 1; Scheduler.log('shouldComponentUpdate: ' + shouldUpdate); return shouldUpdate; } render() { Scheduler.log('render'); return <div />; } } ReactNoop.render(<Foo step={1} />); await waitForAll(['render']); ReactNoop.render(<Foo step={2} />); await waitForAll(['shouldComponentUpdate: false']); ReactNoop.render(<Foo step={3} />); await waitForAll([ // If the memoized props were not updated during last bail out, sCU will // keep returning false. 'shouldComponentUpdate: true', 'render', ]); }); it('can update in the middle of a tree using setState', async () => { let instance; class Bar extends React.Component { constructor() { super(); this.state = {a: 'a'}; instance = this; } render() { return <div>{this.props.children}</div>; } } function Foo() { return ( <div> <Bar /> </div> ); } ReactNoop.render(<Foo />); await waitForAll([]); expect(instance.state).toEqual({a: 'a'}); instance.setState({b: 'b'}); await waitForAll([]); expect(instance.state).toEqual({a: 'a', b: 'b'}); }); it('can queue multiple state updates', async () => { let instance; class Bar extends React.Component { constructor() { super(); this.state = {a: 'a'}; instance = this; } render() { return <div>{this.props.children}</div>; } } function Foo() { return ( <div> <Bar /> </div> ); } ReactNoop.render(<Foo />); await waitForAll([]); // Call setState multiple times before flushing instance.setState({b: 'b'}); instance.setState({c: 'c'}); instance.setState({d: 'd'}); await waitForAll([]); expect(instance.state).toEqual({a: 'a', b: 'b', c: 'c', d: 'd'}); }); it('can use updater form of setState', async () => { let instance; class Bar extends React.Component { constructor() { super(); this.state = {num: 1}; instance = this; } render() { return <div>{this.props.children}</div>; } } function Foo({multiplier}) { return ( <div> <Bar multiplier={multiplier} /> </div> ); } function updater(state, props) { return {num: state.num * props.multiplier}; } ReactNoop.render(<Foo multiplier={2} />); await waitForAll([]); expect(instance.state.num).toEqual(1); instance.setState(updater); await waitForAll([]); expect(instance.state.num).toEqual(2); instance.setState(updater); ReactNoop.render(<Foo multiplier={3} />); await waitForAll([]); expect(instance.state.num).toEqual(6); }); it('can call setState inside update callback', async () => { let instance; class Bar extends React.Component { constructor() { super(); this.state = {num: 1}; instance = this; } render() { return <div>{this.props.children}</div>; } } function Foo({multiplier}) { return ( <div> <Bar multiplier={multiplier} /> </div> ); } function updater(state, props) { return {num: state.num * props.multiplier}; } function callback() { this.setState({called: true}); } ReactNoop.render(<Foo multiplier={2} />); await waitForAll([]); instance.setState(updater); instance.setState(updater, callback); await waitForAll([]); expect(instance.state.num).toEqual(4); expect(instance.state.called).toEqual(true); }); it('can replaceState', async () => { let instance; class Bar extends React.Component { state = {a: 'a'}; render() { instance = this; return <div>{this.props.children}</div>; } } function Foo() { return ( <div> <Bar /> </div> ); } ReactNoop.render(<Foo />); await waitForAll([]); instance.setState({b: 'b'}); instance.setState({c: 'c'}); instance.updater.enqueueReplaceState(instance, {d: 'd'}); await waitForAll([]); expect(instance.state).toEqual({d: 'd'}); }); it('can forceUpdate', async () => { function Baz() { Scheduler.log('Baz'); return <div />; } let instance; class Bar extends React.Component { constructor() { super(); instance = this; } shouldComponentUpdate() { return false; } render() { Scheduler.log('Bar'); return <Baz />; } } function Foo() { Scheduler.log('Foo'); return ( <div> <Bar /> </div> ); } ReactNoop.render(<Foo />); await waitForAll(['Foo', 'Bar', 'Baz']); instance.forceUpdate(); await waitForAll(['Bar', 'Baz']); }); it('should clear forceUpdate after update is flushed', async () => { let a = 0; class Foo extends React.PureComponent { render() { const msg = `A: ${a}, B: ${this.props.b}`; Scheduler.log(msg); return msg; } } const foo = React.createRef(null); ReactNoop.render(<Foo ref={foo} b={0} />); await waitForAll(['A: 0, B: 0']); a = 1; foo.current.forceUpdate(); await waitForAll(['A: 1, B: 0']); ReactNoop.render(<Foo ref={foo} b={0} />); await waitForAll([]); }); xit('can call sCU while resuming a partly mounted component', () => { const instances = new Set(); class Bar extends React.Component { state = {y: 'A'}; constructor() { super(); instances.add(this); } shouldComponentUpdate(newProps, newState) { return this.props.x !== newProps.x || this.state.y !== newState.y; } render() { Scheduler.log('Bar:' + this.props.x); return <span prop={String(this.props.x === this.state.y)} />; } } function Foo(props) { Scheduler.log('Foo'); return [ <Bar key="a" x="A" />, <Bar key="b" x={props.step === 0 ? 'B' : 'B2'} />, <Bar key="c" x="C" />, <Bar key="d" x="D" />, ]; } ReactNoop.render(<Foo step={0} />); ReactNoop.flushDeferredPri(40); assertLog(['Foo', 'Bar:A', 'Bar:B', 'Bar:C']); expect(instances.size).toBe(3); ReactNoop.render(<Foo step={1} />); ReactNoop.flushDeferredPri(50); // A was memoized and reused. B was memoized but couldn't be reused because // props differences. C was memoized and reused. D never even started so it // needed a new instance. assertLog(['Foo', 'Bar:B2', 'Bar:D']); // We expect each rerender to correspond to a new instance. expect(instances.size).toBe(4); }); xit('gets new props when setting state on a partly updated component', async () => { const instances = []; class Bar extends React.Component { state = {y: 'A'}; constructor() { super(); instances.push(this); } performAction() { this.setState({ y: 'B', }); } render() { Scheduler.log('Bar:' + this.props.x + '-' + this.props.step); return <span prop={String(this.props.x === this.state.y)} />; } } function Baz() { // This component is used as a sibling to Foo so that we can fully // complete Foo, without committing. Scheduler.log('Baz'); return <div />; } function Foo(props) { Scheduler.log('Foo'); return [ <Bar key="a" x="A" step={props.step} />, <Bar key="b" x="B" step={props.step} />, ]; } ReactNoop.render( <div> <Foo step={0} /> <Baz /> <Baz /> </div>, ); await waitForAll([]); // Flush part way through with new props, fully completing the first Bar. // However, it doesn't commit yet. ReactNoop.render( <div> <Foo step={1} /> <Baz /> <Baz /> </div>, ); ReactNoop.flushDeferredPri(45); assertLog(['Foo', 'Bar:A-1', 'Bar:B-1', 'Baz']); // Make an update to the same Bar. instances[0].performAction(); await waitForAll(['Bar:A-1', 'Baz']); }); xit('calls componentWillMount twice if the initial render is aborted', async () => { class LifeCycle extends React.Component { state = {x: this.props.x}; UNSAFE_componentWillReceiveProps(nextProps) { Scheduler.log( 'componentWillReceiveProps:' + this.state.x + '-' + nextProps.x, ); this.setState({x: nextProps.x}); } UNSAFE_componentWillMount() { Scheduler.log( 'componentWillMount:' + this.state.x + '-' + this.props.x, ); } componentDidMount() { Scheduler.log('componentDidMount:' + this.state.x + '-' + this.props.x); } render() { return <span />; } } function Trail() { Scheduler.log('Trail'); return null; } function App(props) { Scheduler.log('App'); return ( <div> <LifeCycle x={props.x} /> <Trail /> </div> ); } ReactNoop.render(<App x={0} />); ReactNoop.flushDeferredPri(30); assertLog(['App', 'componentWillMount:0-0']); ReactNoop.render(<App x={1} />); await waitForAll([ 'App', 'componentWillReceiveProps:0-1', 'componentWillMount:1-1', 'Trail', 'componentDidMount:1-1', ]); }); xit('uses state set in componentWillMount even if initial render was aborted', async () => { class LifeCycle extends React.Component { constructor(props) { super(props); this.state = {x: this.props.x + '(ctor)'}; } UNSAFE_componentWillMount() { Scheduler.log('componentWillMount:' + this.state.x); this.setState({x: this.props.x + '(willMount)'}); } componentDidMount() { Scheduler.log('componentDidMount:' + this.state.x); } render() { Scheduler.log('render:' + this.state.x); return <span />; } } function App(props) { Scheduler.log('App'); return <LifeCycle x={props.x} />; } ReactNoop.render(<App x={0} />); ReactNoop.flushDeferredPri(20); assertLog(['App', 'componentWillMount:0(ctor)', 'render:0(willMount)']); ReactNoop.render(<App x={1} />); await waitForAll([ 'App', 'componentWillMount:0(willMount)', 'render:1(willMount)', 'componentDidMount:1(willMount)', ]); }); xit('calls componentWill* twice if an update render is aborted', async () => { class LifeCycle extends React.Component { UNSAFE_componentWillMount() { Scheduler.log('componentWillMount:' + this.props.x); } componentDidMount() { Scheduler.log('componentDidMount:' + this.props.x); } UNSAFE_componentWillReceiveProps(nextProps) { Scheduler.log( 'componentWillReceiveProps:' + this.props.x + '-' + nextProps.x, ); } shouldComponentUpdate(nextProps) { Scheduler.log( 'shouldComponentUpdate:' + this.props.x + '-' + nextProps.x, ); return true; } UNSAFE_componentWillUpdate(nextProps) { Scheduler.log( 'componentWillUpdate:' + this.props.x + '-' + nextProps.x, ); } componentDidUpdate(prevProps) { Scheduler.log('componentDidUpdate:' + this.props.x + '-' + prevProps.x); } render() { Scheduler.log('render:' + this.props.x); return <span />; } } function Sibling() { // The sibling is used to confirm that we've completed the first child, // but not yet flushed. Scheduler.log('Sibling'); return <span />; } function App(props) { Scheduler.log('App'); return [<LifeCycle key="a" x={props.x} />, <Sibling key="b" />]; } ReactNoop.render(<App x={0} />); await waitForAll([ 'App', 'componentWillMount:0', 'render:0', 'Sibling', 'componentDidMount:0', ]); ReactNoop.render(<App x={1} />); ReactNoop.flushDeferredPri(30); assertLog([ 'App', 'componentWillReceiveProps:0-1', 'shouldComponentUpdate:0-1', 'componentWillUpdate:0-1', 'render:1', 'Sibling', // no componentDidUpdate ]); ReactNoop.render(<App x={2} />); await waitForAll([ 'App', 'componentWillReceiveProps:1-2', 'shouldComponentUpdate:1-2', 'componentWillUpdate:1-2', 'render:2', 'Sibling', // When componentDidUpdate finally gets called, it covers both updates. 'componentDidUpdate:2-0', ]); }); it('calls getDerivedStateFromProps even for state-only updates', async () => { let instance; class LifeCycle extends React.Component { state = {}; static getDerivedStateFromProps(props, prevState) { Scheduler.log('getDerivedStateFromProps'); return {foo: 'foo'}; } changeState() { this.setState({foo: 'bar'}); } componentDidUpdate() { Scheduler.log('componentDidUpdate'); } render() { Scheduler.log('render'); instance = this; return null; } } ReactNoop.render(<LifeCycle />); await waitForAll(['getDerivedStateFromProps', 'render']); expect(instance.state).toEqual({foo: 'foo'}); instance.changeState(); await waitForAll([ 'getDerivedStateFromProps', 'render', 'componentDidUpdate', ]); expect(instance.state).toEqual({foo: 'foo'}); }); it('does not call getDerivedStateFromProps if neither state nor props have changed', async () => { class Parent extends React.Component { state = {parentRenders: 0}; static getDerivedStateFromProps(props, prevState) { Scheduler.log('getDerivedStateFromProps'); return prevState.parentRenders + 1; } render() { Scheduler.log('Parent'); return <Child parentRenders={this.state.parentRenders} ref={child} />; } } class Child extends React.Component { render() { Scheduler.log('Child'); return this.props.parentRenders; } } const child = React.createRef(null); ReactNoop.render(<Parent />); await waitForAll(['getDerivedStateFromProps', 'Parent', 'Child']); // Schedule an update on the child. The parent should not re-render. child.current.setState({}); await waitForAll(['Child']); }); xit('does not call componentWillReceiveProps for state-only updates', async () => { const instances = []; class LifeCycle extends React.Component { state = {x: 0}; tick() { this.setState({ x: this.state.x + 1, }); } UNSAFE_componentWillMount() { instances.push(this); Scheduler.log('componentWillMount:' + this.state.x); } componentDidMount() { Scheduler.log('componentDidMount:' + this.state.x); } UNSAFE_componentWillReceiveProps(nextProps) { Scheduler.log('componentWillReceiveProps'); } shouldComponentUpdate(nextProps, nextState) { Scheduler.log( 'shouldComponentUpdate:' + this.state.x + '-' + nextState.x, ); return true; } UNSAFE_componentWillUpdate(nextProps, nextState) { Scheduler.log( 'componentWillUpdate:' + this.state.x + '-' + nextState.x, ); } componentDidUpdate(prevProps, prevState) { Scheduler.log('componentDidUpdate:' + this.state.x + '-' + prevState.x); } render() { Scheduler.log('render:' + this.state.x); return <span />; } } // This wrap is a bit contrived because we can't pause a completed root and // there is currently an issue where a component can't reuse its render // output unless it fully completed. class Wrap extends React.Component { state = {y: 0}; UNSAFE_componentWillMount() { instances.push(this); } tick() { this.setState({ y: this.state.y + 1, }); } render() { Scheduler.log('Wrap'); return <LifeCycle y={this.state.y} />; } } function Sibling() { // The sibling is used to confirm that we've completed the first child, // but not yet flushed. Scheduler.log('Sibling'); return <span />; } function App(props) { Scheduler.log('App'); return [<Wrap key="a" />, <Sibling key="b" />]; } ReactNoop.render(<App y={0} />); await waitForAll([ 'App', 'Wrap', 'componentWillMount:0', 'render:0', 'Sibling', 'componentDidMount:0', ]); // LifeCycle instances[1].tick(); ReactNoop.flushDeferredPri(25); assertLog([ // no componentWillReceiveProps 'shouldComponentUpdate:0-1', 'componentWillUpdate:0-1', 'render:1', // no componentDidUpdate ]); // LifeCycle instances[1].tick(); await waitForAll([ // no componentWillReceiveProps 'shouldComponentUpdate:1-2', 'componentWillUpdate:1-2', 'render:2', // When componentDidUpdate finally gets called, it covers both updates. 'componentDidUpdate:2-0', ]); // Next we will update props of LifeCycle by updating its parent. instances[0].tick(); ReactNoop.flushDeferredPri(30); assertLog([ 'Wrap', 'componentWillReceiveProps', 'shouldComponentUpdate:2-2', 'componentWillUpdate:2-2', 'render:2', // no componentDidUpdate ]); // Next we will update LifeCycle directly but not with new props. instances[1].tick(); await waitForAll([ // This should not trigger another componentWillReceiveProps because // we never got new props. 'shouldComponentUpdate:2-3', 'componentWillUpdate:2-3', 'render:3', 'componentDidUpdate:3-2', ]); // TODO: Test that we get the expected values for the same scenario with // incomplete parents. }); xit('skips will/DidUpdate when bailing unless an update was already in progress', async () => { class LifeCycle extends React.Component { UNSAFE_componentWillMount() { Scheduler.log('componentWillMount'); } componentDidMount() { Scheduler.log('componentDidMount'); } UNSAFE_componentWillReceiveProps(nextProps) { Scheduler.log('componentWillReceiveProps'); } shouldComponentUpdate(nextProps) { Scheduler.log('shouldComponentUpdate'); // Bail return this.props.x !== nextProps.x; } UNSAFE_componentWillUpdate(nextProps) { Scheduler.log('componentWillUpdate'); } componentDidUpdate(prevProps) { Scheduler.log('componentDidUpdate'); } render() { Scheduler.log('render'); return <span />; } } function Sibling() { Scheduler.log('render sibling'); return <span />; } function App(props) { return [<LifeCycle key="a" x={props.x} />, <Sibling key="b" />]; } ReactNoop.render(<App x={0} />); await waitForAll([ 'componentWillMount', 'render', 'render sibling', 'componentDidMount', ]); // Update to same props ReactNoop.render(<App x={0} />); await waitForAll([ 'componentWillReceiveProps', 'shouldComponentUpdate', // no componentWillUpdate // no render 'render sibling', // no componentDidUpdate ]); // Begin updating to new props... ReactNoop.render(<App x={1} />); ReactNoop.flushDeferredPri(30); assertLog([ 'componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'render', 'render sibling', // no componentDidUpdate yet ]); // ...but we'll interrupt it to rerender the same props. ReactNoop.render(<App x={1} />); await waitForAll([]); // We can bail out this time, but we must call componentDidUpdate. assertLog([ 'componentWillReceiveProps', 'shouldComponentUpdate', // no componentWillUpdate // no render 'render sibling', 'componentDidUpdate', ]); }); it('can nest batchedUpdates', async () => { let instance; class Foo extends React.Component { state = {n: 0}; render() { instance = this; return <div />; } } ReactNoop.render(<Foo />); await waitForAll([]); ReactNoop.flushSync(() => { ReactNoop.batchedUpdates(() => { instance.setState({n: 1}, () => Scheduler.log('setState 1')); instance.setState({n: 2}, () => Scheduler.log('setState 2')); ReactNoop.batchedUpdates(() => { instance.setState({n: 3}, () => Scheduler.log('setState 3')); instance.setState({n: 4}, () => Scheduler.log('setState 4')); Scheduler.log('end inner batchedUpdates'); }); Scheduler.log('end outer batchedUpdates'); }); }); // ReactNoop.flush() not needed because updates are synchronous assertLog([ 'end inner batchedUpdates', 'end outer batchedUpdates', 'setState 1', 'setState 2', 'setState 3', 'setState 4', ]); expect(instance.state.n).toEqual(4); }); it('can handle if setState callback throws', async () => { let instance; class Foo extends React.Component { state = {n: 0}; render() { instance = this; return <div />; } } ReactNoop.render(<Foo />); await waitForAll([]); function updater({n}) { return {n: n + 1}; } instance.setState(updater, () => Scheduler.log('first callback')); instance.setState(updater, () => { Scheduler.log('second callback'); throw new Error('callback error'); }); instance.setState(updater, () => Scheduler.log('third callback')); await waitForThrow('callback error'); // The third callback isn't called because the second one throws assertLog(['first callback', 'second callback']); expect(instance.state.n).toEqual(3); }); // @gate !disableLegacyContext it('merges and masks context', async () => { class Intl extends React.Component { static childContextTypes = { locale: PropTypes.string, }; getChildContext() { return { locale: this.props.locale, }; } render() { Scheduler.log('Intl ' + JSON.stringify(this.context)); return this.props.children; } } class Router extends React.Component { static childContextTypes = { route: PropTypes.string, }; getChildContext() { return { route: this.props.route, }; } render() { Scheduler.log('Router ' + JSON.stringify(this.context)); return this.props.children; } } class ShowLocale extends React.Component { static contextTypes = { locale: PropTypes.string, }; render() { Scheduler.log('ShowLocale ' + JSON.stringify(this.context)); return this.context.locale; } } class ShowRoute extends React.Component { static contextTypes = { route: PropTypes.string, }; render() { Scheduler.log('ShowRoute ' + JSON.stringify(this.context)); return this.context.route; } } function ShowBoth(props, context) { Scheduler.log('ShowBoth ' + JSON.stringify(context)); return `${context.route} in ${context.locale}`; } ShowBoth.contextTypes = { locale: PropTypes.string, route: PropTypes.string, }; class ShowNeither extends React.Component { render() { Scheduler.log('ShowNeither ' + JSON.stringify(this.context)); return null; } } class Indirection extends React.Component { render() { Scheduler.log('Indirection ' + JSON.stringify(this.context)); return [ <ShowLocale key="a" />, <ShowRoute key="b" />, <ShowNeither key="c" />, <Intl key="d" locale="ru"> <ShowBoth /> </Intl>, <ShowBoth key="e" />, ]; } } ReactNoop.render( <Intl locale="fr"> <ShowLocale /> <div> <ShowBoth /> </div> </Intl>, ); await waitForAll([ 'Intl {}', 'ShowLocale {"locale":"fr"}', 'ShowBoth {"locale":"fr"}', ]); ReactNoop.render( <Intl locale="de"> <ShowLocale /> <div> <ShowBoth /> </div> </Intl>, ); await waitForAll([ 'Intl {}', 'ShowLocale {"locale":"de"}', 'ShowBoth {"locale":"de"}', ]); React.startTransition(() => { ReactNoop.render( <Intl locale="sv"> <ShowLocale /> <div> <ShowBoth /> </div> </Intl>, ); }); await waitFor(['Intl {}']); ReactNoop.render( <Intl locale="en"> <ShowLocale /> <Router route="/about"> <Indirection /> </Router> <ShowBoth /> </Intl>, ); await waitForAll([ 'ShowLocale {"locale":"sv"}', 'ShowBoth {"locale":"sv"}', 'Intl {}', 'ShowLocale {"locale":"en"}', 'Router {}', 'Indirection {}', 'ShowLocale {"locale":"en"}', 'ShowRoute {"route":"/about"}', 'ShowNeither {}', 'Intl {}', 'ShowBoth {"locale":"ru","route":"/about"}', 'ShowBoth {"locale":"en","route":"/about"}', 'ShowBoth {"locale":"en"}', ]); }); // @gate !disableLegacyContext it('does not leak own context into context provider', async () => { if (gate(flags => flags.disableLegacyContext)) { throw new Error('This test infinite loops when context is disabled.'); } class Recurse extends React.Component { static contextTypes = { n: PropTypes.number, }; static childContextTypes = { n: PropTypes.number, }; getChildContext() { return {n: (this.context.n || 3) - 1}; } render() { Scheduler.log('Recurse ' + JSON.stringify(this.context)); if (this.context.n === 0) { return null; } return <Recurse />; } } ReactNoop.render(<Recurse />); await waitForAll([ 'Recurse {}', 'Recurse {"n":2}', 'Recurse {"n":1}', 'Recurse {"n":0}', ]); }); // @gate !disableModulePatternComponents // @gate !disableLegacyContext it('does not leak own context into context provider (factory components)', async () => { function Recurse(props, context) { return { getChildContext() { return {n: (context.n || 3) - 1}; }, render() { Scheduler.log('Recurse ' + JSON.stringify(context)); if (context.n === 0) { return null; } return <Recurse />; }, }; } Recurse.contextTypes = { n: PropTypes.number, }; Recurse.childContextTypes = { n: PropTypes.number, }; ReactNoop.render(<Recurse />); await expect( async () => await waitForAll([ 'Recurse {}', 'Recurse {"n":2}', 'Recurse {"n":1}', 'Recurse {"n":0}', ]), ).toErrorDev([ 'Warning: The <Recurse /> component appears to be a function component that returns a class instance. ' + 'Change Recurse to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + '`Recurse.prototype = React.Component.prototype`. ' + "Don't use an arrow function since it cannot be called with `new` by React.", ]); }); // @gate www // @gate !disableLegacyContext it('provides context when reusing work', async () => { class Intl extends React.Component { static childContextTypes = { locale: PropTypes.string, }; getChildContext() { return { locale: this.props.locale, }; } render() { Scheduler.log('Intl ' + JSON.stringify(this.context)); return this.props.children; } } class ShowLocale extends React.Component { static contextTypes = { locale: PropTypes.string, }; render() { Scheduler.log('ShowLocale ' + JSON.stringify(this.context)); return this.context.locale; } } React.startTransition(() => { ReactNoop.render( <Intl locale="fr"> <ShowLocale /> <LegacyHiddenDiv mode="hidden"> <ShowLocale /> <Intl locale="ru"> <ShowLocale /> </Intl> </LegacyHiddenDiv> <ShowLocale /> </Intl>, ); }); await waitFor([ 'Intl {}', 'ShowLocale {"locale":"fr"}', 'ShowLocale {"locale":"fr"}', ]); await waitForAll([ 'ShowLocale {"locale":"fr"}', 'Intl {}', 'ShowLocale {"locale":"ru"}', ]); }); // @gate !disableLegacyContext it('reads context when setState is below the provider', async () => { let statefulInst; class Intl extends React.Component { static childContextTypes = { locale: PropTypes.string, }; getChildContext() { const childContext = { locale: this.props.locale, }; Scheduler.log('Intl:provide ' + JSON.stringify(childContext)); return childContext; } render() { Scheduler.log('Intl:read ' + JSON.stringify(this.context)); return this.props.children; } } class ShowLocaleClass extends React.Component { static contextTypes = { locale: PropTypes.string, }; render() { Scheduler.log('ShowLocaleClass:read ' + JSON.stringify(this.context)); return this.context.locale; } } function ShowLocaleFn(props, context) { Scheduler.log('ShowLocaleFn:read ' + JSON.stringify(context)); return context.locale; } ShowLocaleFn.contextTypes = { locale: PropTypes.string, }; class Stateful extends React.Component { state = {x: 0}; render() { statefulInst = this; return this.props.children; } } function IndirectionFn(props, context) { Scheduler.log('IndirectionFn ' + JSON.stringify(context)); return props.children; } class IndirectionClass extends React.Component { render() { Scheduler.log('IndirectionClass ' + JSON.stringify(this.context)); return this.props.children; } } ReactNoop.render( <Intl locale="fr"> <IndirectionFn> <IndirectionClass> <Stateful> <ShowLocaleClass /> <ShowLocaleFn /> </Stateful> </IndirectionClass> </IndirectionFn> </Intl>, ); await waitForAll([ 'Intl:read {}', 'Intl:provide {"locale":"fr"}', 'IndirectionFn {}', 'IndirectionClass {}', 'ShowLocaleClass:read {"locale":"fr"}', 'ShowLocaleFn:read {"locale":"fr"}', ]); statefulInst.setState({x: 1}); await waitForAll([]); // All work has been memoized because setState() // happened below the context and could not have affected it. assertLog([]); }); // @gate !disableLegacyContext it('reads context when setState is above the provider', async () => { let statefulInst; class Intl extends React.Component { static childContextTypes = { locale: PropTypes.string, }; getChildContext() { const childContext = { locale: this.props.locale, }; Scheduler.log('Intl:provide ' + JSON.stringify(childContext)); return childContext; } render() { Scheduler.log('Intl:read ' + JSON.stringify(this.context)); return this.props.children; } } class ShowLocaleClass extends React.Component { static contextTypes = { locale: PropTypes.string, }; render() { Scheduler.log('ShowLocaleClass:read ' + JSON.stringify(this.context)); return this.context.locale; } } function ShowLocaleFn(props, context) { Scheduler.log('ShowLocaleFn:read ' + JSON.stringify(context)); return context.locale; } ShowLocaleFn.contextTypes = { locale: PropTypes.string, }; function IndirectionFn(props, context) { Scheduler.log('IndirectionFn ' + JSON.stringify(context)); return props.children; } class IndirectionClass extends React.Component { render() { Scheduler.log('IndirectionClass ' + JSON.stringify(this.context)); return this.props.children; } } class Stateful extends React.Component { state = {locale: 'fr'}; render() { statefulInst = this; return <Intl locale={this.state.locale}>{this.props.children}</Intl>; } } ReactNoop.render( <Stateful> <IndirectionFn> <IndirectionClass> <ShowLocaleClass /> <ShowLocaleFn /> </IndirectionClass> </IndirectionFn> </Stateful>, ); await waitForAll([ 'Intl:read {}', 'Intl:provide {"locale":"fr"}', 'IndirectionFn {}', 'IndirectionClass {}', 'ShowLocaleClass:read {"locale":"fr"}', 'ShowLocaleFn:read {"locale":"fr"}', ]); statefulInst.setState({locale: 'gr'}); await waitForAll([ // Intl is below setState() so it might have been // affected by it. Therefore we re-render and recompute // its child context. 'Intl:read {}', 'Intl:provide {"locale":"gr"}', // TODO: it's unfortunate that we can't reuse work on // these components even though they don't depend on context. 'IndirectionFn {}', 'IndirectionClass {}', // These components depend on context: 'ShowLocaleClass:read {"locale":"gr"}', 'ShowLocaleFn:read {"locale":"gr"}', ]); }); // @gate !disableLegacyContext || !__DEV__ it('maintains the correct context when providers bail out due to low priority', async () => { class Root extends React.Component { render() { return <Middle {...this.props} />; } } let instance; class Middle extends React.Component { constructor(props, context) { super(props, context); instance = this; } shouldComponentUpdate() { // Return false so that our child will get a NoWork priority (and get bailed out) return false; } render() { return <Child />; } } // Child must be a context provider to trigger the bug class Child extends React.Component { static childContextTypes = {}; getChildContext() { return {}; } render() { return <div />; } } // Init ReactNoop.render(<Root />); await waitForAll([]); // Trigger an update in the middle of the tree instance.setState({}); await waitForAll([]); }); // @gate !disableLegacyContext || !__DEV__ it('maintains the correct context when unwinding due to an error in render', async () => { class Root extends React.Component { componentDidCatch(error) { // If context is pushed/popped correctly, // This method will be used to handle the intentionally-thrown Error. } render() { return <ContextProvider depth={1} />; } } let instance; class ContextProvider extends React.Component { constructor(props, context) { super(props, context); this.state = {}; if (props.depth === 1) { instance = this; } } static childContextTypes = {}; getChildContext() { return {}; } render() { if (this.state.throwError) { throw Error(); } return this.props.depth < 4 ? ( <ContextProvider depth={this.props.depth + 1} /> ) : ( <div /> ); } } // Init ReactNoop.render(<Root />); await waitForAll([]); // Trigger an update in the middle of the tree // This is necessary to reproduce the error as it currently exists. instance.setState({ throwError: true, }); await expect(async () => await waitForAll([])).toErrorDev( 'Error boundaries should implement getDerivedStateFromError()', ); }); // @gate !disableLegacyContext || !__DEV__ it('should not recreate masked context unless inputs have changed', async () => { let scuCounter = 0; class MyComponent extends React.Component { static contextTypes = {}; componentDidMount(prevProps, prevState) { Scheduler.log('componentDidMount'); this.setState({setStateInCDU: true}); } componentDidUpdate(prevProps, prevState) { Scheduler.log('componentDidUpdate'); if (this.state.setStateInCDU) { this.setState({setStateInCDU: false}); } } UNSAFE_componentWillReceiveProps(nextProps) { Scheduler.log('componentWillReceiveProps'); this.setState({setStateInCDU: true}); } render() { Scheduler.log('render'); return null; } shouldComponentUpdate(nextProps, nextState) { Scheduler.log('shouldComponentUpdate'); return scuCounter++ < 5; // Don't let test hang } } ReactNoop.render(<MyComponent />); await waitForAll([ 'render', 'componentDidMount', 'shouldComponentUpdate', 'render', 'componentDidUpdate', 'shouldComponentUpdate', 'render', 'componentDidUpdate', ]); }); xit('should reuse memoized work if pointers are updated before calling lifecycles', async () => { const cduNextProps = []; const cduPrevProps = []; const scuNextProps = []; const scuPrevProps = []; let renderCounter = 0; function SecondChild(props) { return <span>{props.children}</span>; } class FirstChild extends React.Component { componentDidUpdate(prevProps, prevState) { cduNextProps.push(this.props); cduPrevProps.push(prevProps); } shouldComponentUpdate(nextProps, nextState) { scuNextProps.push(nextProps); scuPrevProps.push(this.props); return this.props.children !== nextProps.children; } render() { renderCounter++; return <span>{this.props.children}</span>; } } class Middle extends React.Component { render() { return ( <div> <FirstChild>{this.props.children}</FirstChild> <SecondChild>{this.props.children}</SecondChild> </div> ); } } function Root(props) { return ( <div hidden={true}> <Middle {...props} /> </div> ); } // Initial render of the entire tree. // Renders: Root, Middle, FirstChild, SecondChild ReactNoop.render(<Root>A</Root>); await waitForAll([]); expect(renderCounter).toBe(1); // Schedule low priority work to update children. // Give it enough time to partially render. // Renders: Root, Middle, FirstChild ReactNoop.render(<Root>B</Root>); ReactNoop.flushDeferredPri(20 + 30 + 5); // At this point our FirstChild component has rendered a second time, // But since the render is not completed cDU should not be called yet. expect(renderCounter).toBe(2); expect(scuPrevProps).toEqual([{children: 'A'}]); expect(scuNextProps).toEqual([{children: 'B'}]); expect(cduPrevProps).toEqual([]); expect(cduNextProps).toEqual([]); // Next interrupt the partial render with higher priority work. // The in-progress child content will bailout. // Renders: Root, Middle, FirstChild, SecondChild ReactNoop.render(<Root>B</Root>); await waitForAll([]); // At this point the higher priority render has completed. // Since FirstChild props didn't change, sCU returned false. // The previous memoized copy should be used. expect(renderCounter).toBe(2); expect(scuPrevProps).toEqual([{children: 'A'}, {children: 'B'}]); expect(scuNextProps).toEqual([{children: 'B'}, {children: 'B'}]); expect(cduPrevProps).toEqual([{children: 'A'}]); expect(cduNextProps).toEqual([{children: 'B'}]); }); // @gate !disableLegacyContext it('updates descendants with new context values', async () => { let instance; class TopContextProvider extends React.Component { static childContextTypes = { count: PropTypes.number, }; constructor() { super(); this.state = {count: 0}; instance = this; } getChildContext = () => ({ count: this.state.count, }); render = () => this.props.children; updateCount = () => this.setState(state => ({ count: state.count + 1, })); } class Middle extends React.Component { render = () => this.props.children; } class Child extends React.Component { static contextTypes = { count: PropTypes.number, }; render = () => { Scheduler.log(`count:${this.context.count}`); return null; }; } ReactNoop.render( <TopContextProvider> <Middle> <Child /> </Middle> </TopContextProvider>, ); await waitForAll(['count:0']); instance.updateCount(); await waitForAll(['count:1']); }); // @gate !disableLegacyContext it('updates descendants with multiple context-providing ancestors with new context values', async () => { let instance; class TopContextProvider extends React.Component { static childContextTypes = { count: PropTypes.number, }; constructor() { super(); this.state = {count: 0}; instance = this; } getChildContext = () => ({ count: this.state.count, }); render = () => this.props.children; updateCount = () => this.setState(state => ({ count: state.count + 1, })); } class MiddleContextProvider extends React.Component { static childContextTypes = { name: PropTypes.string, }; getChildContext = () => ({ name: 'brian', }); render = () => this.props.children; } class Child extends React.Component { static contextTypes = { count: PropTypes.number, }; render = () => { Scheduler.log(`count:${this.context.count}`); return null; }; } ReactNoop.render( <TopContextProvider> <MiddleContextProvider> <Child /> </MiddleContextProvider> </TopContextProvider>, ); await waitForAll(['count:0']); instance.updateCount(); await waitForAll(['count:1']); }); // @gate !disableLegacyContext it('should not update descendants with new context values if shouldComponentUpdate returns false', async () => { let instance; class TopContextProvider extends React.Component { static childContextTypes = { count: PropTypes.number, }; constructor() { super(); this.state = {count: 0}; instance = this; } getChildContext = () => ({ count: this.state.count, }); render = () => this.props.children; updateCount = () => this.setState(state => ({ count: state.count + 1, })); } class MiddleScu extends React.Component { shouldComponentUpdate() { return false; } render = () => this.props.children; } class MiddleContextProvider extends React.Component { static childContextTypes = { name: PropTypes.string, }; getChildContext = () => ({ name: 'brian', }); render = () => this.props.children; } class Child extends React.Component { static contextTypes = { count: PropTypes.number, }; render = () => { Scheduler.log(`count:${this.context.count}`); return null; }; } ReactNoop.render( <TopContextProvider> <MiddleScu> <MiddleContextProvider> <Child /> </MiddleContextProvider> </MiddleScu> </TopContextProvider>, ); await waitForAll(['count:0']); instance.updateCount(); await waitForAll([]); }); // @gate !disableLegacyContext it('should update descendants with new context values if setState() is called in the middle of the tree', async () => { let middleInstance; let topInstance; class TopContextProvider extends React.Component { static childContextTypes = { count: PropTypes.number, }; constructor() { super(); this.state = {count: 0}; topInstance = this; } getChildContext = () => ({ count: this.state.count, }); render = () => this.props.children; updateCount = () => this.setState(state => ({ count: state.count + 1, })); } class MiddleScu extends React.Component { shouldComponentUpdate() { return false; } render = () => this.props.children; } class MiddleContextProvider extends React.Component { static childContextTypes = { name: PropTypes.string, }; constructor() { super(); this.state = {name: 'brian'}; middleInstance = this; } getChildContext = () => ({ name: this.state.name, }); updateName = name => { this.setState({name}); }; render = () => this.props.children; } class Child extends React.Component { static contextTypes = { count: PropTypes.number, name: PropTypes.string, }; render = () => { Scheduler.log(`count:${this.context.count}, name:${this.context.name}`); return null; }; } ReactNoop.render( <TopContextProvider> <MiddleScu> <MiddleContextProvider> <Child /> </MiddleContextProvider> </MiddleScu> </TopContextProvider>, ); await waitForAll(['count:0, name:brian']); topInstance.updateCount(); await waitForAll([]); middleInstance.updateName('not brian'); await waitForAll(['count:1, name:not brian']); }); it('does not interrupt for update at same priority', async () => { function Parent(props) { Scheduler.log('Parent: ' + props.step); return <Child step={props.step} />; } function Child(props) { Scheduler.log('Child: ' + props.step); return null; } React.startTransition(() => { ReactNoop.render(<Parent step={1} />); }); await waitFor(['Parent: 1']); // Interrupt at same priority ReactNoop.render(<Parent step={2} />); await waitForAll(['Child: 1', 'Parent: 2', 'Child: 2']); }); it('does not interrupt for update at lower priority', async () => { function Parent(props) { Scheduler.log('Parent: ' + props.step); return <Child step={props.step} />; } function Child(props) { Scheduler.log('Child: ' + props.step); return null; } React.startTransition(() => { ReactNoop.render(<Parent step={1} />); }); await waitFor(['Parent: 1']); // Interrupt at lower priority ReactNoop.expire(2000); ReactNoop.render(<Parent step={2} />); await waitForAll(['Child: 1', 'Parent: 2', 'Child: 2']); }); it('does interrupt for update at higher priority', async () => { function Parent(props) { Scheduler.log('Parent: ' + props.step); return <Child step={props.step} />; } function Child(props) { Scheduler.log('Child: ' + props.step); return null; } React.startTransition(() => { ReactNoop.render(<Parent step={1} />); }); await waitFor(['Parent: 1']); // Interrupt at higher priority ReactNoop.flushSync(() => ReactNoop.render(<Parent step={2} />)); assertLog(['Parent: 2', 'Child: 2']); await waitForAll([]); }); // We sometimes use Maps with Fibers as keys. // @gate !disableLegacyContext || !__DEV__ it('does not break with a bad Map polyfill', async () => { const realMapSet = Map.prototype.set; async function triggerCodePathThatUsesFibersAsMapKeys() { function Thing() { throw new Error('No.'); } // This class uses legacy context, which triggers warnings, // the procedures for which use a Map to store fibers. class Boundary extends React.Component { state = {didError: false}; componentDidCatch() { this.setState({didError: true}); } static contextTypes = { color: () => null, }; render() { return this.state.didError ? null : <Thing />; } } ReactNoop.render( <React.StrictMode> <Boundary /> </React.StrictMode>, ); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'Legacy context API has been detected within a strict-mode tree', ]); } // First, verify that this code path normally receives Fibers as keys, // and that they're not extensible. jest.resetModules(); let receivedNonExtensibleObjects; // eslint-disable-next-line no-extend-native Map.prototype.set = function (key) { if (typeof key === 'object' && key !== null) { if (!Object.isExtensible(key)) { receivedNonExtensibleObjects = true; } } return realMapSet.apply(this, arguments); }; React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); let InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForThrow = InternalTestUtils.waitForThrow; assertLog = InternalTestUtils.assertLog; try { receivedNonExtensibleObjects = false; await triggerCodePathThatUsesFibersAsMapKeys(); } finally { // eslint-disable-next-line no-extend-native Map.prototype.set = realMapSet; } // If this fails, find another code path in Fiber // that passes Fibers as keys to Maps. // Note that we only expect them to be non-extensible // in development. expect(receivedNonExtensibleObjects).toBe(__DEV__); // Next, verify that a Map polyfill that "writes" to keys // doesn't cause a failure. jest.resetModules(); // eslint-disable-next-line no-extend-native Map.prototype.set = function (key, value) { if (typeof key === 'object' && key !== null) { // A polyfill could do something like this. // It would throw if an object is not extensible. key.__internalValueSlot = value; } return realMapSet.apply(this, arguments); }; React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForThrow = InternalTestUtils.waitForThrow; assertLog = InternalTestUtils.assertLog; try { await triggerCodePathThatUsesFibersAsMapKeys(); } finally { // eslint-disable-next-line no-extend-native Map.prototype.set = realMapSet; } // If we got this far, our feature detection worked. // We knew that Map#set() throws for non-extensible objects, // so we didn't set them as non-extensible for that reason. }); });
25.562971
121
0.566662
owtf
import React from 'react'; import {hydrateRoot} from 'react-dom/client'; import App from './components/App'; hydrateRoot(document, <App assets={window.assetManifest} />);
23.857143
61
0.739884
null
'use strict'; const chalk = require('chalk'); const colors = { blue: '#0091ea', gray: '#78909c', green: '#00c853', red: '#d50000', yellow: '#ffd600', }; const theme = chalk.constructor(); theme.package = theme.hex(colors.green); theme.version = theme.hex(colors.yellow); theme.tag = theme.hex(colors.yellow); theme.build = theme.hex(colors.yellow); theme.commit = theme.hex(colors.yellow); theme.error = theme.hex(colors.red).bold; theme.dimmed = theme.hex(colors.gray); theme.caution = theme.hex(colors.red).bold; theme.link = theme.hex(colors.blue).underline.italic; theme.header = theme.hex(colors.green).bold; theme.path = theme.hex(colors.gray).italic; theme.command = theme.hex(colors.gray); theme.quote = theme.italic; theme.diffHeader = theme.hex(colors.gray); theme.diffAdded = theme.hex(colors.green); theme.diffRemoved = theme.hex(colors.red); theme.spinnerInProgress = theme.hex(colors.yellow); theme.spinnerError = theme.hex(colors.red); theme.spinnerSuccess = theme.hex(colors.green); module.exports = theme;
27.108108
53
0.727623
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 EventEmitter from '../events'; import throttle from 'lodash.throttle'; import { SESSION_STORAGE_LAST_SELECTION_KEY, SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, __DEBUG__, } from '../constants'; import { sessionStorageGetItem, sessionStorageRemoveItem, sessionStorageSetItem, } from 'react-devtools-shared/src/storage'; import setupHighlighter from './views/Highlighter'; import { initialize as setupTraceUpdates, toggleEnabled as setTraceUpdatesEnabled, } from './views/TraceUpdates'; import {patch as patchConsole} from './console'; import {currentBridgeProtocol} from 'react-devtools-shared/src/bridge'; import type {BackendBridge} from 'react-devtools-shared/src/bridge'; import type { InstanceAndStyle, NativeType, OwnersList, PathFrame, PathMatch, RendererID, RendererInterface, ConsolePatchSettings, } from './types'; import type { ComponentFilter, BrowserTheme, } from 'react-devtools-shared/src/frontend/types'; import {isSynchronousXHRSupported} from './utils'; const debug = (methodName: string, ...args: Array<string>) => { if (__DEBUG__) { console.log( `%cAgent %c${methodName}`, 'color: purple; font-weight: bold;', 'font-weight: bold;', ...args, ); } }; type ElementAndRendererID = { id: number, rendererID: number, }; type StoreAsGlobalParams = { count: number, id: number, path: Array<string | number>, rendererID: number, }; type CopyElementParams = { id: number, path: Array<string | number>, rendererID: number, }; type InspectElementParams = { forceFullData: boolean, id: number, path: Array<string | number> | null, rendererID: number, requestID: number, }; type OverrideHookParams = { id: number, hookID: number, path: Array<string | number>, rendererID: number, wasForwarded?: boolean, value: any, }; type SetInParams = { id: number, path: Array<string | number>, rendererID: number, wasForwarded?: boolean, value: any, }; type PathType = 'props' | 'hooks' | 'state' | 'context'; type DeletePathParams = { type: PathType, hookID?: ?number, id: number, path: Array<string | number>, rendererID: number, }; type RenamePathParams = { type: PathType, hookID?: ?number, id: number, oldPath: Array<string | number>, newPath: Array<string | number>, rendererID: number, }; type OverrideValueAtPathParams = { type: PathType, hookID?: ?number, id: number, path: Array<string | number>, rendererID: number, value: any, }; type OverrideErrorParams = { id: number, rendererID: number, forceError: boolean, }; type OverrideSuspenseParams = { id: number, rendererID: number, forceFallback: boolean, }; type PersistedSelection = { rendererID: number, path: Array<PathFrame>, }; export default class Agent extends EventEmitter<{ hideNativeHighlight: [], showNativeHighlight: [NativeType], startInspectingNative: [], stopInspectingNative: [], shutdown: [], traceUpdates: [Set<NativeType>], drawTraceUpdates: [Array<NativeType>], disableTraceUpdates: [], }> { _bridge: BackendBridge; _isProfiling: boolean = false; _recordChangeDescriptions: boolean = false; _rendererInterfaces: {[key: RendererID]: RendererInterface, ...} = {}; _persistedSelection: PersistedSelection | null = null; _persistedSelectionMatch: PathMatch | null = null; _traceUpdatesEnabled: boolean = false; constructor(bridge: BackendBridge) { super(); if ( sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true' ) { this._recordChangeDescriptions = sessionStorageGetItem( SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, ) === 'true'; this._isProfiling = true; sessionStorageRemoveItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY); sessionStorageRemoveItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY); } const persistedSelectionString = sessionStorageGetItem( SESSION_STORAGE_LAST_SELECTION_KEY, ); if (persistedSelectionString != null) { this._persistedSelection = JSON.parse(persistedSelectionString); } this._bridge = bridge; bridge.addListener('clearErrorsAndWarnings', this.clearErrorsAndWarnings); bridge.addListener('clearErrorsForFiberID', this.clearErrorsForFiberID); bridge.addListener('clearWarningsForFiberID', this.clearWarningsForFiberID); bridge.addListener('copyElementPath', this.copyElementPath); bridge.addListener('deletePath', this.deletePath); bridge.addListener('getBackendVersion', this.getBackendVersion); bridge.addListener('getBridgeProtocol', this.getBridgeProtocol); bridge.addListener('getProfilingData', this.getProfilingData); bridge.addListener('getProfilingStatus', this.getProfilingStatus); bridge.addListener('getOwnersList', this.getOwnersList); bridge.addListener('inspectElement', this.inspectElement); bridge.addListener('logElementToConsole', this.logElementToConsole); bridge.addListener('overrideError', this.overrideError); bridge.addListener('overrideSuspense', this.overrideSuspense); bridge.addListener('overrideValueAtPath', this.overrideValueAtPath); bridge.addListener('reloadAndProfile', this.reloadAndProfile); bridge.addListener('renamePath', this.renamePath); bridge.addListener('setTraceUpdatesEnabled', this.setTraceUpdatesEnabled); bridge.addListener('startProfiling', this.startProfiling); bridge.addListener('stopProfiling', this.stopProfiling); bridge.addListener('storeAsGlobal', this.storeAsGlobal); bridge.addListener( 'syncSelectionFromNativeElementsPanel', this.syncSelectionFromNativeElementsPanel, ); bridge.addListener('shutdown', this.shutdown); bridge.addListener( 'updateConsolePatchSettings', this.updateConsolePatchSettings, ); bridge.addListener('updateComponentFilters', this.updateComponentFilters); bridge.addListener('viewAttributeSource', this.viewAttributeSource); bridge.addListener('viewElementSource', this.viewElementSource); // Temporarily support older standalone front-ends sending commands to newer embedded backends. // We do this because React Native embeds the React DevTools backend, // but cannot control which version of the frontend users use. bridge.addListener('overrideContext', this.overrideContext); bridge.addListener('overrideHookState', this.overrideHookState); bridge.addListener('overrideProps', this.overrideProps); bridge.addListener('overrideState', this.overrideState); if (this._isProfiling) { bridge.send('profilingStatus', true); } // Send the Bridge protocol and backend versions, after initialization, in case the frontend has already requested it. // The Store may be instantiated beore the agent. const version = process.env.DEVTOOLS_VERSION; if (version) { this._bridge.send('backendVersion', version); } this._bridge.send('bridgeProtocol', currentBridgeProtocol); // Notify the frontend if the backend supports the Storage API (e.g. localStorage). // If not, features like reload-and-profile will not work correctly and must be disabled. let isBackendStorageAPISupported = false; try { localStorage.getItem('test'); isBackendStorageAPISupported = true; } catch (error) {} bridge.send('isBackendStorageAPISupported', isBackendStorageAPISupported); bridge.send('isSynchronousXHRSupported', isSynchronousXHRSupported()); setupHighlighter(bridge, this); setupTraceUpdates(this); } get rendererInterfaces(): {[key: RendererID]: RendererInterface, ...} { return this._rendererInterfaces; } clearErrorsAndWarnings: ({rendererID: RendererID}) => void = ({ rendererID, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); } else { renderer.clearErrorsAndWarnings(); } }; clearErrorsForFiberID: ElementAndRendererID => void = ({id, rendererID}) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); } else { renderer.clearErrorsForFiberID(id); } }; clearWarningsForFiberID: ElementAndRendererID => void = ({ id, rendererID, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); } else { renderer.clearWarningsForFiberID(id); } }; copyElementPath: CopyElementParams => void = ({ id, path, rendererID, }: CopyElementParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { const value = renderer.getSerializedElementValueByPath(id, path); if (value != null) { this._bridge.send('saveToClipboard', value); } else { console.warn(`Unable to obtain serialized value for element "${id}"`); } } }; deletePath: DeletePathParams => void = ({ hookID, id, path, rendererID, type, }: DeletePathParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.deletePath(type, id, hookID, path); } }; getInstanceAndStyle({ id, rendererID, }: ElementAndRendererID): InstanceAndStyle | null { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); return null; } return renderer.getInstanceAndStyle(id); } getBestMatchingRendererInterface(node: Object): RendererInterface | null { let bestMatch = null; for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); const fiber = renderer.getFiberForNative(node); if (fiber !== null) { // check if fiber.stateNode is matching the original hostInstance if (fiber.stateNode === node) { return renderer; } else if (bestMatch === null) { bestMatch = renderer; } } } // if an exact match is not found, return the first valid renderer as fallback return bestMatch; } getIDForNode(node: Object): number | null { const rendererInterface = this.getBestMatchingRendererInterface(node); if (rendererInterface != null) { try { return rendererInterface.getFiberIDForNative(node, true); } catch (error) { // Some old React versions might throw if they can't find a match. // If so we should ignore it... } } return null; } getBackendVersion: () => void = () => { const version = process.env.DEVTOOLS_VERSION; if (version) { this._bridge.send('backendVersion', version); } }; getBridgeProtocol: () => void = () => { this._bridge.send('bridgeProtocol', currentBridgeProtocol); }; getProfilingData: ({rendererID: RendererID}) => void = ({rendererID}) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); } this._bridge.send('profilingData', renderer.getProfilingData()); }; getProfilingStatus: () => void = () => { this._bridge.send('profilingStatus', this._isProfiling); }; getOwnersList: ElementAndRendererID => void = ({id, rendererID}) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { const owners = renderer.getOwnersList(id); this._bridge.send('ownersList', ({id, owners}: OwnersList)); } }; inspectElement: InspectElementParams => void = ({ forceFullData, id, path, rendererID, requestID, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { this._bridge.send( 'inspectedElement', renderer.inspectElement(requestID, id, path, forceFullData), ); // When user selects an element, stop trying to restore the selection, // and instead remember the current selection for the next reload. if ( this._persistedSelectionMatch === null || this._persistedSelectionMatch.id !== id ) { this._persistedSelection = null; this._persistedSelectionMatch = null; renderer.setTrackedPath(null); this._throttledPersistSelection(rendererID, id); } // TODO: If there was a way to change the selected DOM element // in native Elements tab without forcing a switch to it, we'd do it here. // For now, it doesn't seem like there is a way to do that: // https://github.com/bvaughn/react-devtools-experimental/issues/102 // (Setting $0 doesn't work, and calling inspect() switches the tab.) } }; logElementToConsole: ElementAndRendererID => void = ({id, rendererID}) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.logElementToConsole(id); } }; overrideError: OverrideErrorParams => void = ({ id, rendererID, forceError, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.overrideError(id, forceError); } }; overrideSuspense: OverrideSuspenseParams => void = ({ id, rendererID, forceFallback, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.overrideSuspense(id, forceFallback); } }; overrideValueAtPath: OverrideValueAtPathParams => void = ({ hookID, id, path, rendererID, type, value, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.overrideValueAtPath(type, id, hookID, path, value); } }; // Temporarily support older standalone front-ends by forwarding the older message types // to the new "overrideValueAtPath" command the backend is now listening to. overrideContext: SetInParams => void = ({ id, path, rendererID, wasForwarded, value, }) => { // Don't forward a message that's already been forwarded by the front-end Bridge. // We only need to process the override command once! if (!wasForwarded) { this.overrideValueAtPath({ id, path, rendererID, type: 'context', value, }); } }; // Temporarily support older standalone front-ends by forwarding the older message types // to the new "overrideValueAtPath" command the backend is now listening to. overrideHookState: OverrideHookParams => void = ({ id, hookID, path, rendererID, wasForwarded, value, }) => { // Don't forward a message that's already been forwarded by the front-end Bridge. // We only need to process the override command once! if (!wasForwarded) { this.overrideValueAtPath({ id, path, rendererID, type: 'hooks', value, }); } }; // Temporarily support older standalone front-ends by forwarding the older message types // to the new "overrideValueAtPath" command the backend is now listening to. overrideProps: SetInParams => void = ({ id, path, rendererID, wasForwarded, value, }) => { // Don't forward a message that's already been forwarded by the front-end Bridge. // We only need to process the override command once! if (!wasForwarded) { this.overrideValueAtPath({ id, path, rendererID, type: 'props', value, }); } }; // Temporarily support older standalone front-ends by forwarding the older message types // to the new "overrideValueAtPath" command the backend is now listening to. overrideState: SetInParams => void = ({ id, path, rendererID, wasForwarded, value, }) => { // Don't forward a message that's already been forwarded by the front-end Bridge. // We only need to process the override command once! if (!wasForwarded) { this.overrideValueAtPath({ id, path, rendererID, type: 'state', value, }); } }; reloadAndProfile: (recordChangeDescriptions: boolean) => void = recordChangeDescriptions => { sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true'); sessionStorageSetItem( SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, recordChangeDescriptions ? 'true' : 'false', ); // This code path should only be hit if the shell has explicitly told the Store that it supports profiling. // In that case, the shell must also listen for this specific message to know when it needs to reload the app. // The agent can't do this in a way that is renderer agnostic. this._bridge.send('reloadAppForProfiling'); }; renamePath: RenamePathParams => void = ({ hookID, id, newPath, oldPath, rendererID, type, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.renamePath(type, id, hookID, oldPath, newPath); } }; selectNode(target: Object): void { const id = this.getIDForNode(target); if (id !== null) { this._bridge.send('selectFiber', id); } } setRendererInterface( rendererID: RendererID, rendererInterface: RendererInterface, ) { this._rendererInterfaces[rendererID] = rendererInterface; if (this._isProfiling) { rendererInterface.startProfiling(this._recordChangeDescriptions); } rendererInterface.setTraceUpdatesEnabled(this._traceUpdatesEnabled); // When the renderer is attached, we need to tell it whether // we remember the previous selection that we'd like to restore. // It'll start tracking mounts for matches to the last selection path. const selection = this._persistedSelection; if (selection !== null && selection.rendererID === rendererID) { rendererInterface.setTrackedPath(selection.path); } } setTraceUpdatesEnabled: (traceUpdatesEnabled: boolean) => void = traceUpdatesEnabled => { this._traceUpdatesEnabled = traceUpdatesEnabled; setTraceUpdatesEnabled(traceUpdatesEnabled); for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.setTraceUpdatesEnabled(traceUpdatesEnabled); } }; syncSelectionFromNativeElementsPanel: () => void = () => { const target = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0; if (target == null) { return; } this.selectNode(target); }; shutdown: () => void = () => { // Clean up the overlay if visible, and associated events. this.emit('shutdown'); }; startProfiling: (recordChangeDescriptions: boolean) => void = recordChangeDescriptions => { this._recordChangeDescriptions = recordChangeDescriptions; this._isProfiling = true; for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.startProfiling(recordChangeDescriptions); } this._bridge.send('profilingStatus', this._isProfiling); }; stopProfiling: () => void = () => { this._isProfiling = false; this._recordChangeDescriptions = false; for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.stopProfiling(); } this._bridge.send('profilingStatus', this._isProfiling); }; stopInspectingNative: (selected: boolean) => void = selected => { this._bridge.send('stopInspectingNative', selected); }; storeAsGlobal: StoreAsGlobalParams => void = ({ count, id, path, rendererID, }) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.storeAsGlobal(id, path, count); } }; updateConsolePatchSettings: ({ appendComponentStack: boolean, breakOnConsoleErrors: boolean, browserTheme: BrowserTheme, hideConsoleLogsInStrictMode: boolean, showInlineWarningsAndErrors: boolean, }) => void = ({ appendComponentStack, breakOnConsoleErrors, showInlineWarningsAndErrors, hideConsoleLogsInStrictMode, browserTheme, }: ConsolePatchSettings) => { // If the frontend preferences have changed, // or in the case of React Native- if the backend is just finding out the preferences- // then reinstall the console overrides. // It's safe to call `patchConsole` multiple times. patchConsole({ appendComponentStack, breakOnConsoleErrors, showInlineWarningsAndErrors, hideConsoleLogsInStrictMode, browserTheme, }); }; updateComponentFilters: (componentFilters: Array<ComponentFilter>) => void = componentFilters => { for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.updateComponentFilters(componentFilters); } }; viewAttributeSource: CopyElementParams => void = ({id, path, rendererID}) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.prepareViewAttributeSource(id, path); } }; viewElementSource: ElementAndRendererID => void = ({id, rendererID}) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.prepareViewElementSource(id); } }; onTraceUpdates: (nodes: Set<NativeType>) => void = nodes => { this.emit('traceUpdates', nodes); }; onFastRefreshScheduled: () => void = () => { if (__DEBUG__) { debug('onFastRefreshScheduled'); } this._bridge.send('fastRefreshScheduled'); }; onHookOperations: (operations: Array<number>) => void = operations => { if (__DEBUG__) { debug( 'onHookOperations', `(${operations.length}) [${operations.join(', ')}]`, ); } // TODO: // The chrome.runtime does not currently support transferables; it forces JSON serialization. // See bug https://bugs.chromium.org/p/chromium/issues/detail?id=927134 // // Regarding transferables, the postMessage doc states: // If the ownership of an object is transferred, it becomes unusable (neutered) // in the context it was sent from and becomes available only to the worker it was sent to. // // Even though Chrome is eventually JSON serializing the array buffer, // using the transferable approach also sometimes causes it to throw: // DOMException: Failed to execute 'postMessage' on 'Window': ArrayBuffer at index 0 is already neutered. // // See bug https://github.com/bvaughn/react-devtools-experimental/issues/25 // // The Store has a fallback in place that parses the message as JSON if the type isn't an array. // For now the simplest fix seems to be to not transfer the array. // This will negatively impact performance on Firefox so it's unfortunate, // but until we're able to fix the Chrome error mentioned above, it seems necessary. // // this._bridge.send('operations', operations, [operations.buffer]); this._bridge.send('operations', operations); if (this._persistedSelection !== null) { const rendererID = operations[0]; if (this._persistedSelection.rendererID === rendererID) { // Check if we can select a deeper match for the persisted selection. const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); } else { const prevMatch = this._persistedSelectionMatch; const nextMatch = renderer.getBestMatchForTrackedPath(); this._persistedSelectionMatch = nextMatch; const prevMatchID = prevMatch !== null ? prevMatch.id : null; const nextMatchID = nextMatch !== null ? nextMatch.id : null; if (prevMatchID !== nextMatchID) { if (nextMatchID !== null) { // We moved forward, unlocking a deeper node. this._bridge.send('selectFiber', nextMatchID); } } if (nextMatch !== null && nextMatch.isFullMatch) { // We've just unlocked the innermost selected node. // There's no point tracking it further. this._persistedSelection = null; this._persistedSelectionMatch = null; renderer.setTrackedPath(null); } } } } }; onUnsupportedRenderer(rendererID: number) { this._bridge.send('unsupportedRendererVersion', rendererID); } _throttledPersistSelection: any = throttle( (rendererID: number, id: number) => { // This is throttled, so both renderer and selected ID // might not be available by the time we read them. // This is why we need the defensive checks here. const renderer = this._rendererInterfaces[rendererID]; const path = renderer != null ? renderer.getPathForElement(id) : null; if (path !== null) { sessionStorageSetItem( SESSION_STORAGE_LAST_SELECTION_KEY, JSON.stringify(({rendererID, path}: PersistedSelection)), ); } else { sessionStorageRemoveItem(SESSION_STORAGE_LAST_SELECTION_KEY); } }, 1000, ); }
30.602787
122
0.662832
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 {AsyncLocalStorage} from 'async_hooks'; import type {Request} from 'react-server/src/ReactFlightServer'; export * from 'react-server-dom-turbopack/src/ReactFlightServerConfigTurbopackBundler'; export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM'; export const supportsRequestStorage = true; export const requestStorage: AsyncLocalStorage<Request> = new AsyncLocalStorage(); export {createHook as createAsyncHook, executionAsyncId} from 'async_hooks'; export * from '../ReactFlightServerConfigDebugNode';
31.26087
87
0.777328
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {useSyncExternalStore} from 'use-sync-external-store/shim'; // Hook used for safely managing subscriptions in concurrent mode. // // In order to avoid removing and re-adding subscriptions each time this hook is called, // the parameters passed to this hook should be memoized in some way– // either by wrapping the entire params object with useMemo() // or by wrapping the individual callbacks with useCallback(). export function useSubscription<Value>({ // (Synchronously) returns the current value of our subscription. getCurrentValue, // This function is passed an event handler to attach to the subscription. // It should return an unsubscribe function that removes the handler. subscribe, }: { getCurrentValue: () => Value, subscribe: (callback: Function) => () => void, }): Value { return useSyncExternalStore(subscribe, getCurrentValue); }
33.741935
88
0.741636
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'; module.exports = jest.fn();
20.454545
66
0.697872
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Lane, Lanes} from './ReactFiberLane'; import type {Fiber, FiberRoot} from './ReactInternalTypes'; import type {ReactNodeList, Wakeable} from 'shared/ReactTypes'; import type {EventPriority} from './ReactEventPriorities'; // import type {DevToolsProfilingHooks} from 'react-devtools-shared/src/backend/types'; // TODO: This import doesn't work because the DevTools depend on the DOM version of React // and to properly type check against DOM React we can't also type check again non-DOM // React which this hook might be in. type DevToolsProfilingHooks = any; import {getLabelForLane, TotalLanes} from 'react-reconciler/src/ReactFiberLane'; import {DidCapture} from './ReactFiberFlags'; import { consoleManagedByDevToolsDuringStrictMode, enableProfilerTimer, enableSchedulingProfiler, } from 'shared/ReactFeatureFlags'; import { DiscreteEventPriority, ContinuousEventPriority, DefaultEventPriority, IdleEventPriority, } from './ReactEventPriorities'; import { ImmediatePriority as ImmediateSchedulerPriority, UserBlockingPriority as UserBlockingSchedulerPriority, NormalPriority as NormalSchedulerPriority, IdlePriority as IdleSchedulerPriority, log, unstable_setDisableYieldValue, } from './Scheduler'; import {setSuppressWarning} from 'shared/consoleWithStackDev'; import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev'; declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void; let rendererID = null; let injectedHook = null; let injectedProfilingHooks: DevToolsProfilingHooks | null = null; let hasLoggedError = false; export const isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; export function injectInternals(internals: Object): boolean { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // No DevTools return false; } const hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } if (!hook.supportsFiber) { if (__DEV__) { console.error( 'The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools', ); } // DevTools exists, even though it doesn't support Fiber. return true; } try { if (enableSchedulingProfiler) { // Conditionally inject these hooks only if Timeline profiler is supported by this build. // This gives DevTools a way to feature detect that isn't tied to version number // (since profiling and timeline are controlled by different feature flags). internals = { ...internals, getLaneLabelMap, injectProfilingHooks, }; } rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. injectedHook = hook; } catch (err) { // Catch all errors because it is unsafe to throw during initialization. if (__DEV__) { console.error('React instrumentation encountered an error: %s.', err); } } if (hook.checkDCE) { // This is the real DevTools. return true; } else { // This is likely a hook installed by Fast Refresh runtime. return false; } } export function onScheduleRoot(root: FiberRoot, children: ReactNodeList) { if (__DEV__) { if ( injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function' ) { try { injectedHook.onScheduleFiberRoot(rendererID, root, children); } catch (err) { if (__DEV__ && !hasLoggedError) { hasLoggedError = true; console.error('React instrumentation encountered an error: %s', err); } } } } } export function onCommitRoot(root: FiberRoot, eventPriority: EventPriority) { if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { try { const didError = (root.current.flags & DidCapture) === DidCapture; if (enableProfilerTimer) { let schedulerPriority; switch (eventPriority) { case DiscreteEventPriority: schedulerPriority = ImmediateSchedulerPriority; break; case ContinuousEventPriority: schedulerPriority = UserBlockingSchedulerPriority; break; case DefaultEventPriority: schedulerPriority = NormalSchedulerPriority; break; case IdleEventPriority: schedulerPriority = IdleSchedulerPriority; break; default: schedulerPriority = NormalSchedulerPriority; break; } injectedHook.onCommitFiberRoot( rendererID, root, schedulerPriority, didError, ); } else { injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError); } } catch (err) { if (__DEV__) { if (!hasLoggedError) { hasLoggedError = true; console.error('React instrumentation encountered an error: %s', err); } } } } } export function onPostCommitRoot(root: FiberRoot) { if ( injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function' ) { try { injectedHook.onPostCommitFiberRoot(rendererID, root); } catch (err) { if (__DEV__) { if (!hasLoggedError) { hasLoggedError = true; console.error('React instrumentation encountered an error: %s', err); } } } } } export function onCommitUnmount(fiber: Fiber) { if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { try { injectedHook.onCommitFiberUnmount(rendererID, fiber); } catch (err) { if (__DEV__) { if (!hasLoggedError) { hasLoggedError = true; console.error('React instrumentation encountered an error: %s', err); } } } } } export function setIsStrictModeForDevtools(newIsStrictMode: boolean) { if (consoleManagedByDevToolsDuringStrictMode) { if (typeof log === 'function') { // We're in a test because Scheduler.log only exists // in SchedulerMock. To reduce the noise in strict mode tests, // suppress warnings and disable scheduler yielding during the double render unstable_setDisableYieldValue(newIsStrictMode); setSuppressWarning(newIsStrictMode); } if (injectedHook && typeof injectedHook.setStrictMode === 'function') { try { injectedHook.setStrictMode(rendererID, newIsStrictMode); } catch (err) { if (__DEV__) { if (!hasLoggedError) { hasLoggedError = true; console.error( 'React instrumentation encountered an error: %s', err, ); } } } } } else { if (newIsStrictMode) { disableLogs(); } else { reenableLogs(); } } } // Profiler API hooks function injectProfilingHooks(profilingHooks: DevToolsProfilingHooks): void { injectedProfilingHooks = profilingHooks; } function getLaneLabelMap(): Map<Lane, string> | null { if (enableSchedulingProfiler) { const map: Map<Lane, string> = new Map(); let lane = 1; for (let index = 0; index < TotalLanes; index++) { const label = ((getLabelForLane(lane): any): string); map.set(lane, label); lane *= 2; } return map; } else { return null; } } export function markCommitStarted(lanes: Lanes): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function' ) { injectedProfilingHooks.markCommitStarted(lanes); } } } export function markCommitStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function' ) { injectedProfilingHooks.markCommitStopped(); } } } export function markComponentRenderStarted(fiber: Fiber): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function' ) { injectedProfilingHooks.markComponentRenderStarted(fiber); } } } export function markComponentRenderStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function' ) { injectedProfilingHooks.markComponentRenderStopped(); } } } export function markComponentPassiveEffectMountStarted(fiber: Fiber): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function' ) { injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); } } } export function markComponentPassiveEffectMountStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function' ) { injectedProfilingHooks.markComponentPassiveEffectMountStopped(); } } } export function markComponentPassiveEffectUnmountStarted(fiber: Fiber): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function' ) { injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); } } } export function markComponentPassiveEffectUnmountStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function' ) { injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); } } } export function markComponentLayoutEffectMountStarted(fiber: Fiber): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function' ) { injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); } } } export function markComponentLayoutEffectMountStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function' ) { injectedProfilingHooks.markComponentLayoutEffectMountStopped(); } } } export function markComponentLayoutEffectUnmountStarted(fiber: Fiber): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function' ) { injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); } } } export function markComponentLayoutEffectUnmountStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function' ) { injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); } } } export function markComponentErrored( fiber: Fiber, thrownValue: mixed, lanes: Lanes, ): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function' ) { injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); } } } export function markComponentSuspended( fiber: Fiber, wakeable: Wakeable, lanes: Lanes, ): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function' ) { injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); } } } export function markLayoutEffectsStarted(lanes: Lanes): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function' ) { injectedProfilingHooks.markLayoutEffectsStarted(lanes); } } } export function markLayoutEffectsStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function' ) { injectedProfilingHooks.markLayoutEffectsStopped(); } } } export function markPassiveEffectsStarted(lanes: Lanes): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function' ) { injectedProfilingHooks.markPassiveEffectsStarted(lanes); } } } export function markPassiveEffectsStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function' ) { injectedProfilingHooks.markPassiveEffectsStopped(); } } } export function markRenderStarted(lanes: Lanes): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function' ) { injectedProfilingHooks.markRenderStarted(lanes); } } } export function markRenderYielded(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function' ) { injectedProfilingHooks.markRenderYielded(); } } } export function markRenderStopped(): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function' ) { injectedProfilingHooks.markRenderStopped(); } } } export function markRenderScheduled(lane: Lane): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function' ) { injectedProfilingHooks.markRenderScheduled(lane); } } } export function markForceUpdateScheduled(fiber: Fiber, lane: Lane): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function' ) { injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); } } } export function markStateUpdateScheduled(fiber: Fiber, lane: Lane): void { if (enableSchedulingProfiler) { if ( injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function' ) { injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); } } }
27.775093
95
0.679974
owtf
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-jsx-dev-runtime.production.min.js'); } else { module.exports = require('./cjs/react-jsx-dev-runtime.development.js'); }
26.875
76
0.684685
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 */ 'use strict'; // Intentionally not using named imports because Rollup uses dynamic // dispatch for CommonJS interop named imports. import * as shim from 'use-sync-external-store/shim'; export const useSyncExternalStore = shim.useSyncExternalStore;
25.764706
68
0.746696
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 type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | TouchEvent; export type PluginName = string; export type EventSystemFlags = number;
22.8
77
0.730337
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 Store from 'react-devtools-shared/src/devtools/store'; describe('ProfilerStore', () => { let React; let ReactDOM; let legacyRender; let store: Store; let utils; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); legacyRender = utils.legacyRender; store = global.store; store.collapseNodesByDefault = false; store.recordChangeDescriptions = true; React = require('react'); ReactDOM = require('react-dom'); }); // @reactVersion >= 16.9 it('should not remove profiling data when roots are unmounted', async () => { const Parent = ({count}) => new Array(count) .fill(true) .map((_, index) => <Child key={index} duration={index} />); const Child = () => <div>Hi!</div>; const containerA = document.createElement('div'); const containerB = document.createElement('div'); utils.act(() => { legacyRender(<Parent key="A" count={3} />, containerA); legacyRender(<Parent key="B" count={2} />, containerB); }); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => { legacyRender(<Parent key="A" count={4} />, containerA); legacyRender(<Parent key="B" count={1} />, containerB); }); utils.act(() => store.profilerStore.stopProfiling()); const rootA = store.roots[0]; const rootB = store.roots[1]; utils.act(() => ReactDOM.unmountComponentAtNode(containerB)); expect(store.profilerStore.getDataForRoot(rootA)).not.toBeNull(); utils.act(() => ReactDOM.unmountComponentAtNode(containerA)); expect(store.profilerStore.getDataForRoot(rootB)).not.toBeNull(); }); // @reactVersion >= 16.9 it('should not allow new/saved profiling data to be set while profiling is in progress', () => { utils.act(() => store.profilerStore.startProfiling()); const fauxProfilingData = { dataForRoots: new Map(), }; jest.spyOn(console, 'warn').mockImplementation(() => {}); store.profilerStore.profilingData = fauxProfilingData; expect(store.profilerStore.profilingData).not.toBe(fauxProfilingData); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledWith( 'Profiling data cannot be updated while profiling is in progress.', ); utils.act(() => store.profilerStore.stopProfiling()); store.profilerStore.profilingData = fauxProfilingData; expect(store.profilerStore.profilingData).toBe(fauxProfilingData); }); // @reactVersion >= 16.9 // This test covers current broken behavior (arguably) with the synthetic event system. it('should filter empty commits', () => { const inputRef = React.createRef(); const ControlledInput = () => { const [name, setName] = React.useState('foo'); const handleChange = event => setName(event.target.value); return <input ref={inputRef} value={name} onChange={handleChange} />; }; const container = document.createElement('div'); // This element has to be in the <body> for the event system to work. document.body.appendChild(container); // It's important that this test uses legacy sync mode. // The root API does not trigger this particular failing case. legacyRender(<ControlledInput />, container); utils.act(() => store.profilerStore.startProfiling()); // Sets a value in a way that React doesn't see, // so that a subsequent "change" event will trigger the event handler. const setUntrackedValue = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value', ).set; const target = inputRef.current; setUntrackedValue.call(target, 'bar'); target.dispatchEvent(new Event('input', {bubbles: true, cancelable: true})); expect(target.value).toBe('bar'); utils.act(() => store.profilerStore.stopProfiling()); // Only one commit should have been recorded (in response to the "change" event). const root = store.roots[0]; const data = store.profilerStore.getDataForRoot(root); expect(data.commitData).toHaveLength(1); expect(data.operations).toHaveLength(1); }); // @reactVersion >= 16.9 it('should filter empty commits alt', () => { let commitCount = 0; const inputRef = React.createRef(); const Example = () => { const [, setTouched] = React.useState(false); const handleBlur = () => { setTouched(true); }; require('scheduler').unstable_advanceTime(1); React.useLayoutEffect(() => { commitCount++; }); return <input ref={inputRef} onBlur={handleBlur} />; }; const container = document.createElement('div'); // This element has to be in the <body> for the event system to work. document.body.appendChild(container); // It's important that this test uses legacy sync mode. // The root API does not trigger this particular failing case. legacyRender(<Example />, container); expect(commitCount).toBe(1); commitCount = 0; utils.act(() => store.profilerStore.startProfiling()); // Focus and blur. const target = inputRef.current; target.focus(); target.blur(); target.focus(); target.blur(); expect(commitCount).toBe(1); utils.act(() => store.profilerStore.stopProfiling()); // Only one commit should have been recorded (in response to the "change" event). const root = store.roots[0]; const data = store.profilerStore.getDataForRoot(root); expect(data.commitData).toHaveLength(1); expect(data.operations).toHaveLength(1); }); // @reactVersion >= 16.9 it('should throw if component filters are modified while profiling', () => { utils.act(() => store.profilerStore.startProfiling()); expect(() => { utils.act(() => { const { ElementTypeHostComponent, } = require('react-devtools-shared/src/frontend/types'); store.componentFilters = [ utils.createElementTypeFilter(ElementTypeHostComponent), ]; }); }).toThrow('Cannot modify filter preferences while profiling'); }); // @reactVersion >= 16.9 it('should not throw if state contains a property hasOwnProperty ', () => { let setStateCallback; const ControlledInput = () => { const [state, setState] = React.useState({hasOwnProperty: true}); setStateCallback = setState; return state.hasOwnProperty; }; const container = document.createElement('div'); // This element has to be in the <body> for the event system to work. document.body.appendChild(container); // It's important that this test uses legacy sync mode. // The root API does not trigger this particular failing case. legacyRender(<ControlledInput />, container); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => setStateCallback({ hasOwnProperty: false, }), ); utils.act(() => store.profilerStore.stopProfiling()); // Only one commit should have been recorded (in response to the "change" event). const root = store.roots[0]; const data = store.profilerStore.getDataForRoot(root); expect(data.commitData).toHaveLength(1); expect(data.operations).toHaveLength(1); }); // @reactVersion >= 18.0 it('should not throw while initializing context values for Fibers within a not-yet-mounted subtree', () => { const promise = new Promise(resolve => {}); const SuspendingView = () => { throw promise; }; const App = () => { return ( <React.Suspense fallback="Fallback"> <SuspendingView /> </React.Suspense> ); }; const container = document.createElement('div'); utils.act(() => legacyRender(<App />, container)); utils.act(() => store.profilerStore.startProfiling()); }); });
30.924603
110
0.651044
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 KeyValue from './KeyValue'; import Store from '../../store'; import sharedStyles from './InspectedElementSharedStyles.css'; import styles from './InspectedElementStyleXPlugin.css'; import {enableStyleXFeatures} from 'react-devtools-feature-flags'; import type {InspectedElement} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {Element} from 'react-devtools-shared/src/frontend/types'; type Props = { bridge: FrontendBridge, element: Element, inspectedElement: InspectedElement, store: Store, }; export default function InspectedElementStyleXPlugin({ bridge, element, inspectedElement, store, }: Props): React.Node { if (!enableStyleXFeatures) { return null; } const styleXPlugin = inspectedElement.plugins.stylex; if (styleXPlugin == null) { return null; } const {resolvedStyles, sources} = styleXPlugin; return ( <div className={sharedStyles.InspectedElementTree}> <div className={sharedStyles.HeaderRow}> <div className={sharedStyles.Header}>stylex</div> </div> {sources.map(source => ( <div key={source} className={styles.Source}> {source} </div> ))} {Object.entries(resolvedStyles).map(([name, value]) => ( <KeyValue key={name} alphaSort={true} bridge={bridge} canDeletePaths={false} canEditValues={false} canRenamePaths={false} depth={1} element={element} hidden={false} inspectedElement={inspectedElement} name={name} path={[name]} pathRoot="stylex" store={store} value={value} /> ))} </div> ); }
25.246753
79
0.643564
PenTestScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-client/src/ReactFlightClientConfigBrowser'; export * from 'react-server-dom-esm/src/ReactFlightClientConfigBundlerESM'; export * from 'react-server-dom-esm/src/ReactFlightClientConfigTargetESMBrowser'; export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export const usedWithSSR = false;
34.733333
81
0.773832
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 */ /** * Make sure essential globals are available and are patched correctly. Please don't remove this * line. Bundles created by react-packager `require` it before executing any application code. This * ensures it exists in the dependency graph and can be `require`d. * TODO: require this in packager, not in React #10932517 */ // Module provided by RN: import 'react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore'; import ResponderEventPlugin from './legacy-events/ResponderEventPlugin'; import { injectEventPluginOrder, injectEventPluginsByName, } from './legacy-events/EventPluginRegistry'; import ReactNativeBridgeEventPlugin from './ReactNativeBridgeEventPlugin'; import ReactNativeEventPluginOrder from './ReactNativeEventPluginOrder'; /** * Inject module for resolving DOM hierarchy and plugin ordering. */ injectEventPluginOrder(ReactNativeEventPluginOrder); /** * Some important event plugins included by default (without having to require * them). */ injectEventPluginsByName({ ResponderEventPlugin: ResponderEventPlugin, ReactNativeBridgeEventPlugin: ReactNativeBridgeEventPlugin, });
31.634146
99
0.783844
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/ReactFlightDOMClientBrowser';
22.272727
66
0.705882
Python-Penetration-Testing-for-Developers
'use strict'; throw new Error( 'The React Server Writer cannot be used outside a react-server environment. ' + 'You must configure Node.js using the `--conditions react-server` flag.' );
26.857143
81
0.716495
null
'use strict'; /* eslint-disable no-for-of-loops/no-for-of-loops */ const fs = require('fs'); const semver = require('semver'); const {stablePackages} = require('../../ReactVersions'); function main() { if (!fs.existsSync('./build/oss-stable-semver')) { throw new Error('No build artifacts found'); } const packages = new Map(); for (const packageName in stablePackages) { if (!fs.existsSync(`build/oss-stable-semver/${packageName}/package.json`)) { throw new Error(`${packageName}`); } else { const info = JSON.parse( fs.readFileSync(`build/oss-stable-semver/${packageName}/package.json`) ); packages.set(info.name, info); } } for (const [packageName, info] of packages) { if (info.dependencies) { for (const [depName, depRange] of Object.entries(info.dependencies)) { if (packages.has(depName)) { const releaseVersion = packages.get(depName).version; checkDependency(packageName, depName, releaseVersion, depRange); } } } if (info.peerDependencies) { for (const [depName, depRange] of Object.entries(info.peerDependencies)) { if (packages.has(depName)) { const releaseVersion = packages.get(depName).version; checkDependency(packageName, depName, releaseVersion, depRange); } } } } } function checkDependency(packageName, depName, version, range) { if (!semver.satisfies(version, range)) { throw new Error( `${packageName} has an invalid dependency on ${depName}: ${range}` + '\n\n' + 'Actual version is: ' + version ); } } main();
26.65
80
0.62304
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
Ethical-Hacking-Scripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import { Fragment, Suspense, unstable_SuspenseList as SuspenseList, useState, } from 'react'; function SuspenseTree(): React.Node { return ( <Fragment> <h1>Suspense</h1> <h4>Primary to Fallback Cycle</h4> <PrimaryFallbackTest initialSuspend={false} /> <h4>Fallback to Primary Cycle</h4> <PrimaryFallbackTest initialSuspend={true} /> <NestedSuspenseTest /> <SuspenseListTest /> <EmptySuspense /> </Fragment> ); } function EmptySuspense() { return <Suspense />; } // $FlowFixMe[missing-local-annot] function PrimaryFallbackTest({initialSuspend}) { const [suspend, setSuspend] = useState(initialSuspend); const fallbackStep = useTestSequence('fallback', Fallback1, Fallback2); const primaryStep = useTestSequence('primary', Primary1, Primary2); return ( <Fragment> <label> <input checked={suspend} onChange={e => setSuspend(e.target.checked)} type="checkbox" /> Suspend </label> <br /> <Suspense fallback={fallbackStep}> {suspend ? <Never /> : primaryStep} </Suspense> </Fragment> ); } function useTestSequence(label: string, T1: any => any, T2: any => any) { const [step, setStep] = useState(0); const next: $FlowFixMe = ( <button onClick={() => setStep(s => (s + 1) % allSteps.length)}> next {label} content </button> ); const allSteps: $FlowFixMe = [ <Fragment>{next}</Fragment>, <Fragment> {next} <T1 prop={step}>mount</T1> </Fragment>, <Fragment> {next} <T1 prop={step}>update</T1> </Fragment>, <Fragment> {next} <T2 prop={step}>several</T2> <T1 prop={step}>different</T1>{' '} <T2 prop={step}>children</T2> </Fragment>, <Fragment> {next} <T2 prop={step}>goodbye</T2> </Fragment>, ]; return allSteps[step]; } function NestedSuspenseTest() { return ( <Fragment> <h3>Nested Suspense</h3> <Suspense fallback={<Fallback1>Loading outer</Fallback1>}> <Parent /> </Suspense> </Fragment> ); } function Parent() { return ( <div> <Suspense fallback={<Fallback1>Loading inner 1</Fallback1>}> <Primary1>Hello</Primary1> </Suspense>{' '} <Suspense fallback={<Fallback2>Loading inner 2</Fallback2>}> <Primary2>World</Primary2> </Suspense> <br /> <Suspense fallback={<Fallback1>This will never load</Fallback1>}> <Never /> </Suspense> <br /> <b> <LoadLater /> </b> </div> ); } function SuspenseListTest() { return ( <> <h1>SuspenseList</h1> <SuspenseList revealOrder="forwards" tail="collapsed"> <div> <Suspense fallback={<Fallback1>Loading 1</Fallback1>}> <Primary1>Hello</Primary1> </Suspense> </div> <div> <LoadLater /> </div> <div> <Suspense fallback={<Fallback2>Loading 2</Fallback2>}> <Primary2>World</Primary2> </Suspense> </div> </SuspenseList> </> ); } function LoadLater() { const [loadChild, setLoadChild] = useState(false); return ( <Suspense fallback={ <Fallback1 onClick={() => setLoadChild(true)}>Click to load</Fallback1> }> {loadChild ? ( <Primary1 onClick={() => setLoadChild(false)}> Loaded! Click to suspend again. </Primary1> ) : ( <Never /> )} </Suspense> ); } function Never() { throw new Promise(resolve => {}); } function Fallback1({prop, ...rest}: any) { return <span {...rest} />; } function Fallback2({prop, ...rest}: any) { return <span {...rest} />; } function Primary1({prop, ...rest}: any) { return <span {...rest} />; } function Primary2({prop, ...rest}: any) { return <span {...rest} />; } export default SuspenseTree;
22.072222
79
0.577312
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {useContext, useMemo} from 'react'; import {SettingsContext} from './Settings/SettingsContext'; import {THEME_STYLES} from '../constants'; const useThemeStyles = (): any => { const {theme, displayDensity, browserTheme} = useContext(SettingsContext); const style = useMemo( () => ({ ...THEME_STYLES[displayDensity], ...THEME_STYLES[theme === 'auto' ? browserTheme : theme], }), [theme, browserTheme, displayDensity], ); return style; }; export default useThemeStyles;
23.655172
76
0.673669
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Stack} from '../../utils'; import type {SchedulingEvent} from 'react-devtools-timeline/src/types'; import * as React from 'react'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import ViewSourceContext from '../Components/ViewSourceContext'; import {useContext} from 'react'; import {TimelineContext} from 'react-devtools-timeline/src/TimelineContext'; import { formatTimestamp, getSchedulingEventLabel, } from 'react-devtools-timeline/src/utils/formatting'; import {stackToComponentSources} from 'react-devtools-shared/src/devtools/utils'; import {copy} from 'clipboard-js'; import styles from './SidebarEventInfo.css'; export type Props = {}; type SchedulingEventProps = { eventInfo: SchedulingEvent, }; function SchedulingEventInfo({eventInfo}: SchedulingEventProps) { const {viewUrlSourceFunction} = useContext(ViewSourceContext); const {componentName, timestamp} = eventInfo; const componentStack = eventInfo.componentStack || null; const viewSource = (source: ?Stack) => { if (viewUrlSourceFunction != null && source != null) { viewUrlSourceFunction(...source); } }; return ( <> <div className={styles.Toolbar}> {componentName} {getSchedulingEventLabel(eventInfo)} </div> <div className={styles.Content} tabIndex={0}> <ul className={styles.List}> <li className={styles.ListItem}> <label className={styles.Label}>Timestamp</label>:{' '} <span className={styles.Value}>{formatTimestamp(timestamp)}</span> </li> {componentStack && ( <li className={styles.ListItem}> <div className={styles.Row}> <label className={styles.Label}>Rendered by</label> <Button onClick={() => copy(componentStack)} title="Copy component stack to clipboard"> <ButtonIcon type="copy" /> </Button> </div> <ul className={styles.List}> {stackToComponentSources(componentStack).map( ([displayName, source], index) => { return ( <li key={index}> <Button className={ source ? styles.ClickableSource : styles.UnclickableSource } disabled={!source} onClick={() => viewSource(source)}> {displayName} </Button> </li> ); }, )} </ul> </li> )} </ul> </div> </> ); } export default function SidebarEventInfo(_: Props): React.Node { const {selectedEvent} = useContext(TimelineContext); // (TODO) Refactor in next PR so this supports multiple types of events if (selectedEvent && selectedEvent.schedulingEvent) { return <SchedulingEventInfo eventInfo={selectedEvent.schedulingEvent} />; } return null; }
31.883495
81
0.571471
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 Suspense; let getCacheForType; let caches; let seededCache; let waitForAll; describe('ReactSuspenseFallback', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); Suspense = React.Suspense; getCacheForType = React.unstable_getCacheForType; caches = []; seededCache = null; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; }); function createTextCache() { if (seededCache !== null) { // Trick to seed a cache before it exists. // TODO: Need a built-in API to seed data before the 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 <span prop={text} />; } function AsyncText({text, showVersion}) { const version = readText(text); const fullText = showVersion ? `${text} [v${version}]` : text; Scheduler.log(fullText); return <span prop={fullText} />; } // @gate enableLegacyCache it('suspends and shows fallback', async () => { ReactNoop.render( <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" ms={100} /> </Suspense>, ); await waitForAll(['Suspend! [A]', 'Loading...']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />); }); // @gate enableLegacyCache it('suspends and shows null fallback', async () => { ReactNoop.render( <Suspense fallback={null}> <AsyncText text="A" ms={100} /> </Suspense>, ); await waitForAll([ 'Suspend! [A]', // null ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('suspends and shows undefined fallback', async () => { ReactNoop.render( <Suspense> <AsyncText text="A" ms={100} /> </Suspense>, ); await waitForAll([ 'Suspend! [A]', // null ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('suspends and shows inner fallback', async () => { ReactNoop.render( <Suspense fallback={<Text text="Should not show..." />}> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="A" ms={100} /> </Suspense> </Suspense>, ); await waitForAll(['Suspend! [A]', 'Loading...']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Loading..." />); }); // @gate enableLegacyCache it('suspends and shows inner undefined fallback', async () => { ReactNoop.render( <Suspense fallback={<Text text="Should not show..." />}> <Suspense> <AsyncText text="A" ms={100} /> </Suspense> </Suspense>, ); await waitForAll([ 'Suspend! [A]', // null ]); expect(ReactNoop).toMatchRenderedOutput(null); }); // @gate enableLegacyCache it('suspends and shows inner null fallback', async () => { ReactNoop.render( <Suspense fallback={<Text text="Should not show..." />}> <Suspense fallback={null}> <AsyncText text="A" ms={100} /> </Suspense> </Suspense>, ); await waitForAll([ 'Suspend! [A]', // null ]); expect(ReactNoop).toMatchRenderedOutput(null); }); });
24.736607
79
0.560548
owtf
/** @license React v15.7.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'); var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook'); // 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; } 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 stack = ''; if (currentlyValidatingElement) { stack += ReactComponentTreeHook.getCurrentStackAddendum(currentlyValidatingElement) } 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 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 = require('react/lib/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 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; } // 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 = require('react/lib/ReactCurrentOwner'); 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 = ReactCurrentOwner$1.current.getName(); 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 " + element._owner.getName() + "."; } 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; })(); }
30.519031
397
0.647479
owtf
import Header from './Header'; import Fixtures from './fixtures'; import '../style.css'; const React = window.React; class App extends React.Component { render() { return ( <div> <Header /> <Fixtures /> </div> ); } } export default App;
13.789474
35
0.571429
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = require("react"); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const A = /*#__PURE__*/(0, _react.createContext)(1); const B = /*#__PURE__*/(0, _react.createContext)(2); function Component() { const a = (0, _react.useContext)(A); const b = (0, _react.useContext)(B); // prettier-ignore const c = (0, _react.useContext)(A), d = (0, _react.useContext)(B); // eslint-disable-line one-var return a + b + c + d; } //# sourceMappingURL=ComponentWithMultipleHooksPerLine.js.map?foo=bar&param=some_value
25.433333
86
0.655303
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 {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type Store from 'react-devtools-shared/src/devtools/store'; describe('editing interface', () => { let PropTypes; let React; let bridge: FrontendBridge; let legacyRender; let store: Store; let utils; const flushPendingUpdates = () => { utils.act(() => jest.runOnlyPendingTimers()); }; beforeEach(() => { utils = require('./utils'); legacyRender = utils.legacyRender; bridge = global.bridge; store = global.store; store.collapseNodesByDefault = false; store.componentFilters = []; PropTypes = require('prop-types'); React = require('react'); }); describe('props', () => { let committedClassProps; let committedFunctionProps; let inputRef; let classID; let functionID; let hostComponentID; async function mountTestApp() { class ClassComponent extends React.Component { componentDidMount() { committedClassProps = this.props; } componentDidUpdate() { committedClassProps = this.props; } render() { return null; } } function FunctionComponent(props) { React.useLayoutEffect(() => { committedFunctionProps = props; }); return null; } inputRef = React.createRef(null); const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <> <ClassComponent array={[1, 2, 3]} object={{nested: 'initial'}} shallow="initial" /> , <FunctionComponent array={[1, 2, 3]} object={{nested: 'initial'}} shallow="initial" /> , <input ref={inputRef} onChange={jest.fn()} value="initial" /> </>, container, ), ); classID = ((store.getElementIDAtIndex(0): any): number); functionID = ((store.getElementIDAtIndex(1): any): number); hostComponentID = ((store.getElementIDAtIndex(2): any): number); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }); expect(inputRef.current.value).toBe('initial'); } // @reactVersion >= 16.9 it('should have editable values', async () => { await mountTestApp(); function overrideProps(id, path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideValueAtPath', { id, path, rendererID, type: 'props', value, }); flushPendingUpdates(); } overrideProps(classID, ['shallow'], 'updated'); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'updated', }); overrideProps(classID, ['object', 'nested'], 'updated'); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'updated', }, shallow: 'updated', }); overrideProps(classID, ['array', 1], 'updated'); expect(committedClassProps).toStrictEqual({ array: [1, 'updated', 3], object: { nested: 'updated', }, shallow: 'updated', }); overrideProps(functionID, ['shallow'], 'updated'); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'updated', }); overrideProps(functionID, ['object', 'nested'], 'updated'); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'updated', }, shallow: 'updated', }); overrideProps(functionID, ['array', 1], 'updated'); expect(committedFunctionProps).toStrictEqual({ array: [1, 'updated', 3], object: { nested: 'updated', }, shallow: 'updated', }); }); // @reactVersion >= 16.9 // Tests the combination of older frontend (DevTools UI) with newer backend (embedded within a renderer). it('should still support overriding prop values with legacy backend methods', async () => { await mountTestApp(); function overrideProps(id, path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideProps', { id, path, rendererID, value, }); flushPendingUpdates(); } overrideProps(classID, ['object', 'nested'], 'updated'); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'updated', }, shallow: 'initial', }); overrideProps(functionID, ['shallow'], 'updated'); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'updated', }); }); // @reactVersion >= 17.0 it('should have editable paths', async () => { await mountTestApp(); function renamePath(id, oldPath, newPath) { const rendererID = utils.getRendererID(); bridge.send('renamePath', { id, oldPath, newPath, rendererID, type: 'props', }); flushPendingUpdates(); } renamePath(classID, ['shallow'], ['after']); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, after: 'initial', }); renamePath(classID, ['object', 'nested'], ['object', 'after']); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { after: 'initial', }, after: 'initial', }); renamePath(functionID, ['shallow'], ['after']); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, after: 'initial', }); renamePath(functionID, ['object', 'nested'], ['object', 'after']); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { after: 'initial', }, after: 'initial', }); }); // @reactVersion >= 16.9 it('should enable adding new object properties and array values', async () => { await mountTestApp(); function overrideProps(id, path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideValueAtPath', { id, path, rendererID, type: 'props', value, }); flushPendingUpdates(); } overrideProps(classID, ['new'], 'value'); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', new: 'value', }); overrideProps(classID, ['object', 'new'], 'value'); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); overrideProps(classID, ['array', 3], 'new value'); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3, 'new value'], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); overrideProps(functionID, ['new'], 'value'); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', new: 'value', }); overrideProps(functionID, ['object', 'new'], 'value'); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); overrideProps(functionID, ['array', 3], 'new value'); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3, 'new value'], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); }); // @reactVersion >= 17.0 it('should have deletable keys', async () => { await mountTestApp(); function deletePath(id, path) { const rendererID = utils.getRendererID(); bridge.send('deletePath', { id, path, rendererID, type: 'props', }); flushPendingUpdates(); } deletePath(classID, ['shallow']); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, }); deletePath(classID, ['object', 'nested']); expect(committedClassProps).toStrictEqual({ array: [1, 2, 3], object: {}, }); deletePath(classID, ['array', 1]); expect(committedClassProps).toStrictEqual({ array: [1, 3], object: {}, }); deletePath(functionID, ['shallow']); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, }); deletePath(functionID, ['object', 'nested']); expect(committedFunctionProps).toStrictEqual({ array: [1, 2, 3], object: {}, }); deletePath(functionID, ['array', 1]); expect(committedFunctionProps).toStrictEqual({ array: [1, 3], object: {}, }); }); // @reactVersion >= 16.9 it('should support editing host component values', async () => { await mountTestApp(); function overrideProps(id, path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideValueAtPath', { id, path, rendererID, type: 'props', value, }); flushPendingUpdates(); } overrideProps(hostComponentID, ['value'], 'updated'); expect(inputRef.current.value).toBe('updated'); }); }); describe('state', () => { let committedState; let id; async function mountTestApp() { class ClassComponent extends React.Component { state = { array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }; componentDidMount() { committedState = this.state; } componentDidUpdate() { committedState = this.state; } render() { return null; } } const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <ClassComponent object={{nested: 'initial'}} shallow="initial" />, container, ), ); id = ((store.getElementIDAtIndex(0): any): number); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }); } // @reactVersion >= 16.9 it('should have editable values', async () => { await mountTestApp(); function overrideState(path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideValueAtPath', { id, path, rendererID, type: 'state', value, }); flushPendingUpdates(); } overrideState(['shallow'], 'updated'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: {nested: 'initial'}, shallow: 'updated', }); overrideState(['object', 'nested'], 'updated'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: {nested: 'updated'}, shallow: 'updated', }); overrideState(['array', 1], 'updated'); expect(committedState).toStrictEqual({ array: [1, 'updated', 3], object: {nested: 'updated'}, shallow: 'updated', }); }); // @reactVersion >= 16.9 // Tests the combination of older frontend (DevTools UI) with newer backend (embedded within a renderer). it('should still support overriding state values with legacy backend methods', async () => { await mountTestApp(); function overrideState(path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideState', { id, path, rendererID, value, }); flushPendingUpdates(); } overrideState(['array', 1], 'updated'); expect(committedState).toStrictEqual({ array: [1, 'updated', 3], object: {nested: 'initial'}, shallow: 'initial', }); }); // @reactVersion >= 16.9 it('should have editable paths', async () => { await mountTestApp(); function renamePath(oldPath, newPath) { const rendererID = utils.getRendererID(); bridge.send('renamePath', { id, oldPath, newPath, rendererID, type: 'state', }); flushPendingUpdates(); } renamePath(['shallow'], ['after']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, after: 'initial', }); renamePath(['object', 'nested'], ['object', 'after']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { after: 'initial', }, after: 'initial', }); }); // @reactVersion >= 16.9 it('should enable adding new object properties and array values', async () => { await mountTestApp(); function overrideState(path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideValueAtPath', { id, path, rendererID, type: 'state', value, }); flushPendingUpdates(); } overrideState(['new'], 'value'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', new: 'value', }); overrideState(['object', 'new'], 'value'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); overrideState(['array', 3], 'new value'); expect(committedState).toStrictEqual({ array: [1, 2, 3, 'new value'], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); }); // @reactVersion >= 16.9 it('should have deletable keys', async () => { await mountTestApp(); function deletePath(path) { const rendererID = utils.getRendererID(); bridge.send('deletePath', { id, path, rendererID, type: 'state', }); flushPendingUpdates(); } deletePath(['shallow']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, }); deletePath(['object', 'nested']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: {}, }); deletePath(['array', 1]); expect(committedState).toStrictEqual({ array: [1, 3], object: {}, }); }); }); describe('hooks', () => { let committedState; let hookID; let id; async function mountTestApp() { function FunctionComponent() { const [state] = React.useState({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }); React.useLayoutEffect(() => { committedState = state; }); return null; } const container = document.createElement('div'); await utils.actAsync(() => legacyRender(<FunctionComponent />, container), ); hookID = 0; // index id = ((store.getElementIDAtIndex(0): any): number); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }); } // @reactVersion >= 16.9 it('should have editable values', async () => { await mountTestApp(); function overrideHookState(path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideValueAtPath', { hookID, id, path, rendererID, type: 'hooks', value, }); flushPendingUpdates(); } overrideHookState(['shallow'], 'updated'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'updated', }); overrideHookState(['object', 'nested'], 'updated'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'updated', }, shallow: 'updated', }); overrideHookState(['array', 1], 'updated'); expect(committedState).toStrictEqual({ array: [1, 'updated', 3], object: { nested: 'updated', }, shallow: 'updated', }); }); // @reactVersion >= 16.9 // Tests the combination of older frontend (DevTools UI) with newer backend (embedded within a renderer). it('should still support overriding hook values with legacy backend methods', async () => { await mountTestApp(); function overrideHookState(path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideHookState', { hookID, id, path, rendererID, value, }); flushPendingUpdates(); } overrideHookState(['shallow'], 'updated'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'updated', }); }); // @reactVersion >= 17.0 it('should have editable paths', async () => { await mountTestApp(); function renamePath(oldPath, newPath) { const rendererID = utils.getRendererID(); bridge.send('renamePath', { id, hookID, oldPath, newPath, rendererID, type: 'hooks', }); flushPendingUpdates(); } renamePath(['shallow'], ['after']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, after: 'initial', }); renamePath(['object', 'nested'], ['object', 'after']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { after: 'initial', }, after: 'initial', }); }); // @reactVersion >= 16.9 it('should enable adding new object properties and array values', async () => { await mountTestApp(); function overrideHookState(path, value) { const rendererID = utils.getRendererID(); bridge.send('overrideValueAtPath', { hookID, id, path, rendererID, type: 'hooks', value, }); flushPendingUpdates(); } overrideHookState(['new'], 'value'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', new: 'value', }); overrideHookState(['object', 'new'], 'value'); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); overrideHookState(['array', 3], 'new value'); expect(committedState).toStrictEqual({ array: [1, 2, 3, 'new value'], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); }); // @reactVersion >= 17.0 it('should have deletable keys', async () => { await mountTestApp(); function deletePath(path) { const rendererID = utils.getRendererID(); bridge.send('deletePath', { hookID, id, path, rendererID, type: 'hooks', }); flushPendingUpdates(); } deletePath(['shallow']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, }); deletePath(['object', 'nested']); expect(committedState).toStrictEqual({ array: [1, 2, 3], object: {}, }); deletePath(['array', 1]); expect(committedState).toStrictEqual({ array: [1, 3], object: {}, }); }); }); describe('context', () => { let committedContext; let id; async function mountTestApp() { class LegacyContextProvider extends React.Component<any> { static childContextTypes = { array: PropTypes.array, object: PropTypes.object, shallow: PropTypes.string, }; getChildContext() { return { array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }; } render() { return this.props.children; } } class ClassComponent extends React.Component<any> { static contextTypes = { array: PropTypes.array, object: PropTypes.object, shallow: PropTypes.string, }; componentDidMount() { committedContext = this.context; } componentDidUpdate() { committedContext = this.context; } render() { return null; } } const container = document.createElement('div'); await utils.actAsync(() => legacyRender( <LegacyContextProvider> <ClassComponent /> </LegacyContextProvider>, container, ), ); // This test only covers Class components. // Function components using legacy context are not editable. id = ((store.getElementIDAtIndex(1): any): number); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', }); } // @reactVersion >= 16.9 it('should have editable values', async () => { await mountTestApp(); function overrideContext(path, value) { const rendererID = utils.getRendererID(); // To simplify hydration and display of primitive context values (e.g. number, string) // the inspectElement() method wraps context in a {value: ...} object. path = ['value', ...path]; bridge.send('overrideValueAtPath', { id, path, rendererID, type: 'context', value, }); flushPendingUpdates(); } overrideContext(['shallow'], 'updated'); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'updated', }); overrideContext(['object', 'nested'], 'updated'); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'updated', }, shallow: 'updated', }); overrideContext(['array', 1], 'updated'); expect(committedContext).toStrictEqual({ array: [1, 'updated', 3], object: { nested: 'updated', }, shallow: 'updated', }); }); // @reactVersion >= 16.9 // Tests the combination of older frontend (DevTools UI) with newer backend (embedded within a renderer). it('should still support overriding context values with legacy backend methods', async () => { await mountTestApp(); function overrideContext(path, value) { const rendererID = utils.getRendererID(); // To simplify hydration and display of primitive context values (e.g. number, string) // the inspectElement() method wraps context in a {value: ...} object. path = ['value', ...path]; bridge.send('overrideContext', { id, path, rendererID, value, }); flushPendingUpdates(); } overrideContext(['object', 'nested'], 'updated'); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'updated', }, shallow: 'initial', }); }); // @reactVersion >= 16.9 it('should have editable paths', async () => { await mountTestApp(); function renamePath(oldPath, newPath) { const rendererID = utils.getRendererID(); // To simplify hydration and display of primitive context values (e.g. number, string) // the inspectElement() method wraps context in a {value: ...} object. oldPath = ['value', ...oldPath]; newPath = ['value', ...newPath]; bridge.send('renamePath', { id, oldPath, newPath, rendererID, type: 'context', }); flushPendingUpdates(); } renamePath(['shallow'], ['after']); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, after: 'initial', }); renamePath(['object', 'nested'], ['object', 'after']); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { after: 'initial', }, after: 'initial', }); }); // @reactVersion >= 16.9 it('should enable adding new object properties and array values', async () => { await mountTestApp(); function overrideContext(path, value) { const rendererID = utils.getRendererID(); // To simplify hydration and display of primitive context values (e.g. number, string) // the inspectElement() method wraps context in a {value: ...} object. path = ['value', ...path]; bridge.send('overrideValueAtPath', { id, path, rendererID, type: 'context', value, }); flushPendingUpdates(); } overrideContext(['new'], 'value'); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, shallow: 'initial', new: 'value', }); overrideContext(['object', 'new'], 'value'); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); overrideContext(['array', 3], 'new value'); expect(committedContext).toStrictEqual({ array: [1, 2, 3, 'new value'], object: { nested: 'initial', new: 'value', }, shallow: 'initial', new: 'value', }); }); // @reactVersion >= 16.9 it('should have deletable keys', async () => { await mountTestApp(); function deletePath(path) { const rendererID = utils.getRendererID(); // To simplify hydration and display of primitive context values (e.g. number, string) // the inspectElement() method wraps context in a {value: ...} object. path = ['value', ...path]; bridge.send('deletePath', { id, path, rendererID, type: 'context', }); flushPendingUpdates(); } deletePath(['shallow']); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: { nested: 'initial', }, }); deletePath(['object', 'nested']); expect(committedContext).toStrictEqual({ array: [1, 2, 3], object: {}, }); deletePath(['array', 1]); expect(committedContext).toStrictEqual({ array: [1, 3], object: {}, }); }); }); });
24.479759
109
0.511105