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
null
export const hashRE = /#.*$/ export const extRE = /\.(md|html)$/ export const endingSlashRE = /\/$/ export const outboundRE = /^[a-z]+:/i export function normalize (path) { return decodeURI(path) .replace(hashRE, '') .replace(extRE, '') } export function getHash (path) { const match = path.match(hashRE) if (match) { return match[0] } } export function isExternal (path) { return outboundRE.test(path) } export function isMailto (path) { return /^mailto:/.test(path) } export function isTel (path) { return /^tel:/.test(path) } export function ensureExt (path) { if (isExternal(path)) { return path } const hashMatch = path.match(hashRE) const hash = hashMatch ? hashMatch[0] : '' const normalized = normalize(path) if (endingSlashRE.test(normalized)) { return path } return normalized + '.html' + hash } export function isActive (route, path) { const routeHash = decodeURIComponent(route.hash) const linkHash = getHash(path) if (linkHash && routeHash !== linkHash) { return false } const routePath = normalize(route.path) const pagePath = normalize(path) return routePath === pagePath } export function resolvePage (pages, rawPath, base) { if (isExternal(rawPath)) { return { type: 'external', path: rawPath } } if (base) { rawPath = resolvePath(rawPath, base) } const path = normalize(rawPath) for (let i = 0; i < pages.length; i++) { if (normalize(pages[i].regularPath) === path) { return Object.assign({}, pages[i], { type: 'page', path: ensureExt(pages[i].path) }) } } console.error(`[vuepress] No matching page found for sidebar item "${rawPath}"`) return {} } function resolvePath (relative, base, append) { const firstChar = relative.charAt(0) if (firstChar === '/') { return relative } if (firstChar === '?' || firstChar === '#') { return base + relative } const stack = base.split('/') // remove trailing segment if: // - not appending // - appending to trailing slash (last segment is empty) if (!append || !stack[stack.length - 1]) { stack.pop() } // resolve relative path const segments = relative.replace(/^\//, '').split('/') for (let i = 0; i < segments.length; i++) { const segment = segments[i] if (segment === '..') { stack.pop() } else if (segment !== '.') { stack.push(segment) } } // ensure leading slash if (stack[0] !== '') { stack.unshift('') } return stack.join('/') } /** * @param { Page } page * @param { string } regularPath * @param { SiteData } site * @param { string } localePath * @returns { SidebarGroup } */ export function resolveSidebarItems (page, regularPath, site, localePath) { const { pages, themeConfig } = site const localeConfig = localePath && themeConfig.locales ? themeConfig.locales[localePath] || themeConfig : themeConfig const pageSidebarConfig = page.frontmatter.sidebar || localeConfig.sidebar || themeConfig.sidebar if (pageSidebarConfig === 'auto') { return resolveHeaders(page) } const sidebarConfig = localeConfig.sidebar || themeConfig.sidebar if (!sidebarConfig) { return [] } else { const { base, config } = resolveMatchingConfig(regularPath, sidebarConfig) return config ? config.map(item => resolveItem(item, pages, base)) : [] } } /** * @param { Page } page * @returns { SidebarGroup } */ function resolveHeaders (page) { const headers = groupHeaders(page.headers || []) return [{ type: 'group', collapsable: false, title: page.title, path: null, children: headers.map(h => ({ type: 'auto', title: h.title, basePath: page.path, path: page.path + '#' + h.slug, children: h.children || [] })) }] } export function groupHeaders (headers) { // group h3s under h2 headers = headers.map(h => Object.assign({}, h)) let lastH2 headers.forEach(h => { if (h.level === 2) { lastH2 = h } else if (lastH2) { (lastH2.children || (lastH2.children = [])).push(h) } }) return headers.filter(h => h.level === 2) } export function resolveNavLinkItem (linkItem) { return Object.assign(linkItem, { type: linkItem.items && linkItem.items.length ? 'links' : 'link' }) } /** * @param { Route } route * @param { Array<string|string[]> | Array<SidebarGroup> | [link: string]: SidebarConfig } config * @returns { base: string, config: SidebarConfig } */ export function resolveMatchingConfig (regularPath, config) { if (Array.isArray(config)) { return { base: '/', config: config } } for (const base in config) { if (ensureEndingSlash(regularPath).indexOf(encodeURI(base)) === 0) { return { base, config: config[base] } } } return {} } function ensureEndingSlash (path) { return /(\.html|\/)$/.test(path) ? path : path + '/' } function resolveItem (item, pages, base, groupDepth = 1) { if (typeof item === 'string') { return resolvePage(pages, item, base) } else if (Array.isArray(item)) { return Object.assign(resolvePage(pages, item[0], base), { title: item[1] }) } else { if (groupDepth > 3) { console.error( '[vuepress] detected a too deep nested sidebar group.' ) } const children = item.children || [] if (children.length === 0 && item.path) { return Object.assign(resolvePage(pages, item.path, base), { title: item.title }) } return { type: 'group', path: item.path, title: item.title, sidebarDepth: item.sidebarDepth, children: children.map(child => resolveItem(child, pages, base, groupDepth + 1)), collapsable: item.collapsable !== false } } }
22.674797
99
0.611884
cybersecurity-penetration-testing
'use strict'; var s; if (process.env.NODE_ENV === 'production') { s = require('./cjs/react-dom-server.node.production.min.js'); } else { s = require('./cjs/react-dom-server.node.development.js'); } exports.version = s.version; exports.prerenderToNodeStream = s.prerenderToNodeStream;
23.25
63
0.703448
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. */ 'use strict'; const semver = require('semver'); let shouldPass; let isFocused; describe('transform-react-version-pragma', () => { const originalTest = test; // eslint-disable-next-line no-unused-vars const _test_react_version = (range, testName, cb) => { originalTest(testName, (...args) => { shouldPass = !!semver.satisfies('18.0.0', range); return cb(...args); }); }; // eslint-disable-next-line no-unused-vars const _test_react_version_focus = (range, testName, cb) => { originalTest(testName, (...args) => { shouldPass = !!semver.satisfies('18.0.0', range); isFocused = true; return cb(...args); }); }; // eslint-disable-next-line no-unused-vars const _test_ignore_for_react_version = (testName, cb) => { originalTest(testName, (...args) => { shouldPass = false; return cb(...args); }); }; beforeEach(() => { shouldPass = null; isFocused = false; }); // @reactVersion >= 17.9 test('reactVersion flag is on >=', () => { expect(shouldPass).toBe(true); }); // @reactVersion >= 18.1 test('reactVersion flag is off >=', () => { expect(shouldPass).toBe(false); }); // @reactVersion <= 18.1 test('reactVersion flag is on <=', () => { expect(shouldPass).toBe(true); }); // @reactVersion <= 17.9 test('reactVersion flag is off <=', () => { expect(shouldPass).toBe(false); }); // @reactVersion > 17.9 test('reactVersion flag is on >', () => { expect(shouldPass).toBe(true); }); // @reactVersion > 18.1 test('reactVersion flag is off >', () => { expect(shouldPass).toBe(false); }); // @reactVersion < 18.1 test('reactVersion flag is on <', () => { expect(shouldPass).toBe(true); }); // @reactVersion < 17.0.0 test('reactVersion flag is off <', () => { expect(shouldPass).toBe(false); }); // @reactVersion = 18.0 test('reactVersion flag is on =', () => { expect(shouldPass).toBe(true); }); // @reactVersion = 18.1 test('reactVersion flag is off =', () => { expect(shouldPass).toBe(false); }); /* eslint-disable jest/no-focused-tests */ // @reactVersion >= 18.1 fit('reactVersion fit', () => { expect(shouldPass).toBe(false); expect(isFocused).toBe(true); }); // @reactVersion <= 18.1 test.only('reactVersion test.only', () => { expect(shouldPass).toBe(true); expect(isFocused).toBe(true); }); // @reactVersion <= 18.1 // @reactVersion <= 17.1 test('reactVersion multiple pragmas fail', () => { expect(shouldPass).toBe(false); expect(isFocused).toBe(false); }); // @reactVersion <= 18.1 // @reactVersion >= 17.1 test('reactVersion multiple pragmas pass', () => { expect(shouldPass).toBe(true); expect(isFocused).toBe(false); }); // @reactVersion <= 18.1 // @reactVersion <= 17.1 test.only('reactVersion focused multiple pragmas fail', () => { expect(shouldPass).toBe(false); expect(isFocused).toBe(true); }); // @reactVersion <= 18.1 // @reactVersion >= 17.1 test.only('reactVersion focused multiple pragmas pass', () => { expect(shouldPass).toBe(true); expect(isFocused).toBe(true); }); });
23.565217
66
0.597521
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 isArray from 'shared/isArray'; /** * Accumulates items that must not be null or undefined. * * This is used to conserve memory by avoiding array allocations. * * @return {*|array<*>} An accumulation of items. */ function accumulate<T>( current: ?(T | Array<T>), next: T | Array<T>, ): T | Array<T> { if (next == null) { throw new Error( 'accumulate(...): Accumulated items must not be null or undefined.', ); } if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (isArray(current)) { /* $FlowFixMe[incompatible-return] if `current` is `T` and `T` an array, * `isArray` might refine to the array element type of `T` */ return current.concat(next); } if (isArray(next)) { /* $FlowFixMe[incompatible-return] unsound if `next` is `T` and `T` an array, * `isArray` might refine to the array element type of `T` */ return [current].concat(next); } return [current, next]; } export default accumulate;
24.921569
81
0.644966
PenetrationTestingScripts
module.exports = {};
10
20
0.619048
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type ReactNode = | React$Element<any> | ReactPortal | ReactText | ReactFragment | ReactProvider<any> | ReactConsumer<any>; export type ReactEmpty = null | void | boolean; export type ReactFragment = ReactEmpty | Iterable<React$Node>; export type ReactNodeList = ReactEmpty | React$Node; export type ReactText = string | number; export type ReactProvider<T> = { $$typeof: symbol | number, type: ReactProviderType<T>, key: null | string, ref: null, props: { value: T, children?: ReactNodeList, }, }; export type ReactProviderType<T> = { $$typeof: symbol | number, _context: ReactContext<T>, }; export type ReactConsumer<T> = { $$typeof: symbol | number, type: ReactContext<T>, key: null | string, ref: null, props: { children: (value: T) => ReactNodeList, }, }; export type ReactContext<T> = { $$typeof: symbol | number, Consumer: ReactContext<T>, Provider: ReactProviderType<T>, _currentValue: T, _currentValue2: T, _threadCount: number, // DEV only _currentRenderer?: Object | null, _currentRenderer2?: Object | null, // This value may be added by application code // to improve DEV tooling display names displayName?: string, // only used by ServerContext _defaultValue: T, _globalName: string, }; export type ServerContextJSONValue = | string | boolean | number | null | $ReadOnlyArray<ServerContextJSONValue> | {+[key: string]: ServerContextJSONValue}; export type ReactServerContext<T: any> = ReactContext<T>; export type ReactPortal = { $$typeof: symbol | number, key: null | string, containerInfo: any, children: ReactNodeList, // TODO: figure out the API for cross-renderer implementation. implementation: any, }; export type RefObject = { current: any, }; export type ReactScope = { $$typeof: symbol | number, }; export type ReactScopeQuery = ( type: string, props: {[string]: mixed}, instance: mixed, ) => boolean; export type ReactScopeInstance = { DO_NOT_USE_queryAllNodes(ReactScopeQuery): null | Array<Object>, DO_NOT_USE_queryFirstNode(ReactScopeQuery): null | Object, containsNode(Object): boolean, getChildContextValues: <T>(context: ReactContext<T>) => Array<T>, }; // The subset of a Thenable required by things thrown by Suspense. // This doesn't require a value to be passed to either handler. export interface Wakeable { then(onFulfill: () => mixed, onReject: () => mixed): void | Wakeable; } // The subset of a Promise that React APIs rely on. This resolves a value. // This doesn't require a return value neither from the handler nor the // then function. interface ThenableImpl<T> { then( onFulfill: (value: T) => mixed, onReject: (error: mixed) => mixed, ): void | Wakeable; } interface UntrackedThenable<T> extends ThenableImpl<T> { status?: void; } export interface PendingThenable<T> extends ThenableImpl<T> { status: 'pending'; } export interface FulfilledThenable<T> extends ThenableImpl<T> { status: 'fulfilled'; value: T; } export interface RejectedThenable<T> extends ThenableImpl<T> { status: 'rejected'; reason: mixed; } export type Thenable<T> = | UntrackedThenable<T> | PendingThenable<T> | FulfilledThenable<T> | RejectedThenable<T>; export type OffscreenMode = | 'hidden' | 'unstable-defer-without-hiding' | 'visible' | 'manual'; export type StartTransitionOptions = { name?: string, }; export type Usable<T> = Thenable<T> | ReactContext<T>; export type ReactCustomFormAction = { name?: string, action?: string, encType?: string, method?: string, target?: string, data?: null | FormData, }; // This is an opaque type returned by decodeFormState on the server, but it's // defined in this shared file because the same type is used by React on // the client. export type ReactFormState<S, ReferenceId> = [ S /* actual state value */, string /* key path */, ReferenceId /* Server Reference ID */, number /* number of bound arguments */, ]; export type Awaited<T> = T extends null | void ? T // special case for `null | undefined` when not in `--strictNullChecks` mode : T extends Object // `await` only unwraps object types with a callable then. Non-object types are not unwrapped. ? T extends {then(onfulfilled: infer F): any} // thenable, extracts the first argument to `then()` ? F extends (value: infer V) => any // if the argument to `then` is callable, extracts the argument ? Awaited<V> // recursively unwrap the value : empty // the argument to `then` was not callable. : T // argument was not an object : T; // non-thenable
24.394737
115
0.690091
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. */ export * from './src/ReactFreshRuntime';
25
66
0.712446
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 is from './objectIs'; import hasOwnProperty from './hasOwnProperty'; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA: mixed, objB: mixed): boolean { if (is(objA, objB)) { return true; } if ( typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null ) { return false; } const keysA = Object.keys(objA); const keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (let i = 0; i < keysA.length; i++) { const currentKey = keysA[i]; if ( !hasOwnProperty.call(objB, currentKey) || // $FlowFixMe[incompatible-use] lost refinement of `objB` !is(objA[currentKey], objB[currentKey]) ) { return false; } } return true; } export default shallowEqual;
21.909091
79
0.641779
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ /* eslint-disable no-func-assign */ 'use strict'; import {useInsertionEffect} from 'react'; describe('useEffectEvent', () => { let React; let ReactNoop; let Scheduler; let act; let createContext; let useContext; let useState; let useEffectEvent; let useEffect; let useLayoutEffect; let useMemo; let waitForAll; let assertLog; let waitForThrow; beforeEach(() => { React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; createContext = React.createContext; useContext = React.useContext; useState = React.useState; useEffectEvent = React.experimental_useEffectEvent; useEffect = React.useEffect; useLayoutEffect = React.useLayoutEffect; useMemo = React.useMemo; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; waitForThrow = InternalTestUtils.waitForThrow; }); function Text(props) { Scheduler.log(props.text); return <span prop={props.text} />; } // @gate enableUseEffectEventHook it('memoizes basic case correctly', async () => { class IncrementButton extends React.PureComponent { increment = () => { this.props.onClick(); }; render() { return <Text text="Increment" />; } } function Counter({incrementBy}) { const [count, updateCount] = useState(0); const onClick = useEffectEvent(() => updateCount(c => c + incrementBy)); return ( <> <IncrementButton onClick={() => onClick()} ref={button} /> <Text text={'Count: ' + count} /> </> ); } const button = React.createRef(null); ReactNoop.render(<Counter incrementBy={1} />); await waitForAll(['Increment', 'Count: 0']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 0" /> </>, ); await act(() => button.current.increment()); assertLog(['Increment', 'Count: 1']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 1" /> </>, ); await act(() => button.current.increment()); assertLog([ 'Increment', // Event should use the updated callback function closed over the new value. 'Count: 2', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 2" /> </>, ); // Increase the increment prop amount ReactNoop.render(<Counter incrementBy={10} />); await waitForAll(['Increment', 'Count: 2']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 2" /> </>, ); // Event uses the new prop await act(() => button.current.increment()); assertLog(['Increment', 'Count: 12']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 12" /> </>, ); }); // @gate enableUseEffectEventHook it('can be defined more than once', async () => { class IncrementButton extends React.PureComponent { increment = () => { this.props.onClick(); }; multiply = () => { this.props.onMouseEnter(); }; render() { return <Text text="Increment" />; } } function Counter({incrementBy}) { const [count, updateCount] = useState(0); const onClick = useEffectEvent(() => updateCount(c => c + incrementBy)); const onMouseEnter = useEffectEvent(() => { updateCount(c => c * incrementBy); }); return ( <> <IncrementButton onClick={() => onClick()} onMouseEnter={() => onMouseEnter()} ref={button} /> <Text text={'Count: ' + count} /> </> ); } const button = React.createRef(null); ReactNoop.render(<Counter incrementBy={5} />); await waitForAll(['Increment', 'Count: 0']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 0" /> </>, ); await act(() => button.current.increment()); assertLog(['Increment', 'Count: 5']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 5" /> </>, ); await act(() => button.current.multiply()); assertLog(['Increment', 'Count: 25']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 25" /> </>, ); }); // @gate enableUseEffectEventHook it('does not preserve `this` in event functions', async () => { class GreetButton extends React.PureComponent { greet = () => { this.props.onClick(); }; render() { return <Text text={'Say ' + this.props.hello} />; } } function Greeter({hello}) { const person = { toString() { return 'Jane'; }, greet() { return updateGreeting(this + ' says ' + hello); }, }; const [greeting, updateGreeting] = useState('Seb says ' + hello); const onClick = useEffectEvent(person.greet); return ( <> <GreetButton hello={hello} onClick={() => onClick()} ref={button} /> <Text text={'Greeting: ' + greeting} /> </> ); } const button = React.createRef(null); ReactNoop.render(<Greeter hello={'hej'} />); await waitForAll(['Say hej', 'Greeting: Seb says hej']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Say hej" /> <span prop="Greeting: Seb says hej" /> </>, ); await act(() => button.current.greet()); assertLog(['Say hej', 'Greeting: undefined says hej']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Say hej" /> <span prop="Greeting: undefined says hej" /> </>, ); }); // @gate enableUseEffectEventHook it('throws when called in render', async () => { class IncrementButton extends React.PureComponent { increment = () => { this.props.onClick(); }; render() { // Will throw. this.props.onClick(); return <Text text="Increment" />; } } function Counter({incrementBy}) { const [count, updateCount] = useState(0); const onClick = useEffectEvent(() => updateCount(c => c + incrementBy)); return ( <> <IncrementButton onClick={() => onClick()} /> <Text text={'Count: ' + count} /> </> ); } ReactNoop.render(<Counter incrementBy={1} />); await waitForThrow( "A function wrapped in useEffectEvent can't be called during rendering.", ); assertLog([]); }); // @gate enableUseEffectEventHook it("useLayoutEffect shouldn't re-fire when event handlers change", async () => { class IncrementButton extends React.PureComponent { increment = () => { this.props.onClick(); }; render() { return <Text text="Increment" />; } } function Counter({incrementBy}) { const [count, updateCount] = useState(0); const increment = useEffectEvent(amount => updateCount(c => c + (amount || incrementBy)), ); useLayoutEffect(() => { Scheduler.log('Effect: by ' + incrementBy * 2); increment(incrementBy * 2); }, [incrementBy]); return ( <> <IncrementButton onClick={() => increment()} ref={button} /> <Text text={'Count: ' + count} /> </> ); } const button = React.createRef(null); ReactNoop.render(<Counter incrementBy={1} />); assertLog([]); await waitForAll([ 'Increment', 'Count: 0', 'Effect: by 2', 'Increment', 'Count: 2', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 2" /> </>, ); await act(() => button.current.increment()); assertLog([ 'Increment', // Effect should not re-run because the dependency hasn't changed. 'Count: 3', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 3" /> </>, ); await act(() => button.current.increment()); assertLog([ 'Increment', // Event should use the updated callback function closed over the new value. 'Count: 4', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 4" /> </>, ); // Increase the increment prop amount ReactNoop.render(<Counter incrementBy={10} />); await waitForAll([ 'Increment', 'Count: 4', 'Effect: by 20', 'Increment', 'Count: 24', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 24" /> </>, ); // Event uses the new prop await act(() => button.current.increment()); assertLog(['Increment', 'Count: 34']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 34" /> </>, ); }); // @gate enableUseEffectEventHook it("useEffect shouldn't re-fire when event handlers change", async () => { class IncrementButton extends React.PureComponent { increment = () => { this.props.onClick(); }; render() { return <Text text="Increment" />; } } function Counter({incrementBy}) { const [count, updateCount] = useState(0); const increment = useEffectEvent(amount => updateCount(c => c + (amount || incrementBy)), ); useEffect(() => { Scheduler.log('Effect: by ' + incrementBy * 2); increment(incrementBy * 2); }, [incrementBy]); return ( <> <IncrementButton onClick={() => increment()} ref={button} /> <Text text={'Count: ' + count} /> </> ); } const button = React.createRef(null); ReactNoop.render(<Counter incrementBy={1} />); await waitForAll([ 'Increment', 'Count: 0', 'Effect: by 2', 'Increment', 'Count: 2', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 2" /> </>, ); await act(() => button.current.increment()); assertLog([ 'Increment', // Effect should not re-run because the dependency hasn't changed. 'Count: 3', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 3" /> </>, ); await act(() => button.current.increment()); assertLog([ 'Increment', // Event should use the updated callback function closed over the new value. 'Count: 4', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 4" /> </>, ); // Increase the increment prop amount ReactNoop.render(<Counter incrementBy={10} />); await waitForAll([ 'Increment', 'Count: 4', 'Effect: by 20', 'Increment', 'Count: 24', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 24" /> </>, ); // Event uses the new prop await act(() => button.current.increment()); assertLog(['Increment', 'Count: 34']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 34" /> </>, ); }); // @gate enableUseEffectEventHook it('is stable in a custom hook', async () => { class IncrementButton extends React.PureComponent { increment = () => { this.props.onClick(); }; render() { return <Text text="Increment" />; } } function useCount(incrementBy) { const [count, updateCount] = useState(0); const increment = useEffectEvent(amount => updateCount(c => c + (amount || incrementBy)), ); return [count, increment]; } function Counter({incrementBy}) { const [count, increment] = useCount(incrementBy); useEffect(() => { Scheduler.log('Effect: by ' + incrementBy * 2); increment(incrementBy * 2); }, [incrementBy]); return ( <> <IncrementButton onClick={() => increment()} ref={button} /> <Text text={'Count: ' + count} /> </> ); } const button = React.createRef(null); ReactNoop.render(<Counter incrementBy={1} />); await waitForAll([ 'Increment', 'Count: 0', 'Effect: by 2', 'Increment', 'Count: 2', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 2" /> </>, ); await act(() => button.current.increment()); assertLog([ 'Increment', // Effect should not re-run because the dependency hasn't changed. 'Count: 3', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 3" /> </>, ); await act(() => button.current.increment()); assertLog([ 'Increment', // Event should use the updated callback function closed over the new value. 'Count: 4', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 4" /> </>, ); // Increase the increment prop amount ReactNoop.render(<Counter incrementBy={10} />); await waitForAll([ 'Increment', 'Count: 4', 'Effect: by 20', 'Increment', 'Count: 24', ]); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 24" /> </>, ); // Event uses the new prop await act(() => button.current.increment()); assertLog(['Increment', 'Count: 34']); expect(ReactNoop).toMatchRenderedOutput( <> <span prop="Increment" /> <span prop="Count: 34" /> </>, ); }); // @gate enableUseEffectEventHook it('is mutated before all other effects', async () => { function Counter({value}) { useInsertionEffect(() => { Scheduler.log('Effect value: ' + value); increment(); }, [value]); // This is defined after the insertion effect, but it should // update the event fn _before_ the insertion effect fires. const increment = useEffectEvent(() => { Scheduler.log('Event value: ' + value); }); return <></>; } ReactNoop.render(<Counter value={1} />); await waitForAll(['Effect value: 1', 'Event value: 1']); await act(() => ReactNoop.render(<Counter value={2} />)); assertLog(['Effect value: 2', 'Event value: 2']); }); // @gate enableUseEffectEventHook it("doesn't provide a stable identity", async () => { function Counter({shouldRender, value}) { const onClick = useEffectEvent(() => { Scheduler.log( 'onClick, shouldRender=' + shouldRender + ', value=' + value, ); }); // onClick doesn't have a stable function identity so this effect will fire on every render. // In a real app useEffectEvent functions should *not* be passed as a dependency, this is for // testing purposes only. useEffect(() => { onClick(); }, [onClick]); useEffect(() => { onClick(); }, [shouldRender]); return <></>; } ReactNoop.render(<Counter shouldRender={true} value={0} />); await waitForAll([ 'onClick, shouldRender=true, value=0', 'onClick, shouldRender=true, value=0', ]); ReactNoop.render(<Counter shouldRender={true} value={1} />); await waitForAll(['onClick, shouldRender=true, value=1']); ReactNoop.render(<Counter shouldRender={false} value={2} />); await waitForAll([ 'onClick, shouldRender=false, value=2', 'onClick, shouldRender=false, value=2', ]); }); // @gate enableUseEffectEventHook it('event handlers always see the latest committed value', async () => { let committedEventHandler = null; function App({value}) { const event = useEffectEvent(() => { return 'Value seen by useEffectEvent: ' + value; }); // Set up an effect that registers the event handler with an external // event system (e.g. addEventListener). useEffect( () => { // Log when the effect fires. In the test below, we'll assert that this // only happens during initial render, not during updates. Scheduler.log('Commit new event handler'); committedEventHandler = event; return () => { committedEventHandler = null; }; }, // Note that we've intentionally omitted the event from the dependency // array. But it will still be able to see the latest `value`. This is the // key feature of useEffectEvent that makes it different from a regular closure. [], ); return 'Latest rendered value ' + value; } // Initial render const root = ReactNoop.createRoot(); await act(() => { root.render(<App value={1} />); }); assertLog(['Commit new event handler']); expect(root).toMatchRenderedOutput('Latest rendered value 1'); expect(committedEventHandler()).toBe('Value seen by useEffectEvent: 1'); // Update await act(() => { root.render(<App value={2} />); }); // No new event handler should be committed, because it was omitted from // the dependency array. assertLog([]); // But the event handler should still be able to see the latest value. expect(root).toMatchRenderedOutput('Latest rendered value 2'); expect(committedEventHandler()).toBe('Value seen by useEffectEvent: 2'); }); // @gate enableUseEffectEventHook it('integration: implements docs chat room example', async () => { function createConnection() { let connectedCallback; let timeout; return { connect() { timeout = setTimeout(() => { if (connectedCallback) { connectedCallback(); } }, 100); }, on(event, callback) { if (connectedCallback) { throw Error('Cannot add the handler twice.'); } if (event !== 'connected') { throw Error('Only "connected" event is supported.'); } connectedCallback = callback; }, disconnect() { clearTimeout(timeout); }, }; } function ChatRoom({roomId, theme}) { const onConnected = useEffectEvent(() => { Scheduler.log('Connected! theme: ' + theme); }); useEffect(() => { const connection = createConnection(roomId); connection.on('connected', () => { onConnected(); }); connection.connect(); return () => connection.disconnect(); }, [roomId]); return <Text text={`Welcome to the ${roomId} room!`} />; } await act(() => ReactNoop.render(<ChatRoom roomId="general" theme="light" />), ); await act(() => jest.runAllTimers()); assertLog(['Welcome to the general room!', 'Connected! theme: light']); expect(ReactNoop).toMatchRenderedOutput( <span prop="Welcome to the general room!" />, ); // change roomId only await act(() => ReactNoop.render(<ChatRoom roomId="music" theme="light" />), ); await act(() => jest.runAllTimers()); assertLog([ 'Welcome to the music room!', // should trigger a reconnect 'Connected! theme: light', ]); expect(ReactNoop).toMatchRenderedOutput( <span prop="Welcome to the music room!" />, ); // change theme only await act(() => ReactNoop.render(<ChatRoom roomId="music" theme="dark" />)); await act(() => jest.runAllTimers()); // should not trigger a reconnect assertLog(['Welcome to the music room!']); expect(ReactNoop).toMatchRenderedOutput( <span prop="Welcome to the music room!" />, ); // change roomId only await act(() => ReactNoop.render(<ChatRoom roomId="travel" theme="dark" />), ); await act(() => jest.runAllTimers()); assertLog([ 'Welcome to the travel room!', // should trigger a reconnect 'Connected! theme: dark', ]); expect(ReactNoop).toMatchRenderedOutput( <span prop="Welcome to the travel room!" />, ); }); // @gate enableUseEffectEventHook it('integration: implements the docs logVisit example', async () => { class AddToCartButton extends React.PureComponent { addToCart = () => { this.props.onClick(); }; render() { return <Text text="Add to cart" />; } } const ShoppingCartContext = createContext(null); function AppShell({children}) { const [items, updateItems] = useState([]); const value = useMemo(() => ({items, updateItems}), [items, updateItems]); return ( <ShoppingCartContext.Provider value={value}> {children} </ShoppingCartContext.Provider> ); } function Page({url}) { const {items, updateItems} = useContext(ShoppingCartContext); const onClick = useEffectEvent(() => updateItems([...items, 1])); const numberOfItems = items.length; const onVisit = useEffectEvent(visitedUrl => { Scheduler.log( 'url: ' + visitedUrl + ', numberOfItems: ' + numberOfItems, ); }); useEffect(() => { onVisit(url); }, [url]); return ( <AddToCartButton onClick={() => { onClick(); }} ref={button} /> ); } const button = React.createRef(null); await act(() => ReactNoop.render( <AppShell> <Page url="/shop/1" /> </AppShell>, ), ); assertLog(['Add to cart', 'url: /shop/1, numberOfItems: 0']); await act(() => button.current.addToCart()); assertLog(['Add to cart']); await act(() => ReactNoop.render( <AppShell> <Page url="/shop/2" /> </AppShell>, ), ); assertLog(['Add to cart', 'url: /shop/2, numberOfItems: 1']); }); });
25.865116
99
0.555988
Hands-On-AWS-Penetration-Testing-with-Kali-Linux
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {GitHubIssue} from './githubAPI'; import * as React from 'react'; import Icon from '../Icon'; import styles from './shared.css'; export default function UpdateExistingIssue({ gitHubIssue, }: { gitHubIssue: GitHubIssue, }): React.Node { const {title, url} = gitHubIssue; return ( <div className={styles.GitHubLinkRow}> <Icon className={styles.ReportIcon} type="bug" /> <div className={styles.UpdateExistingIssuePrompt}> Update existing issue: </div> <a className={styles.ReportLink} href={url} rel="noopener noreferrer" target="_blank" title="Report bug"> {title} </a> </div> ); }
22.153846
66
0.633038
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 {smartParse} from '../../utils'; import {parseHookPathForEdit} from './utils'; import styles from './NewArrayValue.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, index: number, inspectedElement: InspectedElement, path: Array<string | number>, store: Store, type: 'props' | 'context' | 'hooks' | 'state', }; export default function NewArrayValue({ bridge, depth, hidden, hookID, index, inspectedElement, path, store, type, }: Props): React.Node { const [key, setKey] = useState<number>(0); const [isInvalid, setIsInvalid] = useState(false); // This is a bit of an unusual usage of the EditableName component, // but otherwise it acts the way we want for a new Array entry. // $FlowFixMe[missing-local-annot] const overrideName = (oldPath: any, newPath) => { const value = newPath[newPath.length - 1]; let parsedValue; let newIsInvalid = true; try { parsedValue = smartParse(value); newIsInvalid = false; } catch (error) {} if (isInvalid !== newIsInvalid) { setIsInvalid(newIsInvalid); } if (!newIsInvalid) { setKey(key + 1); const {id} = inspectedElement; const rendererID = store.getRendererIDForElement(id); if (rendererID !== null) { let basePath = path; if (hookID != null) { basePath = parseHookPathForEdit(basePath); } bridge.send('overrideValueAtPath', { type, hookID, id, path: [...basePath, index], rendererID, value: parsedValue, }); } } }; return ( <div key={key} hidden={hidden} style={{ paddingLeft: `${(depth - 1) * 0.75}rem`, }}> <div className={styles.NewArrayValue}> <EditableName allowWhiteSpace={true} autoFocus={key > 0} className={[styles.EditableName, isInvalid && styles.Invalid].join( ' ', )} initialValue="" overrideName={overrideName} path={path} /> </div> </div> ); }
23.330275
79
0.605055
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 {Fiber, FiberRoot} from './ReactInternalTypes'; import type { UpdateQueue as HookQueue, Update as HookUpdate, } from './ReactFiberHooks'; import type { SharedQueue as ClassQueue, Update as ClassUpdate, } from './ReactFiberClassUpdateQueue'; import type {Lane, Lanes} from './ReactFiberLane'; import type {OffscreenInstance} from './ReactFiberActivityComponent'; import { warnAboutUpdateOnNotYetMountedFiberInDEV, throwIfInfiniteUpdateLoopDetected, getWorkInProgressRoot, } from './ReactFiberWorkLoop'; import {NoLane, NoLanes, mergeLanes, markHiddenUpdate} from './ReactFiberLane'; import {NoFlags, Placement, Hydrating} from './ReactFiberFlags'; import {HostRoot, OffscreenComponent} from './ReactWorkTags'; import {OffscreenVisible} from './ReactFiberActivityComponent'; export type ConcurrentUpdate = { next: ConcurrentUpdate, lane: Lane, }; type ConcurrentQueue = { pending: ConcurrentUpdate | null, }; // If a render is in progress, and we receive an update from a concurrent event, // we wait until the current render is over (either finished or interrupted) // before adding it to the fiber/hook queue. Push to this array so we can // access the queue, fiber, update, et al later. const concurrentQueues: Array<any> = []; let concurrentQueuesIndex = 0; let concurrentlyUpdatedLanes: Lanes = NoLanes; export function finishQueueingConcurrentUpdates(): void { const endIndex = concurrentQueuesIndex; concurrentQueuesIndex = 0; concurrentlyUpdatedLanes = NoLanes; let i = 0; while (i < endIndex) { const fiber: Fiber = concurrentQueues[i]; concurrentQueues[i++] = null; const queue: ConcurrentQueue = concurrentQueues[i]; concurrentQueues[i++] = null; const update: ConcurrentUpdate = concurrentQueues[i]; concurrentQueues[i++] = null; const lane: Lane = concurrentQueues[i]; concurrentQueues[i++] = null; if (queue !== null && update !== null) { const pending = queue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } queue.pending = update; } if (lane !== NoLane) { markUpdateLaneFromFiberToRoot(fiber, update, lane); } } } export function getConcurrentlyUpdatedLanes(): Lanes { return concurrentlyUpdatedLanes; } function enqueueUpdate( fiber: Fiber, queue: ConcurrentQueue | null, update: ConcurrentUpdate | null, lane: Lane, ) { // Don't update the `childLanes` on the return path yet. If we already in // the middle of rendering, wait until after it has completed. concurrentQueues[concurrentQueuesIndex++] = fiber; concurrentQueues[concurrentQueuesIndex++] = queue; concurrentQueues[concurrentQueuesIndex++] = update; concurrentQueues[concurrentQueuesIndex++] = lane; concurrentlyUpdatedLanes = mergeLanes(concurrentlyUpdatedLanes, lane); // The fiber's `lane` field is used in some places to check if any work is // scheduled, to perform an eager bailout, so we need to update it immediately. // TODO: We should probably move this to the "shared" queue instead. fiber.lanes = mergeLanes(fiber.lanes, lane); const alternate = fiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, lane); } } export function enqueueConcurrentHookUpdate<S, A>( fiber: Fiber, queue: HookQueue<S, A>, update: HookUpdate<S, A>, lane: Lane, ): FiberRoot | null { const concurrentQueue: ConcurrentQueue = (queue: any); const concurrentUpdate: ConcurrentUpdate = (update: any); enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane); return getRootForUpdatedFiber(fiber); } export function enqueueConcurrentHookUpdateAndEagerlyBailout<S, A>( fiber: Fiber, queue: HookQueue<S, A>, update: HookUpdate<S, A>, ): void { // This function is used to queue an update that doesn't need a rerender. The // only reason we queue it is in case there's a subsequent higher priority // update that causes it to be rebased. const lane = NoLane; const concurrentQueue: ConcurrentQueue = (queue: any); const concurrentUpdate: ConcurrentUpdate = (update: any); enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane); // Usually we can rely on the upcoming render phase to process the concurrent // queue. However, since this is a bail out, we're not scheduling any work // here. So the update we just queued will leak until something else happens // to schedule work (if ever). // // Check if we're currently in the middle of rendering a tree, and if not, // process the queue immediately to prevent a leak. const isConcurrentlyRendering = getWorkInProgressRoot() !== null; if (!isConcurrentlyRendering) { finishQueueingConcurrentUpdates(); } } export function enqueueConcurrentClassUpdate<State>( fiber: Fiber, queue: ClassQueue<State>, update: ClassUpdate<State>, lane: Lane, ): FiberRoot | null { const concurrentQueue: ConcurrentQueue = (queue: any); const concurrentUpdate: ConcurrentUpdate = (update: any); enqueueUpdate(fiber, concurrentQueue, concurrentUpdate, lane); return getRootForUpdatedFiber(fiber); } export function enqueueConcurrentRenderForLane( fiber: Fiber, lane: Lane, ): FiberRoot | null { enqueueUpdate(fiber, null, null, lane); return getRootForUpdatedFiber(fiber); } // Calling this function outside this module should only be done for backwards // compatibility and should always be accompanied by a warning. export function unsafe_markUpdateLaneFromFiberToRoot( sourceFiber: Fiber, lane: Lane, ): FiberRoot | null { // NOTE: For Hyrum's Law reasons, if an infinite update loop is detected, it // should throw before `markUpdateLaneFromFiberToRoot` is called. But this is // undefined behavior and we can change it if we need to; it just so happens // that, at the time of this writing, there's an internal product test that // happens to rely on this. const root = getRootForUpdatedFiber(sourceFiber); markUpdateLaneFromFiberToRoot(sourceFiber, null, lane); return root; } function markUpdateLaneFromFiberToRoot( sourceFiber: Fiber, update: ConcurrentUpdate | null, lane: Lane, ): void { // Update the source fiber's lanes sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); let alternate = sourceFiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, lane); } // Walk the parent path to the root and update the child lanes. let isHidden = false; let parent = sourceFiber.return; let node = sourceFiber; while (parent !== null) { parent.childLanes = mergeLanes(parent.childLanes, lane); alternate = parent.alternate; if (alternate !== null) { alternate.childLanes = mergeLanes(alternate.childLanes, lane); } if (parent.tag === OffscreenComponent) { // Check if this offscreen boundary is currently hidden. // // The instance may be null if the Offscreen parent was unmounted. Usually // the parent wouldn't be reachable in that case because we disconnect // fibers from the tree when they are deleted. However, there's a weird // edge case where setState is called on a fiber that was interrupted // before it ever mounted. Because it never mounts, it also never gets // deleted. Because it never gets deleted, its return pointer never gets // disconnected. Which means it may be attached to a deleted Offscreen // parent node. (This discovery suggests it may be better for memory usage // if we don't attach the `return` pointer until the commit phase, though // in order to do that we'd need some other way to track the return // pointer during the initial render, like on the stack.) // // This case is always accompanied by a warning, but we still need to // account for it. (There may be other cases that we haven't discovered, // too.) const offscreenInstance: OffscreenInstance | null = parent.stateNode; if ( offscreenInstance !== null && !(offscreenInstance._visibility & OffscreenVisible) ) { isHidden = true; } } node = parent; parent = parent.return; } if (isHidden && update !== null && node.tag === HostRoot) { const root: FiberRoot = node.stateNode; markHiddenUpdate(root, update, lane); } } function getRootForUpdatedFiber(sourceFiber: Fiber): FiberRoot | null { // TODO: We will detect and infinite update loop and throw even if this fiber // has already unmounted. This isn't really necessary but it happens to be the // current behavior we've used for several release cycles. Consider not // performing this check if the updated fiber already unmounted, since it's // not possible for that to cause an infinite update loop. throwIfInfiniteUpdateLoopDetected(); // When a setState happens, we must ensure the root is scheduled. Because // update queues do not have a backpointer to the root, the only way to do // this currently is to walk up the return path. This used to not be a big // deal because we would have to walk up the return path to set // the `childLanes`, anyway, but now those two traversals happen at // different times. // TODO: Consider adding a `root` backpointer on the update queue. detectUpdateOnUnmountedFiber(sourceFiber, sourceFiber); let node = sourceFiber; let parent = node.return; while (parent !== null) { detectUpdateOnUnmountedFiber(sourceFiber, node); node = parent; parent = node.return; } return node.tag === HostRoot ? (node.stateNode: FiberRoot) : null; } function detectUpdateOnUnmountedFiber(sourceFiber: Fiber, parent: Fiber) { if (__DEV__) { const alternate = parent.alternate; if ( alternate === null && (parent.flags & (Placement | Hydrating)) !== NoFlags ) { warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); } } }
35.070423
81
0.715513
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; export * from './src/ReactIs';
18.307692
66
0.676
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {normalizeCodeLocInfo} from './utils'; describe('component stack', () => { let React; let act; let legacyRender; let mockError; let mockWarn; beforeEach(() => { // Intercept native console methods before DevTools bootstraps. // Normalize component stack locations. mockError = jest.fn(); mockWarn = jest.fn(); console.error = (...args) => { mockError(...args.map(normalizeCodeLocInfo)); }; console.warn = (...args) => { mockWarn(...args.map(normalizeCodeLocInfo)); }; const utils = require('./utils'); act = utils.act; legacyRender = utils.legacyRender; React = require('react'); }); // @reactVersion >=16.9 it('should log the current component stack along with an error or warning', () => { const Grandparent = () => <Parent />; const Parent = () => <Child />; const Child = () => { console.error('Test error.'); console.warn('Test warning.'); return null; }; const container = document.createElement('div'); act(() => legacyRender(<Grandparent />, container)); expect(mockError).toHaveBeenCalledWith( 'Test error.', '\n in Child (at **)' + '\n in Parent (at **)' + '\n in Grandparent (at **)', ); expect(mockWarn).toHaveBeenCalledWith( 'Test warning.', '\n in Child (at **)' + '\n in Parent (at **)' + '\n in Grandparent (at **)', ); }); // This test should have caught #19911 // but didn't because both DevTools and ReactDOM are running in the same memory space, // so the case we're testing against (DevTools prod build and React DEV build) doesn't exist. // It would be nice to figure out a way to test this combination at some point... xit('should disable the current dispatcher before shallow rendering so no effects get scheduled', () => { let useEffectCount = 0; const Example = props => { React.useEffect(() => { useEffectCount++; expect(props).toBeDefined(); }, [props]); console.warn('Warning to trigger appended component stacks.'); return null; }; const container = document.createElement('div'); act(() => legacyRender(<Example test="abc" />, container)); expect(useEffectCount).toBe(1); expect(mockWarn).toHaveBeenCalledWith( 'Warning to trigger appended component stacks.', '\n in Example (at **)', ); }); });
27.634409
107
0.605184
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from '../ReactServerStreamConfigFB'; export function scheduleWork(callback: () => void) { // We don't schedule work in this model, and instead expect performWork to always be called repeatedly. }
26.533333
105
0.716019
null
'use strict'; /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function' ) { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); }
25.545455
74
0.687285
PenetrationTestingScripts
/* global chrome */ import {registerDevToolsEventLogger} from 'react-devtools-shared/src/registerDevToolsEventLogger'; function registerEventsLogger() { registerDevToolsEventLogger('extension', async () => { // TODO: after we upgrade to Firefox Manifest V3, chrome.tabs.query returns a Promise without the callback. return new Promise(resolve => { chrome.tabs.query({active: true}, tabs => { resolve({ page_url: tabs[0]?.url, }); }); }); }); } export default registerEventsLogger;
27.368421
111
0.667286
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-interactions-events/press-legacy.production.min.js'); } else { module.exports = require('./cjs/react-interactions-events/press-legacy.development.js'); }
31.125
93
0.71875
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ export const TYPES = { CLIPPING_RECTANGLE: 'ClippingRectangle', GROUP: 'Group', SHAPE: 'Shape', TEXT: 'Text', }; export const EVENT_TYPES = { onClick: 'click', onMouseMove: 'mousemove', onMouseOver: 'mouseover', onMouseOut: 'mouseout', onMouseUp: 'mouseup', onMouseDown: 'mousedown', }; export function childrenAsString(children) { if (!children) { return ''; } else if (typeof children === 'string') { return children; } else if (children.length) { return children.join(''); } else { return ''; } }
20.171429
66
0.652703
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 ReactDOM from 'react-dom'; const ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; export default ReactDOMSharedInternals;
22.8125
66
0.734211
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 {Wakeable} from 'shared/ReactTypes'; import type {TimelineData} from './types'; import {importFile as importFileWorker} from './import-worker'; const Pending = 0; const Resolved = 1; const Rejected = 2; type PendingRecord = { status: 0, value: Wakeable, }; type ResolvedRecord<T> = { status: 1, value: T, }; type RejectedRecord = { status: 2, value: Error, }; type Record<T> = PendingRecord | ResolvedRecord<T> | RejectedRecord; // This is intentionally a module-level Map, rather than a React-managed one. // Otherwise, refreshing the inspected element cache would also clear this cache. // Profiler file contents are static anyway. const fileNameToProfilerDataMap: Map<string, Record<TimelineData>> = new Map(); function readRecord<T>(record: Record<T>): ResolvedRecord<T> | RejectedRecord { if (record.status === Resolved) { // This is just a type refinement. return record; } else if (record.status === Rejected) { // This is just a type refinement. return record; } else { throw record.value; } } export function importFile(file: File): TimelineData | Error { const fileName = file.name; let record = fileNameToProfilerDataMap.get(fileName); if (!record) { const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { then(callback: () => mixed) { callbacks.add(callback); }, // Optional property used by Timeline: displayName: `Importing file "${fileName}"`, }; const wake = () => { // This assumes they won't throw. callbacks.forEach(callback => callback()); callbacks.clear(); }; const newRecord: Record<TimelineData> = (record = { status: Pending, value: wakeable, }); importFileWorker(file).then(data => { switch (data.status) { case 'SUCCESS': const resolvedRecord = ((newRecord: any): ResolvedRecord<TimelineData>); resolvedRecord.status = Resolved; resolvedRecord.value = data.processedData; break; case 'INVALID_PROFILE_ERROR': case 'UNEXPECTED_ERROR': const thrownRecord = ((newRecord: any): RejectedRecord); thrownRecord.status = Rejected; thrownRecord.value = data.error; break; } wake(); }); fileNameToProfilerDataMap.set(fileName, record); } const response = readRecord(record).value; return response; }
24.528846
81
0.645064
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 { Thenable, PendingThenable, FulfilledThenable, RejectedThenable, ReactCustomFormAction, } from 'shared/ReactTypes'; import { REACT_ELEMENT_TYPE, REACT_LAZY_TYPE, REACT_PROVIDER_TYPE, getIteratorFn, } from 'shared/ReactSymbols'; import { describeObjectForErrorMessage, isSimpleObject, objectName, } from 'shared/ReactSerializationErrors'; import isArray from 'shared/isArray'; import getPrototypeOf from 'shared/getPrototypeOf'; const ObjectPrototype = Object.prototype; import {usedWithSSR} from './ReactFlightClientConfig'; type ReactJSONValue = | string | boolean | number | null | $ReadOnlyArray<ReactJSONValue> | ReactServerObject; export opaque type ServerReference<T> = T; export type CallServerCallback = <A, T>(id: any, args: A) => Promise<T>; export type ServerReferenceId = any; const knownServerReferences: WeakMap< Function, {id: ServerReferenceId, bound: null | Thenable<Array<any>>}, > = new WeakMap(); // Serializable values export type ReactServerValue = // References are passed by their value | ServerReference<any> // The rest are passed as is. Sub-types can be passed in but lose their // subtype, so the receiver can only accept once of these. | string | boolean | number | symbol | null | void | bigint | Iterable<ReactServerValue> | Array<ReactServerValue> | Map<ReactServerValue, ReactServerValue> | Set<ReactServerValue> | Date | ReactServerObject | Promise<ReactServerValue>; // Thenable<ReactServerValue> type ReactServerObject = {+[key: string]: ReactServerValue}; // function serializeByValueID(id: number): string { // return '$' + id.toString(16); // } function serializePromiseID(id: number): string { return '$@' + id.toString(16); } function serializeServerReferenceID(id: number): string { return '$F' + id.toString(16); } function serializeSymbolReference(name: string): string { return '$S' + name; } function serializeFormDataReference(id: number): string { // Why K? F is "Function". D is "Date". What else? return '$K' + id.toString(16); } function serializeNumber(number: number): string | number { if (Number.isFinite(number)) { if (number === 0 && 1 / number === -Infinity) { return '$-0'; } else { return number; } } else { if (number === Infinity) { return '$Infinity'; } else if (number === -Infinity) { return '$-Infinity'; } else { return '$NaN'; } } } function serializeUndefined(): string { return '$undefined'; } function serializeDateFromDateJSON(dateJSON: string): string { // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. // We need only tack on a $D prefix. return '$D' + dateJSON; } function serializeBigInt(n: bigint): string { return '$n' + n.toString(10); } function serializeMapID(id: number): string { return '$Q' + id.toString(16); } function serializeSetID(id: number): string { return '$W' + id.toString(16); } function escapeStringValue(value: string): string { if (value[0] === '$') { // We need to escape $ prefixed strings since we use those to encode // references to IDs and as special symbol values. return '$' + value; } else { return value; } } export function processReply( root: ReactServerValue, formFieldPrefix: string, resolve: (string | FormData) => void, reject: (error: mixed) => void, ): void { let nextPartId = 1; let pendingParts = 0; let formData: null | FormData = null; function resolveToJSON( this: | {+[key: string | number]: ReactServerValue} | $ReadOnlyArray<ReactServerValue>, key: string, value: ReactServerValue, ): ReactJSONValue { const parent = this; // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us if (__DEV__) { // $FlowFixMe[incompatible-use] const originalValue = parent[key]; if ( typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date) ) { if (objectName(originalValue) !== 'Object') { console.error( 'Only plain objects can be passed to Server Functions from the Client. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key), ); } else { console.error( 'Only plain objects can be passed to Server Functions from the Client. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key), ); } } } if (value === null) { return null; } if (typeof value === 'object') { // $FlowFixMe[method-unbinding] if (typeof value.then === 'function') { // We assume that any object with a .then property is a "Thenable" type, // or a Promise type. Either of which can be represented by a Promise. if (formData === null) { // Upgrade to use FormData to allow us to stream this value. formData = new FormData(); } pendingParts++; const promiseId = nextPartId++; const thenable: Thenable<any> = (value: any); thenable.then( partValue => { const partJSON = JSON.stringify(partValue, resolveToJSON); // $FlowFixMe[incompatible-type] We know it's not null because we assigned it above. const data: FormData = formData; // eslint-disable-next-line react-internal/safe-string-coercion data.append(formFieldPrefix + promiseId, partJSON); pendingParts--; if (pendingParts === 0) { resolve(data); } }, reason => { // In the future we could consider serializing this as an error // that throws on the server instead. reject(reason); }, ); return serializePromiseID(promiseId); } if (isArray(value)) { // $FlowFixMe[incompatible-return] return value; } // TODO: Should we the Object.prototype.toString.call() to test for cross-realm objects? if (value instanceof FormData) { if (formData === null) { // Upgrade to use FormData to allow us to use rich objects as its values. formData = new FormData(); } const data: FormData = formData; const refId = nextPartId++; // Copy all the form fields with a prefix for this reference. // These must come first in the form order because we assume that all the // fields are available before this is referenced. const prefix = formFieldPrefix + refId + '_'; // $FlowFixMe[prop-missing]: FormData has forEach. value.forEach((originalValue: string | File, originalKey: string) => { data.append(prefix + originalKey, originalValue); }); return serializeFormDataReference(refId); } if (value instanceof Map) { const partJSON = JSON.stringify(Array.from(value), resolveToJSON); if (formData === null) { formData = new FormData(); } const mapId = nextPartId++; formData.append(formFieldPrefix + mapId, partJSON); return serializeMapID(mapId); } if (value instanceof Set) { const partJSON = JSON.stringify(Array.from(value), resolveToJSON); if (formData === null) { formData = new FormData(); } const setId = nextPartId++; formData.append(formFieldPrefix + setId, partJSON); return serializeSetID(setId); } const iteratorFn = getIteratorFn(value); if (iteratorFn) { return Array.from((value: any)); } // Verify that this is a simple plain object. const proto = getPrototypeOf(value); if ( proto !== ObjectPrototype && (proto === null || getPrototypeOf(proto) !== null) ) { throw new Error( 'Only plain objects, and a few built-ins, can be passed to Server Actions. ' + 'Classes or null prototypes are not supported.', ); } if (__DEV__) { if ((value: any).$$typeof === REACT_ELEMENT_TYPE) { console.error( 'React Element cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key), ); } else if ((value: any).$$typeof === REACT_LAZY_TYPE) { console.error( 'React Lazy cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key), ); } else if ((value: any).$$typeof === REACT_PROVIDER_TYPE) { console.error( 'React Context Providers cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key), ); } else if (objectName(value) !== 'Object') { console.error( 'Only plain objects can be passed to Server Functions from the Client. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key), ); } else if (!isSimpleObject(value)) { console.error( 'Only plain objects can be passed to Server Functions from the Client. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key), ); } else if (Object.getOwnPropertySymbols) { const symbols = Object.getOwnPropertySymbols(value); if (symbols.length > 0) { console.error( 'Only plain objects can be passed to Server Functions from the Client. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key), ); } } } // $FlowFixMe[incompatible-return] return value; } if (typeof value === 'string') { // TODO: Maybe too clever. If we support URL there's no similar trick. if (value[value.length - 1] === 'Z') { // Possibly a Date, whose toJSON automatically calls toISOString // $FlowFixMe[incompatible-use] const originalValue = parent[key]; if (originalValue instanceof Date) { return serializeDateFromDateJSON(value); } } return escapeStringValue(value); } if (typeof value === 'boolean') { return value; } if (typeof value === 'number') { return serializeNumber(value); } if (typeof value === 'undefined') { return serializeUndefined(); } if (typeof value === 'function') { const metaData = knownServerReferences.get(value); if (metaData !== undefined) { const metaDataJSON = JSON.stringify(metaData, resolveToJSON); if (formData === null) { // Upgrade to use FormData to allow us to stream this value. formData = new FormData(); } // The reference to this function came from the same client so we can pass it back. const refId = nextPartId++; // eslint-disable-next-line react-internal/safe-string-coercion formData.set(formFieldPrefix + refId, metaDataJSON); return serializeServerReferenceID(refId); } throw new Error( 'Client Functions cannot be passed directly to Server Functions. ' + 'Only Functions passed from the Server can be passed back again.', ); } if (typeof value === 'symbol') { // $FlowFixMe[incompatible-type] `description` might be undefined const name: string = value.description; if (Symbol.for(name) !== value) { throw new Error( 'Only global symbols received from Symbol.for(...) can be passed to Server Functions. ' + `The symbol Symbol.for(${ // $FlowFixMe[incompatible-type] `description` might be undefined value.description }) cannot be found among global symbols.`, ); } return serializeSymbolReference(name); } if (typeof value === 'bigint') { return serializeBigInt(value); } throw new Error( `Type ${typeof value} is not supported as an argument to a Server Function.`, ); } // $FlowFixMe[incompatible-type] it's not going to be undefined because we'll encode it. const json: string = JSON.stringify(root, resolveToJSON); if (formData === null) { // If it's a simple data structure, we just use plain JSON. resolve(json); } else { // Otherwise, we use FormData to let us stream in the result. formData.set(formFieldPrefix + '0', json); if (pendingParts === 0) { // $FlowFixMe[incompatible-call] this has already been refined. resolve(formData); } } } const boundCache: WeakMap< {id: ServerReferenceId, bound: null | Thenable<Array<any>>}, Thenable<FormData>, > = new WeakMap(); function encodeFormData(reference: any): Thenable<FormData> { let resolve, reject; // We need to have a handle on the thenable so that we can synchronously set // its status from processReply, when it can complete synchronously. const thenable: Thenable<FormData> = new Promise((res, rej) => { resolve = res; reject = rej; }); processReply( reference, '', (body: string | FormData) => { if (typeof body === 'string') { const data = new FormData(); data.append('0', body); body = data; } const fulfilled: FulfilledThenable<FormData> = (thenable: any); fulfilled.status = 'fulfilled'; fulfilled.value = body; resolve(body); }, e => { const rejected: RejectedThenable<FormData> = (thenable: any); rejected.status = 'rejected'; rejected.reason = e; reject(e); }, ); return thenable; } export function encodeFormAction( this: any => Promise<any>, identifierPrefix: string, ): ReactCustomFormAction { const reference = knownServerReferences.get(this); if (!reference) { throw new Error( 'Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.', ); } let data: null | FormData = null; let name; const boundPromise = reference.bound; if (boundPromise !== null) { let thenable = boundCache.get(reference); if (!thenable) { thenable = encodeFormData(reference); boundCache.set(reference, thenable); } if (thenable.status === 'rejected') { throw thenable.reason; } else if (thenable.status !== 'fulfilled') { throw thenable; } const encodedFormData = thenable.value; // This is hacky but we need the identifier prefix to be added to // all fields but the suspense cache would break since we might get // a new identifier each time. So we just append it at the end instead. const prefixedData = new FormData(); // $FlowFixMe[prop-missing] encodedFormData.forEach((value: string | File, key: string) => { prefixedData.append('$ACTION_' + identifierPrefix + ':' + key, value); }); data = prefixedData; // We encode the name of the prefix containing the data. name = '$ACTION_REF_' + identifierPrefix; } else { // This is the simple case so we can just encode the ID. name = '$ACTION_ID_' + reference.id; } return { name: name, method: 'POST', encType: 'multipart/form-data', data: data, }; } function isSignatureEqual( this: any => Promise<any>, referenceId: ServerReferenceId, numberOfBoundArgs: number, ): boolean { const reference = knownServerReferences.get(this); if (!reference) { throw new Error( 'Tried to encode a Server Action from a different instance than the encoder is from. ' + 'This is a bug in React.', ); } if (reference.id !== referenceId) { // These are different functions. return false; } // Now check if the number of bound arguments is the same. const boundPromise = reference.bound; if (boundPromise === null) { // No bound arguments. return numberOfBoundArgs === 0; } // Unwrap the bound arguments array by suspending, if necessary. As with // encodeFormData, this means isSignatureEqual can only be called while React // is rendering. switch (boundPromise.status) { case 'fulfilled': { const boundArgs = boundPromise.value; return boundArgs.length === numberOfBoundArgs; } case 'pending': { throw boundPromise; } case 'rejected': { throw boundPromise.reason; } default: { if (typeof boundPromise.status === 'string') { // Only instrument the thenable if the status if not defined. } else { const pendingThenable: PendingThenable<Array<any>> = (boundPromise: any); pendingThenable.status = 'pending'; pendingThenable.then( (boundArgs: Array<any>) => { const fulfilledThenable: FulfilledThenable<Array<any>> = (boundPromise: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = boundArgs; }, (error: mixed) => { const rejectedThenable: RejectedThenable<number> = (boundPromise: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = error; }, ); } throw boundPromise; } } } export function registerServerReference( proxy: any, reference: {id: ServerReferenceId, bound: null | Thenable<Array<any>>}, ) { // Expose encoder for use by SSR, as well as a special bind that can be used to // keep server capabilities. if (usedWithSSR) { // Only expose this in builds that would actually use it. Not needed on the client. Object.defineProperties((proxy: any), { $$FORM_ACTION: {value: encodeFormAction}, $$IS_SIGNATURE_EQUAL: {value: isSignatureEqual}, bind: {value: bind}, }); } knownServerReferences.set(proxy, reference); } // $FlowFixMe[method-unbinding] const FunctionBind = Function.prototype.bind; // $FlowFixMe[method-unbinding] const ArraySlice = Array.prototype.slice; function bind(this: Function) { // $FlowFixMe[unsupported-syntax] const newFn = FunctionBind.apply(this, arguments); const reference = knownServerReferences.get(this); if (reference) { const args = ArraySlice.call(arguments, 1); let boundPromise = null; if (reference.bound !== null) { boundPromise = Promise.resolve((reference.bound: any)).then(boundArgs => boundArgs.concat(args), ); } else { boundPromise = Promise.resolve(args); } registerServerReference(newFn, {id: reference.id, bound: boundPromise}); } return newFn; } export function createServerReference<A: Iterable<any>, T>( id: ServerReferenceId, callServer: CallServerCallback, ): (...A) => Promise<T> { const proxy = function (): Promise<T> { // $FlowFixMe[method-unbinding] const args = Array.prototype.slice.call(arguments); return callServer(id, args); }; registerServerReference(proxy, {id, bound: null}); return proxy; }
30.806763
99
0.623361
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 */ // This is a host config that's used for the `react-reconciler` package on npm. // It is only used by third-party renderers. // // Its API lets you pass the host config as an argument. // However, inside the `react-reconciler` we treat host config as a module. // This file is a shim between two worlds. // // It works because the `react-reconciler` bundle is wrapped in something like: // // module.exports = function ($$$config) { // /* reconciler code */ // } // // So `$$$config` looks like a global variable, but it's // really an argument to a top-level wrapping function. declare var $$$config: any; export opaque type Type = mixed; // eslint-disable-line no-undef export opaque type Props = mixed; // eslint-disable-line no-undef export opaque type Container = mixed; // eslint-disable-line no-undef export opaque type Instance = mixed; // eslint-disable-line no-undef export opaque type TextInstance = mixed; // eslint-disable-line no-undef export opaque type SuspenseInstance = mixed; // eslint-disable-line no-undef export opaque type HydratableInstance = mixed; // eslint-disable-line no-undef export opaque type PublicInstance = mixed; // eslint-disable-line no-undef export opaque type HostContext = mixed; // eslint-disable-line no-undef export opaque type UpdatePayload = mixed; // eslint-disable-line no-undef export opaque type ChildSet = mixed; // eslint-disable-line no-undef export opaque type TimeoutHandle = mixed; // eslint-disable-line no-undef export opaque type NoTimeout = mixed; // eslint-disable-line no-undef export opaque type RendererInspectionConfig = mixed; // eslint-disable-line no-undef export opaque type TransitionStatus = mixed; // eslint-disable-line no-undef export type EventResponder = any; export const getPublicInstance = $$$config.getPublicInstance; export const getRootHostContext = $$$config.getRootHostContext; export const getChildHostContext = $$$config.getChildHostContext; export const prepareForCommit = $$$config.prepareForCommit; export const resetAfterCommit = $$$config.resetAfterCommit; export const createInstance = $$$config.createInstance; export const appendInitialChild = $$$config.appendInitialChild; export const finalizeInitialChildren = $$$config.finalizeInitialChildren; export const shouldSetTextContent = $$$config.shouldSetTextContent; export const createTextInstance = $$$config.createTextInstance; export const scheduleTimeout = $$$config.scheduleTimeout; export const cancelTimeout = $$$config.cancelTimeout; export const noTimeout = $$$config.noTimeout; export const isPrimaryRenderer = $$$config.isPrimaryRenderer; export const warnsIfNotActing = $$$config.warnsIfNotActing; export const supportsMutation = $$$config.supportsMutation; export const supportsPersistence = $$$config.supportsPersistence; export const supportsHydration = $$$config.supportsHydration; export const getInstanceFromNode = $$$config.getInstanceFromNode; export const beforeActiveInstanceBlur = $$$config.beforeActiveInstanceBlur; export const afterActiveInstanceBlur = $$$config.afterActiveInstanceBlur; export const preparePortalMount = $$$config.preparePortalMount; export const prepareScopeUpdate = $$$config.prepareScopeUpdate; export const getInstanceFromScope = $$$config.getInstanceFromScope; export const getCurrentEventPriority = $$$config.getCurrentEventPriority; export const shouldAttemptEagerTransition = $$$config.shouldAttemptEagerTransition; export const detachDeletedInstance = $$$config.detachDeletedInstance; export const requestPostPaintCallback = $$$config.requestPostPaintCallback; export const maySuspendCommit = $$$config.maySuspendCommit; export const preloadInstance = $$$config.preloadInstance; export const startSuspendingCommit = $$$config.startSuspendingCommit; export const suspendInstance = $$$config.suspendInstance; export const waitForCommitToBeReady = $$$config.waitForCommitToBeReady; export const NotPendingTransition = $$$config.NotPendingTransition; // ------------------- // Microtasks // (optional) // ------------------- export const supportsMicrotasks = $$$config.supportsMicrotasks; export const scheduleMicrotask = $$$config.scheduleMicrotask; // ------------------- // Test selectors // (optional) // ------------------- export const supportsTestSelectors = $$$config.supportsTestSelectors; export const findFiberRoot = $$$config.findFiberRoot; export const getBoundingRect = $$$config.getBoundingRect; export const getTextContent = $$$config.getTextContent; export const isHiddenSubtree = $$$config.isHiddenSubtree; export const matchAccessibilityRole = $$$config.matchAccessibilityRole; export const setFocusIfFocusable = $$$config.setFocusIfFocusable; export const setupIntersectionObserver = $$$config.setupIntersectionObserver; // ------------------- // Mutation // (optional) // ------------------- export const appendChild = $$$config.appendChild; export const appendChildToContainer = $$$config.appendChildToContainer; export const commitTextUpdate = $$$config.commitTextUpdate; export const commitMount = $$$config.commitMount; export const commitUpdate = $$$config.commitUpdate; export const insertBefore = $$$config.insertBefore; export const insertInContainerBefore = $$$config.insertInContainerBefore; export const removeChild = $$$config.removeChild; export const removeChildFromContainer = $$$config.removeChildFromContainer; export const resetTextContent = $$$config.resetTextContent; export const hideInstance = $$$config.hideInstance; export const hideTextInstance = $$$config.hideTextInstance; export const unhideInstance = $$$config.unhideInstance; export const unhideTextInstance = $$$config.unhideTextInstance; export const clearContainer = $$$config.clearContainer; // ------------------- // Persistence // (optional) // ------------------- export const cloneInstance = $$$config.cloneInstance; export const createContainerChildSet = $$$config.createContainerChildSet; export const appendChildToContainerChildSet = $$$config.appendChildToContainerChildSet; export const finalizeContainerChildren = $$$config.finalizeContainerChildren; export const replaceContainerChildren = $$$config.replaceContainerChildren; export const cloneHiddenInstance = $$$config.cloneHiddenInstance; export const cloneHiddenTextInstance = $$$config.cloneHiddenTextInstance; // ------------------- // Hydration // (optional) // ------------------- export const isHydratableText = $$$config.isHydratableText; export const isSuspenseInstancePending = $$$config.isSuspenseInstancePending; export const isSuspenseInstanceFallback = $$$config.isSuspenseInstanceFallback; export const getSuspenseInstanceFallbackErrorDetails = $$$config.getSuspenseInstanceFallbackErrorDetails; export const registerSuspenseInstanceRetry = $$$config.registerSuspenseInstanceRetry; export const canHydrateFormStateMarker = $$$config.canHydrateFormStateMarker; export const isFormStateMarkerMatching = $$$config.isFormStateMarkerMatching; export const getNextHydratableSibling = $$$config.getNextHydratableSibling; export const getFirstHydratableChild = $$$config.getFirstHydratableChild; export const getFirstHydratableChildWithinContainer = $$$config.getFirstHydratableChildWithinContainer; export const getFirstHydratableChildWithinSuspenseInstance = $$$config.getFirstHydratableChildWithinSuspenseInstance; export const canHydrateInstance = $$$config.canHydrateInstance; export const canHydrateTextInstance = $$$config.canHydrateTextInstance; export const canHydrateSuspenseInstance = $$$config.canHydrateSuspenseInstance; export const hydrateInstance = $$$config.hydrateInstance; export const hydrateTextInstance = $$$config.hydrateTextInstance; export const hydrateSuspenseInstance = $$$config.hydrateSuspenseInstance; export const getNextHydratableInstanceAfterSuspenseInstance = $$$config.getNextHydratableInstanceAfterSuspenseInstance; export const commitHydratedContainer = $$$config.commitHydratedContainer; export const commitHydratedSuspenseInstance = $$$config.commitHydratedSuspenseInstance; export const clearSuspenseBoundary = $$$config.clearSuspenseBoundary; export const clearSuspenseBoundaryFromContainer = $$$config.clearSuspenseBoundaryFromContainer; export const shouldDeleteUnhydratedTailInstances = $$$config.shouldDeleteUnhydratedTailInstances; export const didNotMatchHydratedContainerTextInstance = $$$config.didNotMatchHydratedContainerTextInstance; export const didNotMatchHydratedTextInstance = $$$config.didNotMatchHydratedTextInstance; export const didNotHydrateInstanceWithinContainer = $$$config.didNotHydrateInstanceWithinContainer; export const didNotHydrateInstanceWithinSuspenseInstance = $$$config.didNotHydrateInstanceWithinSuspenseInstance; export const didNotHydrateInstance = $$$config.didNotHydrateInstance; export const didNotFindHydratableInstanceWithinContainer = $$$config.didNotFindHydratableInstanceWithinContainer; export const didNotFindHydratableTextInstanceWithinContainer = $$$config.didNotFindHydratableTextInstanceWithinContainer; export const didNotFindHydratableSuspenseInstanceWithinContainer = $$$config.didNotFindHydratableSuspenseInstanceWithinContainer; export const didNotFindHydratableInstanceWithinSuspenseInstance = $$$config.didNotFindHydratableInstanceWithinSuspenseInstance; export const didNotFindHydratableTextInstanceWithinSuspenseInstance = $$$config.didNotFindHydratableTextInstanceWithinSuspenseInstance; export const didNotFindHydratableSuspenseInstanceWithinSuspenseInstance = $$$config.didNotFindHydratableSuspenseInstanceWithinSuspenseInstance; export const didNotFindHydratableInstance = $$$config.didNotFindHydratableInstance; export const didNotFindHydratableTextInstance = $$$config.didNotFindHydratableTextInstance; export const didNotFindHydratableSuspenseInstance = $$$config.didNotFindHydratableSuspenseInstance; export const errorHydratingContainer = $$$config.errorHydratingContainer; // ------------------- // Resources // (optional) // ------------------- export type HoistableRoot = mixed; export type Resource = mixed; // eslint-disable-line no-undef export const supportsResources = $$$config.supportsResources; export const isHostHoistableType = $$$config.isHostHoistableType; export const getHoistableRoot = $$$config.getHoistableRoot; export const getResource = $$$config.getResource; export const acquireResource = $$$config.acquireResource; export const releaseResource = $$$config.releaseResource; export const hydrateHoistable = $$$config.hydrateHoistable; export const mountHoistable = $$$config.mountHoistable; export const unmountHoistable = $$$config.unmountHoistable; export const createHoistableInstance = $$$config.createHoistableInstance; export const prepareToCommitHoistables = $$$config.prepareToCommitHoistables; export const mayResourceSuspendCommit = $$$config.mayResourceSuspendCommit; export const preloadResource = $$$config.preloadResource; export const suspendResource = $$$config.suspendResource; // ------------------- // Singletons // (optional) // ------------------- export const supportsSingletons = $$$config.supportsSingletons; export const resolveSingletonInstance = $$$config.resolveSingletonInstance; export const clearSingleton = $$$config.clearSingleton; export const acquireSingletonInstance = $$$config.acquireSingletonInstance; export const releaseSingletonInstance = $$$config.releaseSingletonInstance; export const isHostSingletonType = $$$config.isHostSingletonType;
50.337719
84
0.795967
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 ReactDOMFizzStatic; let Suspense; let textCache; let document; let writable; let container; let buffer = ''; let hasErrored = false; let fatalError = undefined; describe('ReactDOMFizzStatic', () => { beforeEach(() => { jest.resetModules(); JSDOM = require('jsdom').JSDOM; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); if (__EXPERIMENTAL__) { ReactDOMFizzStatic = require('react-dom/static'); } Stream = require('stream'); Suspense = React.Suspense; textCache = new Map(); // 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 act(callback) { await callback(); // Await one turn around the event loop. // This assumes that we'll flush everything we have so far. await new Promise(resolve => { setImmediate(resolve); }); if (hasErrored) { throw fatalError; } // JSDOM doesn't support stream HTML parser so we need to give it a proper fragment. // We also want to execute any scripts that are embedded. // We assume that we have now received a proper fragment of HTML. const bufferedContent = buffer; buffer = ''; const fakeBody = document.createElement('body'); fakeBody.innerHTML = bufferedContent; while (fakeBody.firstChild) { const node = fakeBody.firstChild; if (node.nodeName === 'SCRIPT') { const script = document.createElement('script'); script.textContent = node.textContent; for (let i = 0; i < node.attributes.length; i++) { const attribute = node.attributes[i]; script.setAttribute(attribute.name, attribute.value); } fakeBody.removeChild(node); container.appendChild(script); } else { container.appendChild(node); } } } function getVisibleChildren(element) { const children = []; let node = element.firstChild; while (node) { if (node.nodeType === 1) { if ( (node.tagName !== 'SCRIPT' || node.hasAttribute('type')) && node.tagName !== 'TEMPLATE' && node.tagName !== 'template' && !node.hasAttribute('hidden') && !node.hasAttribute('aria-hidden') ) { 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; } function resolveText(text) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } } /* function rejectText(text, error) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'rejected', value: error, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'rejected'; record.value = error; thenable.pings.forEach(t => t()); } } */ function readText(text) { const record = textCache.get(text); if (record !== undefined) { switch (record.status) { case 'pending': throw record.value; case 'rejected': throw record.value; case 'resolved': return record.value; } } else { const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.set(text, newRecord); throw thenable; } } function Text({text}) { return text; } function AsyncText({text}) { return readText(text); } // @gate experimental it('should render a fully static document, send it and then hydrate it', async () => { function App() { return ( <div> <Suspense fallback={<Text text="Loading..." />}> <AsyncText text="Hello" /> </Suspense> </div> ); } const promise = ReactDOMFizzStatic.prerenderToNodeStream(<App />); resolveText('Hello'); const result = await promise; expect(result.postponed).toBe(null); await act(async () => { result.prelude.pipe(writable); }); expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); expect(getVisibleChildren(container)).toEqual(<div>Hello</div>); }); // @gate experimental it('should support importMap option', async () => { const importMap = { foo: 'path/to/foo.js', }; const result = await ReactDOMFizzStatic.prerenderToNodeStream( <html> <body>hello world</body> </html>, {importMap}, ); await act(async () => { result.prelude.pipe(writable); }); expect(getVisibleChildren(container)).toEqual([ <script type="importmap">{JSON.stringify(importMap)}</script>, 'hello world', ]); }); // @gate experimental it('supports onHeaders', async () => { let headers; function onHeaders(x) { headers = x; } function App() { ReactDOM.preload('image', {as: 'image', fetchPriority: 'high'}); ReactDOM.preload('font', {as: 'font'}); return ( <html> <body>hello</body> </html> ); } const result = await ReactDOMFizzStatic.prerenderToNodeStream(<App />, { onHeaders, }); expect(headers).toEqual({ Link: ` <font>; rel=preload; as="font"; crossorigin="", <image>; rel=preload; as="image"; fetchpriority="high" ` .replaceAll('\n', '') .trim(), }); await act(async () => { result.prelude.pipe(writable); }); expect(getVisibleChildren(container)).toEqual('hello'); }); // @gate experimental && enablePostpone it('includes stylesheet preloads in onHeaders when postponing in the Shell', async () => { let headers; function onHeaders(x) { headers = x; } function App() { ReactDOM.preload('image', {as: 'image', fetchPriority: 'high'}); ReactDOM.preinit('style', {as: 'style'}); React.unstable_postpone(); return ( <html> <body>hello</body> </html> ); } const result = await ReactDOMFizzStatic.prerenderToNodeStream(<App />, { onHeaders, }); expect(headers).toEqual({ Link: ` <image>; rel=preload; as="image"; fetchpriority="high", <style>; rel=preload; as="style" ` .replaceAll('\n', '') .trim(), }); await act(async () => { result.prelude.pipe(writable); }); expect(getVisibleChildren(container)).toEqual(undefined); }); });
24.825959
94
0.573566
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'; // Based on similar script in Jest // https://github.com/facebook/jest/blob/a7acc5ae519613647ff2c253dd21933d6f94b47f/scripts/prettier.js const chalk = require('chalk'); const glob = require('glob'); const prettier = require('prettier'); const fs = require('fs'); const path = require('path'); const listChangedFiles = require('../shared/listChangedFiles'); const prettierConfigPath = require.resolve('../../.prettierrc'); const mode = process.argv[2] || 'check'; const shouldWrite = mode === 'write' || mode === 'write-changed'; const onlyChanged = mode === 'check-changed' || mode === 'write-changed'; const changedFiles = onlyChanged ? listChangedFiles() : null; const prettierIgnoreFilePath = path.join( __dirname, '..', '..', '.prettierignore' ); const prettierIgnore = fs.readFileSync(prettierIgnoreFilePath, { encoding: 'utf8', }); const ignoredPathsListedInPrettierIgnore = prettierIgnore .toString() .replace(/\r\n/g, '\n') .split('\n') .filter(line => !!line && !line.startsWith('#')); const ignoredPathsListedInPrettierIgnoreInGlobFormat = ignoredPathsListedInPrettierIgnore.map(ignoredPath => { const existsAndDirectory = fs.existsSync(ignoredPath) && fs.lstatSync(ignoredPath).isDirectory(); if (existsAndDirectory) { return path.join(ignoredPath, '/**'); } return ignoredPath; }); const files = glob .sync('**/*.js', { ignore: [ '**/node_modules/**', '**/cjs/**', ...ignoredPathsListedInPrettierIgnoreInGlobFormat, ], }) .filter(f => !onlyChanged || changedFiles.has(f)); if (!files.length) { process.exit(0); } async function main() { let didWarn = false; let didError = false; await Promise.all( files.map(async file => { const options = await prettier.resolveConfig(file, { config: prettierConfigPath, }); try { const input = fs.readFileSync(file, 'utf8'); if (shouldWrite) { const output = await prettier.format(input, options); if (output !== input) { fs.writeFileSync(file, output, 'utf8'); } } else { const isFormatted = await prettier.check(input, options); if (!isFormatted) { if (!didWarn) { console.log( '\n' + chalk.red( ` This project uses prettier to format all JavaScript code.\n` ) + chalk.dim(` Please run `) + chalk.reset('yarn prettier-all') + chalk.dim( ` and add changes to files listed below to your commit:` ) + `\n\n` ); didWarn = true; } console.log(file); } } } catch (error) { didError = true; console.log('\n\n' + error.message); console.log(file); } }) ); if (didWarn || didError) { process.exit(1); } } main().catch(error => { console.error(error); process.exit(1); });
26.283333
101
0.582951
null
'use strict'; const {TestEnvironment: JSDOMEnvironment} = require('jest-environment-jsdom'); const {TestEnvironment: NodeEnvironment} = require('jest-environment-node'); /** * Test environment for testing integration of react-dom (browser) with react-dom/server (node) */ class ReactDOMServerIntegrationEnvironment extends NodeEnvironment { constructor(config, context) { super(config, context); this.domEnvironment = new JSDOMEnvironment(config, context); this.global.window = this.domEnvironment.dom.window; this.global.document = this.global.window.document; this.global.navigator = this.global.window.navigator; this.global.Node = this.global.window.Node; this.global.addEventListener = this.global.window.addEventListener; this.global.MutationObserver = this.global.window.MutationObserver; } async setup() { await super.setup(); await this.domEnvironment.setup(); } async teardown() { await this.domEnvironment.teardown(); await super.teardown(); } } module.exports = ReactDOMServerIntegrationEnvironment;
29.914286
95
0.745606
null
#!/usr/bin/env node 'use strict'; const {readJson} = require('fs-extra'); const {join} = require('path'); const theme = require('../theme'); const run = async ({cwd, packages, tags}) => { // Prevent a "next" release from ever being published as @latest // All canaries share a version number, so it's okay to check any of them. const arbitraryPackageName = packages[0]; const packageJSONPath = join( cwd, 'build', 'node_modules', arbitraryPackageName, 'package.json' ); const {version} = await readJson(packageJSONPath); const isExperimentalVersion = version.indexOf('experimental') !== -1; if (version.indexOf('-') !== -1) { if (tags.includes('latest')) { if (isExperimentalVersion) { console.log( theme`{error Experimental release} {version ${version}} {error cannot be tagged as} {tag latest}` ); } else { console.log( theme`{error Next release} {version ${version}} {error cannot be tagged as} {tag latest}` ); } process.exit(1); } if (tags.includes('next') && isExperimentalVersion) { console.log( theme`{error Experimental release} {version ${version}} {error cannot be tagged as} {tag next}` ); process.exit(1); } if (tags.includes('experimental') && !isExperimentalVersion) { console.log( theme`{error Next release} {version ${version}} {error cannot be tagged as} {tag experimental}` ); process.exit(1); } } else { if (!tags.includes('latest')) { console.log( theme`{error Stable release} {version ${version}} {error must always be tagged as} {tag latest}` ); process.exit(1); } if (tags.includes('experimental')) { console.log( theme`{error Stable release} {version ${version}} {error cannot be tagged as} {tag experimental}` ); process.exit(1); } } }; module.exports = run;
29.46875
107
0.607491
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React; let ReactDOM; let ReactDOMSelection; let getModernOffsetsFromPoints; describe('ReactDOMSelection', () => { beforeEach(() => { React = require('react'); ReactDOM = require('react-dom'); ReactDOMSelection = require('react-dom-bindings/src/client/ReactDOMSelection'); ({getModernOffsetsFromPoints} = ReactDOMSelection); }); // Simple implementation to compare correctness. React's old implementation of // this logic used DOM Range objects and is available for manual testing at // https://gist.github.com/sophiebits/2e6d571f4f10f33b62ea138a6e9c265c. function simpleModernOffsetsFromPoints( outerNode, anchorNode, anchorOffset, focusNode, focusOffset, ) { let start; let end; let length = 0; function traverse(node) { if (node.nodeType === Node.TEXT_NODE) { if (node === anchorNode) { start = length + anchorOffset; } if (node === focusNode) { end = length + focusOffset; } length += node.nodeValue.length; return; } for (let i = 0; true; i++) { if (node === anchorNode && i === anchorOffset) { start = length; } if (node === focusNode && i === focusOffset) { end = length; } if (i === node.childNodes.length) { break; } const n = node.childNodes[i]; traverse(n); } } traverse(outerNode); if (start === null || end === null) { throw new Error('Provided anchor/focus nodes were outside of root.'); } return {start, end}; } // Complicated example derived from a real-world DOM tree. Has a bit of // everything. function getFixture() { return ReactDOM.render( <div> <div> <div> <div>xxxxxxxxxxxxxxxxxxxx</div> </div> x <div> <div> x <div> <div> <div>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</div> <div /> <div /> <div>xxxxxxxxxxxxxxxxxx</div> </div> </div> </div> </div> <div /> </div> <div> <div> <div> <div>xxxx</div> <div>xxxxxxxxxxxxxxxxxxx</div> </div> </div> <div>xxx</div> <div>xxxxx</div> <div>xxx</div> <div> <div> <div> <div>{['x', 'x', 'xxx']}</div> </div> </div> </div> </div> <div> <div>xxxxxx</div> </div> </div>, document.createElement('div'), ); } it('returns correctly for base case', () => { const node = document.createElement('div'); expect(getModernOffsetsFromPoints(node, node, 0, node, 0)).toEqual({ start: 0, end: 0, }); expect(simpleModernOffsetsFromPoints(node, node, 0, node, 0)).toEqual({ start: 0, end: 0, }); }); it('returns correctly for fuzz test', () => { const fixtureRoot = getFixture(); const allNodes = [fixtureRoot].concat( Array.from(fixtureRoot.querySelectorAll('*')), ); expect(allNodes.length).toBe(27); allNodes.slice().forEach(element => { // Add text nodes. allNodes.push( ...Array.from(element.childNodes).filter(n => n.nodeType === 3), ); }); expect(allNodes.length).toBe(41); function randomNode() { return allNodes[(Math.random() * allNodes.length) | 0]; } function randomOffset(node) { return ( (Math.random() * (1 + (node.nodeType === 3 ? node.nodeValue : node.childNodes).length)) | 0 ); } for (let i = 0; i < 2000; i++) { const anchorNode = randomNode(); const anchorOffset = randomOffset(anchorNode); const focusNode = randomNode(); const focusOffset = randomOffset(focusNode); const offsets1 = getModernOffsetsFromPoints( fixtureRoot, anchorNode, anchorOffset, focusNode, focusOffset, ); const offsets2 = simpleModernOffsetsFromPoints( fixtureRoot, anchorNode, anchorOffset, focusNode, focusOffset, ); if (JSON.stringify(offsets1) !== JSON.stringify(offsets2)) { throw new Error( JSON.stringify(offsets1) + ' does not match ' + JSON.stringify(offsets2) + ' for anchorNode=allNodes[' + allNodes.indexOf(anchorNode) + '], anchorOffset=' + anchorOffset + ', focusNode=allNodes[' + allNodes.indexOf(focusNode) + '], focusOffset=' + focusOffset, ); } } }); });
24.490099
83
0.523116
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 Point = $ReadOnly<{x: number, y: number}>; export type Size = $ReadOnly<{width: number, height: number}>; export type IntrinsicSize = { ...Size, // If content is this height or less, hide the scrollbar entirely, // so that it doesn't take up vertical space unnecessarily (e.g. for a single row of content). hideScrollBarIfLessThanHeight?: number, // The initial height should be the height of the content, or this, whichever is less. maxInitialHeight?: number, }; export type Rect = $ReadOnly<{origin: Point, size: Size}>; /** * Alternative representation of `Rect`. * A tuple of (`top`, `right`, `bottom`, `left`) coordinates. */ type Box = [number, number, number, number]; export const zeroPoint: Point = Object.freeze({x: 0, y: 0}); export const zeroSize: Size = Object.freeze({width: 0, height: 0}); export const zeroRect: Rect = Object.freeze({ origin: zeroPoint, size: zeroSize, }); export function pointEqualToPoint(point1: Point, point2: Point): boolean { return point1.x === point2.x && point1.y === point2.y; } export function sizeEqualToSize(size1: Size, size2: Size): boolean { return size1.width === size2.width && size1.height === size2.height; } export function rectEqualToRect(rect1: Rect, rect2: Rect): boolean { return ( pointEqualToPoint(rect1.origin, rect2.origin) && sizeEqualToSize(rect1.size, rect2.size) ); } export function sizeIsValid({width, height}: Size): boolean { return width >= 0 && height >= 0; } export function sizeIsEmpty({width, height}: Size): boolean { return width <= 0 || height <= 0; } function rectToBox(rect: Rect): Box { const top = rect.origin.y; const right = rect.origin.x + rect.size.width; const bottom = rect.origin.y + rect.size.height; const left = rect.origin.x; return [top, right, bottom, left]; } function boxToRect(box: Box): Rect { const [top, right, bottom, left] = box; return { origin: { x: left, y: top, }, size: { width: right - left, height: bottom - top, }, }; } export function rectIntersectsRect(rect1: Rect, rect2: Rect): boolean { if ( rect1.size.width === 0 || rect1.size.height === 0 || rect2.size.width === 0 || rect2.size.height === 0 ) { return false; } const [top1, right1, bottom1, left1] = rectToBox(rect1); const [top2, right2, bottom2, left2] = rectToBox(rect2); return !( right1 < left2 || right2 < left1 || bottom1 < top2 || bottom2 < top1 ); } /** * Returns the intersection of the 2 rectangles. * * Prerequisite: `rect1` must intersect with `rect2`. */ export function intersectionOfRects(rect1: Rect, rect2: Rect): Rect { const [top1, right1, bottom1, left1] = rectToBox(rect1); const [top2, right2, bottom2, left2] = rectToBox(rect2); return boxToRect([ Math.max(top1, top2), Math.min(right1, right2), Math.min(bottom1, bottom2), Math.max(left1, left2), ]); } export function rectContainsPoint({x, y}: Point, rect: Rect): boolean { const [top, right, bottom, left] = rectToBox(rect); return left <= x && x <= right && top <= y && y <= bottom; } /** * Returns the smallest rectangle that contains all provided rects. * * @returns Union of `rects`. If `rects` is empty, returns `zeroRect`. */ export function unionOfRects(...rects: Rect[]): Rect { if (rects.length === 0) { return zeroRect; } const [firstRect, ...remainingRects] = rects; const boxUnion = remainingRects .map(rectToBox) .reduce((intermediateUnion, nextBox): Box => { const [unionTop, unionRight, unionBottom, unionLeft] = intermediateUnion; const [nextTop, nextRight, nextBottom, nextLeft] = nextBox; return [ Math.min(unionTop, nextTop), Math.max(unionRight, nextRight), Math.max(unionBottom, nextBottom), Math.min(unionLeft, nextLeft), ]; }, rectToBox(firstRect)); return boxToRect(boxUnion); }
27.02027
96
0.656536
Mastering-Machine-Learning-for-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import { Fragment, useCallback, useContext, useLayoutEffect, useReducer, useRef, useState, } from 'react'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import Toggle from '../Toggle'; import ElementBadges from './ElementBadges'; import {OwnersListContext} from './OwnersListContext'; import {TreeDispatcherContext, TreeStateContext} from './TreeContext'; import {useIsOverflowing} from '../hooks'; import {StoreContext} from '../context'; import Tooltip from '../Components/reach-ui/tooltip'; import { Menu, MenuList, MenuButton, MenuItem, } from '../Components/reach-ui/menu-button'; import type {SerializedElement} from 'react-devtools-shared/src/frontend/types'; import styles from './OwnersStack.css'; type SelectOwner = (owner: SerializedElement | null) => void; type ACTION_UPDATE_OWNER_ID = { type: 'UPDATE_OWNER_ID', ownerID: number | null, owners: Array<SerializedElement>, }; type ACTION_UPDATE_SELECTED_INDEX = { type: 'UPDATE_SELECTED_INDEX', selectedIndex: number, }; type Action = ACTION_UPDATE_OWNER_ID | ACTION_UPDATE_SELECTED_INDEX; type State = { ownerID: number | null, owners: Array<SerializedElement>, selectedIndex: number, }; function dialogReducer(state: State, action: Action) { switch (action.type) { case 'UPDATE_OWNER_ID': const selectedIndex = action.owners.findIndex( owner => owner.id === action.ownerID, ); return { ownerID: action.ownerID, owners: action.owners, selectedIndex, }; case 'UPDATE_SELECTED_INDEX': return { ...state, selectedIndex: action.selectedIndex, }; default: throw new Error(`Invalid action "${action.type}"`); } } export default function OwnerStack(): React.Node { const read = useContext(OwnersListContext); const {ownerID} = useContext(TreeStateContext); const treeDispatch = useContext(TreeDispatcherContext); const [state, dispatch] = useReducer<State, State, Action>(dialogReducer, { ownerID: null, owners: [], selectedIndex: 0, }); // When an owner is selected, we either need to update the selected index, or we need to fetch a new list of owners. // We use a reducer here so that we can avoid fetching a new list unless the owner ID has actually changed. if (ownerID === null) { dispatch({ type: 'UPDATE_OWNER_ID', ownerID: null, owners: [], }); } else if (ownerID !== state.ownerID) { const isInStore = state.owners.findIndex(owner => owner.id === ownerID) >= 0; dispatch({ type: 'UPDATE_OWNER_ID', ownerID, owners: isInStore ? state.owners : read(ownerID) || [], }); } const {owners, selectedIndex} = state; const selectOwner = useCallback<SelectOwner>( (owner: SerializedElement | null) => { if (owner !== null) { const index = owners.indexOf(owner); dispatch({ type: 'UPDATE_SELECTED_INDEX', selectedIndex: index >= 0 ? index : 0, }); treeDispatch({type: 'SELECT_OWNER', payload: owner.id}); } else { dispatch({ type: 'UPDATE_SELECTED_INDEX', selectedIndex: 0, }); treeDispatch({type: 'RESET_OWNER_STACK'}); } }, [owners, treeDispatch], ); const [elementsTotalWidth, setElementsTotalWidth] = useState(0); const elementsBarRef = useRef<HTMLDivElement | null>(null); const isOverflowing = useIsOverflowing(elementsBarRef, elementsTotalWidth); const selectedOwner = owners[selectedIndex]; useLayoutEffect(() => { // If we're already overflowing, then we don't need to re-measure items. // That's because once the owners stack is open, it can only get larger (by drilling in). // A totally new stack can only be reached by exiting this mode and re-entering it. if (elementsBarRef.current === null || isOverflowing) { return () => {}; } let totalWidth = 0; for (let i = 0; i < owners.length; i++) { const element = elementsBarRef.current.children[i]; const computedStyle = getComputedStyle(element); totalWidth += element.offsetWidth + parseInt(computedStyle.marginLeft, 10) + parseInt(computedStyle.marginRight, 10); } setElementsTotalWidth(totalWidth); }, [elementsBarRef, isOverflowing, owners.length]); return ( <div className={styles.OwnerStack}> <div className={styles.Bar} ref={elementsBarRef}> {isOverflowing && ( <Fragment> <ElementsDropdown owners={owners} selectedIndex={selectedIndex} selectOwner={selectOwner} /> <BackToOwnerButton owners={owners} selectedIndex={selectedIndex} selectOwner={selectOwner} /> {selectedOwner != null && ( <ElementView owner={selectedOwner} isSelected={true} selectOwner={selectOwner} /> )} </Fragment> )} {!isOverflowing && owners.map((owner, index) => ( <ElementView key={index} owner={owner} isSelected={index === selectedIndex} selectOwner={selectOwner} /> ))} </div> <div className={styles.VRule} /> <Button onClick={() => selectOwner(null)} title="Back to tree view"> <ButtonIcon type="close" /> </Button> </div> ); } type ElementsDropdownProps = { owners: Array<SerializedElement>, selectedIndex: number, selectOwner: SelectOwner, }; function ElementsDropdown({owners, selectOwner}: ElementsDropdownProps) { const store = useContext(StoreContext); const menuItems = []; for (let index = owners.length - 1; index >= 0; index--) { const owner = owners[index]; const isInStore = store.containsElement(owner.id); menuItems.push( <MenuItem key={owner.id} className={`${styles.Component} ${isInStore ? '' : styles.NotInStore}`} onSelect={() => (isInStore ? selectOwner(owner) : null)}> {owner.displayName} <ElementBadges hocDisplayNames={owner.hocDisplayNames} compiledWithForget={owner.compiledWithForget} className={styles.BadgesBlock} /> </MenuItem>, ); } return ( <Menu> <MenuButton className={styles.MenuButton}> <Tooltip label="Open elements dropdown"> <span className={styles.MenuButtonContent} tabIndex={-1}> <ButtonIcon type="more" /> </span> </Tooltip> </MenuButton> <MenuList className={styles.Modal}>{menuItems}</MenuList> </Menu> ); } type ElementViewProps = { isSelected: boolean, owner: SerializedElement, selectOwner: SelectOwner, ... }; function ElementView({isSelected, owner, selectOwner}: ElementViewProps) { const store = useContext(StoreContext); const {displayName, hocDisplayNames, compiledWithForget} = owner; const isInStore = store.containsElement(owner.id); const handleChange = useCallback(() => { if (isInStore) { selectOwner(owner); } }, [isInStore, selectOwner, owner]); return ( <Toggle className={`${styles.Component} ${isInStore ? '' : styles.NotInStore}`} isChecked={isSelected} onChange={handleChange}> {displayName} <ElementBadges hocDisplayNames={hocDisplayNames} compiledWithForget={compiledWithForget} className={styles.BadgesBlock} /> </Toggle> ); } type BackToOwnerButtonProps = { owners: Array<SerializedElement>, selectedIndex: number, selectOwner: SelectOwner, }; function BackToOwnerButton({ owners, selectedIndex, selectOwner, }: BackToOwnerButtonProps) { const store = useContext(StoreContext); if (selectedIndex <= 0) { return null; } const owner = owners[selectedIndex - 1]; const isInStore = store.containsElement(owner.id); return ( <Button className={isInStore ? undefined : styles.NotInStore} onClick={() => (isInStore ? selectOwner(owner) : null)} title={`Up to ${owner.displayName || 'owner'}`}> <ButtonIcon type="previous" /> </Button> ); }
27.045902
118
0.628084
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 isArray from 'shared/isArray'; /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto<T>( current: ?(Array<T> | T), next: T | Array<T>, ): T | Array<T> { if (next == null) { throw new Error( 'accumulateInto(...): Accumulated items must not be null or undefined.', ); } if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (isArray(current)) { if (isArray(next)) { // $FlowFixMe[prop-missing] `isArray` does not ensure array is mutable // $FlowFixMe[method-unbinding] current.push.apply(current, next); return current; } // $FlowFixMe[prop-missing] `isArray` does not ensure array is mutable current.push(next); return current; } if (isArray(next)) { // A bit too dangerous to mutate `next`. /* $FlowFixMe[incompatible-return] unsound if `next` is `T` and `T` an array, * `isArray` might refine to the array element type of `T` */ return [current].concat(next); } return [current, next]; } export default accumulateInto;
27.609375
81
0.660656
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 chalk = require('chalk'); const fs = require('fs'); const path = require('path'); const mkdirp = require('mkdirp'); const inlinedHostConfigs = require('../shared/inlinedHostConfigs'); const flowVersion = require('../../package.json').devDependencies['flow-bin']; const configTemplate = fs .readFileSync(__dirname + '/config/flowconfig') .toString(); // stores all forks discovered during config generation const allForks = new Set(); // maps forked file to the base path containing it and it's forks (it's parent) const forkedFiles = new Map(); function findForks(file) { const basePath = path.join(file, '..'); const forksPath = path.join(basePath, 'forks'); const forks = fs.readdirSync(path.join('packages', forksPath)); forks.forEach(f => allForks.add('forks/' + f)); forkedFiles.set(file, basePath); return basePath; } function addFork(forks, renderer, file) { let basePath = forkedFiles.get(file); if (!basePath) { basePath = findForks(file); } const baseFilename = file.slice(basePath.length + 1); const parts = renderer.split('-'); while (parts.length) { const candidate = `forks/${baseFilename}.${parts.join('-')}.js`; if (allForks.has(candidate)) { forks.set(candidate, `${baseFilename}$$`); return; } parts.pop(); } throw new Error(`Cannot find fork for ${file} for renderer ${renderer}`); } function writeConfig( renderer, rendererInfo, isServerSupported, isFlightSupported, ) { const folder = __dirname + '/' + renderer; mkdirp.sync(folder); isFlightSupported = isFlightSupported === true || (isServerSupported && isFlightSupported !== false); const serverRenderer = isServerSupported ? renderer : 'custom'; const flightRenderer = isFlightSupported ? renderer : 'custom'; const ignoredPaths = []; inlinedHostConfigs.forEach(otherRenderer => { if (otherRenderer === rendererInfo) { return; } otherRenderer.paths.forEach(otherPath => { if (rendererInfo.paths.indexOf(otherPath) !== -1) { return; } ignoredPaths.push(`.*/packages/${otherPath}`); }); }); const forks = new Map(); addFork(forks, renderer, 'react-reconciler/src/ReactFiberConfig'); addFork(forks, serverRenderer, 'react-server/src/ReactServerStreamConfig'); addFork(forks, serverRenderer, 'react-server/src/ReactFizzConfig'); addFork(forks, flightRenderer, 'react-server/src/ReactFlightServerConfig'); addFork(forks, flightRenderer, 'react-client/src/ReactFlightClientConfig'); forks.set( 'react-devtools-shared/src/config/DevToolsFeatureFlags.default', 'react-devtools-feature-flags', ); allForks.forEach(fork => { if (!forks.has(fork)) { ignoredPaths.push(`.*/packages/.*/${fork}`); } }); let moduleMappings = ''; forks.forEach((source, target) => { moduleMappings += `module.name_mapper='${source.slice( source.lastIndexOf('/') + 1, )}' -> '${target}'\n`; }); const config = configTemplate .replace( '%CI_MAX_WORKERS%\n', // On CI, we seem to need to limit workers. process.env.CI ? 'server.max_workers=4\n' : '', ) .replace('%REACT_RENDERER_FLOW_OPTIONS%', moduleMappings.trim()) .replace('%REACT_RENDERER_FLOW_IGNORES%', ignoredPaths.join('\n')) .replace('%FLOW_VERSION%', flowVersion); const disclaimer = ` # ---------------------------------------------------------------# # NOTE: this file is generated. # # If you want to edit it, open ./scripts/flow/config/flowconfig. # # Then run Yarn for changes to take effect. # # ---------------------------------------------------------------# `.trim(); const configFile = folder + '/.flowconfig'; let oldConfig; try { oldConfig = fs.readFileSync(configFile).toString(); } catch (err) { oldConfig = null; } const newConfig = ` ${disclaimer} ${config} ${disclaimer} `.trim(); if (newConfig !== oldConfig) { fs.writeFileSync(configFile, newConfig); console.log(chalk.dim('Wrote a Flow config to ' + configFile)); } } // Write multiple configs in different folders // so that we can run those checks in parallel if we want. inlinedHostConfigs.forEach(rendererInfo => { if (rendererInfo.isFlowTyped) { writeConfig( rendererInfo.shortName, rendererInfo, rendererInfo.isServerSupported, rendererInfo.isFlightSupported, ); } });
28.436709
79
0.642581
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactNoopFlightServer';
21.727273
66
0.698795
null
/** * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {REACT_POSTPONE_TYPE} from 'shared/ReactSymbols'; declare class Postpone extends Error { $$typeof: symbol; } export type {Postpone}; export function postpone(reason: string): void { // eslint-disable-next-line react-internal/prod-error-codes const postponeInstance: Postpone = (new Error(reason): any); postponeInstance.$$typeof = REACT_POSTPONE_TYPE; throw postponeInstance; }
24.291667
66
0.729373
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ // This is a DevTools fork of ReactComponentStackFrame. // This fork enables DevTools to use the same "native" component stack format, // while still maintaining support for multiple renderer versions // (which use different values for ReactTypeOfWork). import type {LazyComponent} from 'react/src/ReactLazy'; import type {CurrentDispatcherRef} from './types'; import { FORWARD_REF_NUMBER, FORWARD_REF_SYMBOL_STRING, LAZY_NUMBER, LAZY_SYMBOL_STRING, MEMO_NUMBER, MEMO_SYMBOL_STRING, SUSPENSE_NUMBER, SUSPENSE_SYMBOL_STRING, SUSPENSE_LIST_NUMBER, SUSPENSE_LIST_SYMBOL_STRING, } from './ReactSymbols'; // The shared console patching code is DEV-only. // We can't use it since DevTools only ships production builds. import {disableLogs, reenableLogs} from './DevToolsConsolePatching'; let prefix; export function describeBuiltInComponentFrame( name: string, ownerFn: void | null | Function, ): string { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { const match = x.stack.trim().match(/\n( *(at )?)/); prefix = (match && match[1]) || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } let reentry = false; let componentFrameCache; if (__DEV__) { const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap<$FlowFixMe, string>(); } export function describeNativeComponentFrame( fn: Function, construct: boolean, currentDispatcherRef: CurrentDispatcherRef, ): string { // If something asked for a stack inside a fake render, it should get ignored. if (!fn || reentry) { return ''; } if (__DEV__) { const frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } let control; const previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe[incompatible-type] It does accept undefined. Error.prepareStackTrace = undefined; reentry = true; // Override the dispatcher so effects scheduled by this shallow render are thrown away. // // Note that unlike the code this was forked from (in ReactComponentStackFrame) // DevTools should override the dispatcher even when DevTools is compiled in production mode, // because the app itself may be in development mode and log errors/warnings. const previousDispatcher = currentDispatcherRef.current; currentDispatcherRef.current = null; disableLogs(); try { // This should throw. if (construct) { // Something should be setting the props in the constructor. const Fake = function () { throw Error(); }; // $FlowFixMe[prop-missing] Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); }, }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } // $FlowFixMe[prop-missing] found when upgrading Flow fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. const sampleLines = sample.stack.split('\n'); const controlLines = control.stack.split('\n'); let s = sampleLines.length - 1; let c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. const frame = '\n' + sampleLines[s].replace(' at new ', ' at '); if (__DEV__) { if (typeof fn === 'function') { componentFrameCache.set(fn, frame); } } // Return the line we found. return frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; Error.prepareStackTrace = previousPrepareStackTrace; currentDispatcherRef.current = previousDispatcher; reenableLogs(); } // Fallback to just using the name if we couldn't make it throw. const name = fn ? fn.displayName || fn.name : ''; const syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; if (__DEV__) { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } export function describeClassComponentFrame( ctor: Function, ownerFn: void | null | Function, currentDispatcherRef: CurrentDispatcherRef, ): string { return describeNativeComponentFrame(ctor, true, currentDispatcherRef); } export function describeFunctionComponentFrame( fn: Function, ownerFn: void | null | Function, currentDispatcherRef: CurrentDispatcherRef, ): string { return describeNativeComponentFrame(fn, false, currentDispatcherRef); } function shouldConstruct(Component: Function) { const prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } export function describeUnknownElementTypeFrameInDEV( type: any, ownerFn: void | null | Function, currentDispatcherRef: CurrentDispatcherRef, ): string { if (!__DEV__) { return ''; } if (type == null) { return ''; } if (typeof type === 'function') { return describeNativeComponentFrame( type, shouldConstruct(type), currentDispatcherRef, ); } if (typeof type === 'string') { return describeBuiltInComponentFrame(type, ownerFn); } switch (type) { case SUSPENSE_NUMBER: case SUSPENSE_SYMBOL_STRING: return describeBuiltInComponentFrame('Suspense', ownerFn); case SUSPENSE_LIST_NUMBER: case SUSPENSE_LIST_SYMBOL_STRING: return describeBuiltInComponentFrame('SuspenseList', ownerFn); } if (typeof type === 'object') { switch (type.$$typeof) { case FORWARD_REF_NUMBER: case FORWARD_REF_SYMBOL_STRING: return describeFunctionComponentFrame( type.render, ownerFn, currentDispatcherRef, ); case MEMO_NUMBER: case MEMO_SYMBOL_STRING: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV( type.type, ownerFn, currentDispatcherRef, ); case LAZY_NUMBER: case LAZY_SYMBOL_STRING: { const lazyComponent: LazyComponent<any, any> = (type: any); const payload = lazyComponent._payload; const init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV( init(payload), ownerFn, currentDispatcherRef, ); } catch (x) {} } } } return ''; }
31.602076
98
0.626473
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export { __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, act as unstable_act, Children, Component, Fragment, Profiler, PureComponent, StrictMode, Suspense, cloneElement, createContext, createElement, createFactory, createRef, use, forwardRef, isValidElement, lazy, memo, cache, unstable_useCacheRefresh, startTransition, useId, useCallback, useContext, useDebugValue, useDeferredValue, useEffect, useImperativeHandle, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useOptimistic, useRef, useState, useSyncExternalStore, useTransition, version, } from './src/React';
15.941176
66
0.71263
Python-Penetration-Testing-Cookbook
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ const {useMemo, useState} = require('react'); function Component(props) { const InnerComponent = useMemo(() => () => { const [state] = useState(0); return state; }); props.callback(InnerComponent); return null; }; module.exports = {Component};
19.391304
66
0.660256
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ // Renderers that don't support mutation // can re-export everything from this module. function shim(...args: any): empty { throw new Error( 'The current renderer does not support mutation. ' + 'This error is likely caused by a bug in React. ' + 'Please file an issue.', ); } // Mutation (when unsupported) export const supportsMutation = false; export const appendChild = shim; export const appendChildToContainer = shim; export const commitTextUpdate = shim; export const commitMount = shim; export const commitUpdate = shim; export const insertBefore = shim; export const insertInContainerBefore = shim; export const removeChild = shim; export const removeChildFromContainer = shim; export const resetTextContent = shim; export const hideInstance = shim; export const hideTextInstance = shim; export const unhideInstance = shim; export const unhideTextInstance = shim; export const clearContainer = shim;
28.868421
66
0.748677
Python-Penetration-Testing-for-Developers
'use strict'; module.exports = require('./client.browser');
14.5
45
0.688525
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 {Children} from 'react'; let didWarnSelectedSetOnOption = false; let didWarnInvalidChild = false; let didWarnInvalidInnerHTML = false; /** * Implements an <option> host component that warns when `selected` is set. */ export function validateOptionProps(element: Element, props: Object) { if (__DEV__) { // If a value is not provided, then the children must be simple. if (props.value == null) { if (typeof props.children === 'object' && props.children !== null) { Children.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { return; } if (!didWarnInvalidChild) { didWarnInvalidChild = true; console.error( 'Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.', ); } }); } else if (props.dangerouslySetInnerHTML != null) { if (!didWarnInvalidInnerHTML) { didWarnInvalidInnerHTML = true; console.error( 'Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.', ); } } } // TODO: Remove support for `selected` in <option>. if (props.selected != null && !didWarnSelectedSetOnOption) { console.error( 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.', ); didWarnSelectedSetOnOption = true; } } }
29.901639
85
0.586518
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * @typechecks * * Example usage: * <Wedge * outerRadius={50} * startAngle={0} * endAngle={360} * fill="blue" * /> * * Additional optional property: * (Int) innerRadius * */ 'use strict'; var assign = Object.assign; var PropTypes = require('prop-types'); var React = require('react'); var ReactART = require('react-art'); var createReactClass = require('create-react-class'); var Shape = ReactART.Shape; var Path = ReactART.Path; /** * Wedge is a React component for drawing circles, wedges and arcs. Like other * ReactART components, it must be used in a <Surface>. */ var Wedge = createReactClass({ displayName: 'Wedge', propTypes: { outerRadius: PropTypes.number.isRequired, startAngle: PropTypes.number.isRequired, endAngle: PropTypes.number.isRequired, innerRadius: PropTypes.number, }, circleRadians: Math.PI * 2, radiansPerDegree: Math.PI / 180, /** * _degreesToRadians(degrees) * * Helper function to convert degrees to radians * * @param {number} degrees * @return {number} */ _degreesToRadians: function _degreesToRadians(degrees) { if (degrees !== 0 && degrees % 360 === 0) { // 360, 720, etc. return this.circleRadians; } else { return (degrees * this.radiansPerDegree) % this.circleRadians; } }, /** * _createCirclePath(or, ir) * * Creates the ReactART Path for a complete circle. * * @param {number} or The outer radius of the circle * @param {number} ir The inner radius, greater than zero for a ring * @return {object} */ _createCirclePath: function _createCirclePath(or, ir) { var path = Path(); path .move(0, or) .arc(or * 2, 0, or) .arc(-or * 2, 0, or); if (ir) { path .move(or - ir, 0) .counterArc(ir * 2, 0, ir) .counterArc(-ir * 2, 0, ir); } path.close(); return path; }, /** * _createArcPath(sa, ea, ca, or, ir) * * Creates the ReactART Path for an arc or wedge. * * @param {number} startAngle The starting degrees relative to 12 o'clock * @param {number} endAngle The ending degrees relative to 12 o'clock * @param {number} or The outer radius in pixels * @param {number} ir The inner radius in pixels, greater than zero for an arc * @return {object} */ _createArcPath: function _createArcPath(startAngle, endAngle, or, ir) { var path = Path(); // angles in radians var sa = this._degreesToRadians(startAngle); var ea = this._degreesToRadians(endAngle); // central arc angle in radians var ca = sa > ea ? this.circleRadians - sa + ea : ea - sa; // cached sine and cosine values var ss = Math.sin(sa); var es = Math.sin(ea); var sc = Math.cos(sa); var ec = Math.cos(ea); // cached differences var ds = es - ss; var dc = ec - sc; var dr = ir - or; // if the angle is over pi radians (180 degrees) // we will need to let the drawing method know. var large = ca > Math.PI; // TODO (sema) Please improve theses comments to make the math // more understandable. // // Formula for a point on a circle at a specific angle with a center // at (0, 0): // x = radius * Math.sin(radians) // y = radius * Math.cos(radians) // // For our starting point, we offset the formula using the outer // radius because our origin is at (top, left). // In typical web layout fashion, we are drawing in quadrant IV // (a.k.a. Southeast) where x is positive and y is negative. // // The arguments for path.arc and path.counterArc used below are: // (endX, endY, radiusX, radiusY, largeAngle) path .move(or + or * ss, or - or * sc) // move to starting point .arc(or * ds, or * -dc, or, or, large) // outer arc .line(dr * es, dr * -ec); // width of arc or wedge if (ir) { path.counterArc(ir * -ds, ir * dc, ir, ir, large); // inner arc } return path; }, render: function render() { // angles are provided in degrees var startAngle = this.props.startAngle; var endAngle = this.props.endAngle; if (startAngle - endAngle === 0) { return null; } // radii are provided in pixels var innerRadius = this.props.innerRadius || 0; var outerRadius = this.props.outerRadius; // sorted radii var ir = Math.min(innerRadius, outerRadius); var or = Math.max(innerRadius, outerRadius); var path; if (endAngle >= startAngle + 360) { path = this._createCirclePath(or, ir); } else { path = this._createArcPath(startAngle, endAngle, or, ir); } return React.createElement(Shape, assign({}, this.props, {d: path})); }, }); module.exports = Wedge;
25.153439
80
0.619183
Ethical-Hacking-Scripts
import * as React from 'react'; import {useState} from 'react'; export default function Toggle() { const [show, setShow] = useState(false); return ( <> <h2>Toggle</h2> <div> <> <button onClick={() => setShow(s => !s)}>Show child</button> {show && ' '} {show && <Greeting>Hello</Greeting>} </> </div> </> ); } function Greeting({children}) { return <p>{children}</p>; }
18.652174
70
0.507761
Python-Penetration-Testing-Cookbook
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ const {useState} = require('react'); const {useCustom} = require('./useCustom'); function Component(props) { const [count] = useState(0); useCustom(); return count; } module.exports = {Component};
20.526316
66
0.681373
PenetrationTestingScripts
module.exports = require('./dist/hookNames');
22.5
45
0.717391
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ /* eslint-disable no-func-assign */ 'use strict'; let PropTypes; let React; let ReactNoop; let Suspense; let Scheduler; let act; let waitForAll; let assertLog; describe('memo', () => { beforeEach(() => { jest.resetModules(); PropTypes = require('prop-types'); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; ({Suspense} = React); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; assertLog = InternalTestUtils.assertLog; }); function Text(props) { Scheduler.log(props.text); return <span prop={props.text} />; } async function fakeImport(result) { return {default: result}; } it('warns when giving a ref (simple)', async () => { // This test lives outside sharedTests because the wrappers don't forward // refs properly, and they end up affecting the current owner which is used // by the warning (making the messages not line up). function App() { return null; } App = React.memo(App); function Outer() { return <App ref={() => {}} />; } ReactNoop.render(<Outer />); await expect(async () => await waitForAll([])).toErrorDev([ 'Warning: Function components cannot be given refs. Attempts to access ' + 'this ref will fail.', ]); }); it('warns when giving a ref (complex)', async () => { // defaultProps means this won't use SimpleMemoComponent (as of this writing) // SimpleMemoComponent is unobservable tho, so we can't check :) function App() { return null; } App.defaultProps = {}; App = React.memo(App); function Outer() { return <App ref={() => {}} />; } ReactNoop.render(<Outer />); await expect(async () => await waitForAll([])).toErrorDev([ 'App: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.', 'Warning: Function components cannot be given refs. Attempts to access ' + 'this ref will fail.', ]); }); // Tests should run against both the lazy and non-lazy versions of `memo`. // To make the tests work for both versions, we wrap the non-lazy version in // a lazy function component. sharedTests('normal', (...args) => { const Memo = React.memo(...args); function Indirection(props) { return <Memo {...props} />; } return React.lazy(() => fakeImport(Indirection)); }); sharedTests('lazy', (...args) => { const Memo = React.memo(...args); return React.lazy(() => fakeImport(Memo)); }); function sharedTests(label, memo) { describe(`${label}`, () => { it('bails out on props equality', async () => { function Counter({count}) { return <Text text={count} />; } Counter = memo(Counter); await act(() => ReactNoop.render( <Suspense fallback={<Text text="Loading..." />}> <Counter count={0} /> </Suspense>, ), ); assertLog(['Loading...', 0]); expect(ReactNoop).toMatchRenderedOutput(<span prop={0} />); // Should bail out because props have not changed ReactNoop.render( <Suspense> <Counter count={0} /> </Suspense>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop={0} />); // Should update because count prop changed ReactNoop.render( <Suspense> <Counter count={1} /> </Suspense>, ); await waitForAll([1]); expect(ReactNoop).toMatchRenderedOutput(<span prop={1} />); }); it("does not bail out if there's a context change", async () => { const CountContext = React.createContext(0); function readContext(Context) { const dispatcher = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .ReactCurrentDispatcher.current; return dispatcher.readContext(Context); } function Counter(props) { const count = readContext(CountContext); return <Text text={`${props.label}: ${count}`} />; } Counter = memo(Counter); class Parent extends React.Component { state = {count: 0}; render() { return ( <Suspense fallback={<Text text="Loading..." />}> <CountContext.Provider value={this.state.count}> <Counter label="Count" /> </CountContext.Provider> </Suspense> ); } } const parent = React.createRef(null); await act(() => ReactNoop.render(<Parent ref={parent} />)); assertLog(['Loading...', 'Count: 0']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />); // Should bail out because props have not changed ReactNoop.render(<Parent ref={parent} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 0" />); // Should update because there was a context change parent.current.setState({count: 1}); await waitForAll(['Count: 1']); expect(ReactNoop).toMatchRenderedOutput(<span prop="Count: 1" />); }); it('consistent behavior for reusing props object across different function component types', async () => { // This test is a bit complicated because it relates to an // implementation detail. We don't have strong guarantees that the props // object is referentially equal during updates where we can't bail // out anyway — like if the props are shallowly equal, but there's a // local state or context update in the same batch. // // However, as a principle, we should aim to make the behavior // consistent across different ways of memoizing a component. For // example, React.memo has a different internal Fiber layout if you pass // a normal function component (SimpleMemoComponent) versus if you pass // a different type like forwardRef (MemoComponent). But this is an // implementation detail. Wrapping a component in forwardRef (or // React.lazy, etc) shouldn't affect whether the props object is reused // during a bailout. // // So this test isn't primarily about asserting a particular behavior // for reusing the props object; it's about making sure the behavior // is consistent. const {useEffect, useState} = React; let setSimpleMemoStep; const SimpleMemo = React.memo(props => { const [step, setStep] = useState(0); setSimpleMemoStep = setStep; const prevProps = React.useRef(props); useEffect(() => { if (props !== prevProps.current) { prevProps.current = props; Scheduler.log('Props changed [SimpleMemo]'); } }, [props]); return <Text text={`SimpleMemo [${props.prop}${step}]`} />; }); let setComplexMemo; const ComplexMemo = React.memo( React.forwardRef((props, ref) => { const [step, setStep] = useState(0); setComplexMemo = setStep; const prevProps = React.useRef(props); useEffect(() => { if (props !== prevProps.current) { prevProps.current = props; Scheduler.log('Props changed [ComplexMemo]'); } }, [props]); return <Text text={`ComplexMemo [${props.prop}${step}]`} />; }), ); let setMemoWithIndirectionStep; const MemoWithIndirection = React.memo(props => { return <Indirection props={props} />; }); function Indirection({props}) { const [step, setStep] = useState(0); setMemoWithIndirectionStep = setStep; const prevProps = React.useRef(props); useEffect(() => { if (props !== prevProps.current) { prevProps.current = props; Scheduler.log('Props changed [MemoWithIndirection]'); } }, [props]); return <Text text={`MemoWithIndirection [${props.prop}${step}]`} />; } function setLocalUpdateOnChildren(step) { setSimpleMemoStep(step); setMemoWithIndirectionStep(step); setComplexMemo(step); } function App({prop}) { return ( <> <SimpleMemo prop={prop} /> <ComplexMemo prop={prop} /> <MemoWithIndirection prop={prop} /> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App prop="A" />); }); assertLog([ 'SimpleMemo [A0]', 'ComplexMemo [A0]', 'MemoWithIndirection [A0]', ]); // Demonstrate what happens when the props change await act(() => { root.render(<App prop="B" />); }); assertLog([ 'SimpleMemo [B0]', 'ComplexMemo [B0]', 'MemoWithIndirection [B0]', 'Props changed [SimpleMemo]', 'Props changed [ComplexMemo]', 'Props changed [MemoWithIndirection]', ]); // Demonstrate what happens when the prop object changes but there's a // bailout because all the individual props are the same. await act(() => { root.render(<App prop="B" />); }); // Nothing re-renders assertLog([]); // Demonstrate what happens when the prop object changes, it bails out // because all the props are the same, but we still render the // children because there's a local update in the same batch. await act(() => { root.render(<App prop="B" />); setLocalUpdateOnChildren(1); }); // The components should re-render with the new local state, but none // of the props objects should have changed assertLog([ 'SimpleMemo [B1]', 'ComplexMemo [B1]', 'MemoWithIndirection [B1]', ]); // Do the same thing again. We should still reuse the props object. await act(() => { root.render(<App prop="B" />); setLocalUpdateOnChildren(2); }); // The components should re-render with the new local state, but none // of the props objects should have changed assertLog([ 'SimpleMemo [B2]', 'ComplexMemo [B2]', 'MemoWithIndirection [B2]', ]); }); it('accepts custom comparison function', async () => { function Counter({count}) { return <Text text={count} />; } Counter = memo(Counter, (oldProps, newProps) => { Scheduler.log( `Old count: ${oldProps.count}, New count: ${newProps.count}`, ); return oldProps.count === newProps.count; }); await act(() => ReactNoop.render( <Suspense fallback={<Text text="Loading..." />}> <Counter count={0} /> </Suspense>, ), ); assertLog(['Loading...', 0]); expect(ReactNoop).toMatchRenderedOutput(<span prop={0} />); // Should bail out because props have not changed ReactNoop.render( <Suspense> <Counter count={0} /> </Suspense>, ); await waitForAll(['Old count: 0, New count: 0']); expect(ReactNoop).toMatchRenderedOutput(<span prop={0} />); // Should update because count prop changed ReactNoop.render( <Suspense> <Counter count={1} /> </Suspense>, ); await waitForAll(['Old count: 0, New count: 1', 1]); expect(ReactNoop).toMatchRenderedOutput(<span prop={1} />); }); it('supports non-pure class components', async () => { class CounterInner extends React.Component { static defaultProps = {suffix: '!'}; render() { return <Text text={this.props.count + String(this.props.suffix)} />; } } const Counter = memo(CounterInner); await act(() => ReactNoop.render( <Suspense fallback={<Text text="Loading..." />}> <Counter count={0} /> </Suspense>, ), ); assertLog(['Loading...', '0!']); expect(ReactNoop).toMatchRenderedOutput(<span prop="0!" />); // Should bail out because props have not changed ReactNoop.render( <Suspense> <Counter count={0} /> </Suspense>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="0!" />); // Should update because count prop changed ReactNoop.render( <Suspense> <Counter count={1} /> </Suspense>, ); await waitForAll(['1!']); expect(ReactNoop).toMatchRenderedOutput(<span prop="1!" />); }); it('supports defaultProps defined on the memo() return value', async () => { function Counter({a, b, c, d, e}) { return <Text text={a + b + c + d + e} />; } Counter.defaultProps = { a: 1, }; // Note! We intentionally use React.memo() rather than the injected memo(). // This tests a synchronous chain of React.memo() without lazy() in the middle. Counter = React.memo(Counter); Counter.defaultProps = { b: 2, }; Counter = React.memo(Counter); Counter = React.memo(Counter); // Layer without defaultProps Counter.defaultProps = { c: 3, }; Counter = React.memo(Counter); Counter.defaultProps = { d: 4, }; // The final layer uses memo() from test fixture (which might be lazy). Counter = memo(Counter); await expect(async () => { await act(() => { ReactNoop.render( <Suspense fallback={<Text text="Loading..." />}> <Counter e={5} /> </Suspense>, ); }); assertLog(['Loading...', 15]); }).toErrorDev([ 'Counter: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop={15} />); // Should bail out because props have not changed ReactNoop.render( <Suspense> <Counter e={5} /> </Suspense>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop={15} />); // Should update because count prop changed ReactNoop.render( <Suspense> <Counter e={10} /> </Suspense>, ); await waitForAll([20]); expect(ReactNoop).toMatchRenderedOutput(<span prop={20} />); }); it('warns if the first argument is undefined', () => { expect(() => memo()).toErrorDev( 'memo: The first argument must be a component. Instead ' + 'received: undefined', {withoutStack: true}, ); }); it('warns if the first argument is null', () => { expect(() => memo(null)).toErrorDev( 'memo: The first argument must be a component. Instead ' + 'received: null', {withoutStack: true}, ); }); it('validates propTypes declared on the inner component', async () => { function FnInner(props) { return props.inner; } FnInner.propTypes = {inner: PropTypes.number.isRequired}; const Fn = React.memo(FnInner); // Mount await expect(async () => { ReactNoop.render(<Fn inner="2" />); await waitForAll([]); }).toErrorDev( 'Invalid prop `inner` of type `string` supplied to `FnInner`, expected `number`.', ); // Update await expect(async () => { ReactNoop.render(<Fn inner={false} />); await waitForAll([]); }).toErrorDev( 'Invalid prop `inner` of type `boolean` supplied to `FnInner`, expected `number`.', ); }); it('validates propTypes declared on the outer component', async () => { function FnInner(props) { return props.outer; } const Fn = React.memo(FnInner); Fn.propTypes = {outer: PropTypes.number.isRequired}; // Mount await expect(async () => { ReactNoop.render(<Fn outer="3" />); await waitForAll([]); }).toErrorDev( // Outer props are checked in createElement 'Invalid prop `outer` of type `string` supplied to `FnInner`, expected `number`.', ); // Update await expect(async () => { ReactNoop.render(<Fn outer={false} />); await waitForAll([]); }).toErrorDev( // Outer props are checked in createElement 'Invalid prop `outer` of type `boolean` supplied to `FnInner`, expected `number`.', ); }); it('validates nested propTypes declarations', async () => { function Inner(props) { return props.inner + props.middle + props.outer; } Inner.propTypes = {inner: PropTypes.number.isRequired}; Inner.defaultProps = {inner: 0}; const Middle = React.memo(Inner); Middle.propTypes = {middle: PropTypes.number.isRequired}; Middle.defaultProps = {middle: 0}; const Outer = React.memo(Middle); Outer.propTypes = {outer: PropTypes.number.isRequired}; Outer.defaultProps = {outer: 0}; // No warning expected because defaultProps satisfy both. ReactNoop.render( <div> <Outer /> </div>, ); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'Inner: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.', ]); // Mount await expect(async () => { ReactNoop.render( <div> <Outer inner="2" middle="3" outer="4" /> </div>, ); await waitForAll([]); }).toErrorDev([ 'Invalid prop `outer` of type `string` supplied to `Inner`, expected `number`.', 'Invalid prop `middle` of type `string` supplied to `Inner`, expected `number`.', 'Invalid prop `inner` of type `string` supplied to `Inner`, expected `number`.', ]); // Update await expect(async () => { ReactNoop.render( <div> <Outer inner={false} middle={false} outer={false} /> </div>, ); await waitForAll([]); }).toErrorDev([ 'Invalid prop `outer` of type `boolean` supplied to `Inner`, expected `number`.', 'Invalid prop `middle` of type `boolean` supplied to `Inner`, expected `number`.', 'Invalid prop `inner` of type `boolean` supplied to `Inner`, expected `number`.', ]); }); it('does not drop lower priority state updates when bailing out at higher pri (simple)', async () => { const {useState} = React; let setCounter; const Counter = memo(() => { const [counter, _setCounter] = useState(0); setCounter = _setCounter; return counter; }); function App() { return ( <Suspense fallback="Loading..."> <Counter /> </Suspense> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); expect(root).toMatchRenderedOutput('0'); await act(() => { setCounter(1); ReactNoop.discreteUpdates(() => { root.render(<App />); }); }); expect(root).toMatchRenderedOutput('1'); }); it('does not drop lower priority state updates when bailing out at higher pri (complex)', async () => { const {useState} = React; let setCounter; const Counter = memo( () => { const [counter, _setCounter] = useState(0); setCounter = _setCounter; return counter; }, (a, b) => a.complexProp.val === b.complexProp.val, ); function App() { return ( <Suspense fallback="Loading..."> <Counter complexProp={{val: 1}} /> </Suspense> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); expect(root).toMatchRenderedOutput('0'); await act(() => { setCounter(1); ReactNoop.discreteUpdates(() => { root.render(<App />); }); }); expect(root).toMatchRenderedOutput('1'); }); }); it('should fall back to showing something meaningful if no displayName or name are present', () => { const MemoComponent = React.memo(props => <div {...props} />); MemoComponent.propTypes = { required: PropTypes.string.isRequired, }; expect(() => ReactNoop.render(<MemoComponent optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`Memo`, 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 inner component in warnings', () => { function Component(props) { return <div {...props} />; } Component.displayName = 'Inner'; const MemoComponent = React.memo(Component); MemoComponent.propTypes = { required: PropTypes.string.isRequired, }; expect(() => ReactNoop.render(<MemoComponent optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`Inner`, but its value is `undefined`.\n' + ' in Inner (at **)', ); }); it('should honor a displayName if set on the memo wrapper in warnings', () => { const MemoComponent = React.memo(function Component(props) { return <div {...props} />; }); MemoComponent.displayName = 'Outer'; MemoComponent.propTypes = { required: PropTypes.string.isRequired, }; expect(() => ReactNoop.render(<MemoComponent optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`Outer`, but its value is `undefined`.\n' + ' in Component (at **)', ); }); it('should pass displayName to an anonymous inner component so it shows up in component stacks', () => { const MemoComponent = React.memo(props => { return <div {...props} />; }); MemoComponent.displayName = 'Memo'; MemoComponent.propTypes = { required: PropTypes.string.isRequired, }; expect(() => ReactNoop.render(<MemoComponent optional="foo" />), ).toErrorDev( 'Warning: Failed prop type: The prop `required` is marked as required in ' + '`Memo`, but its value is `undefined`.\n' + ' in Memo (at **)', ); }); it('should honor a outer displayName when wrapped component and memo component set displayName at the same time.', () => { function Component(props) { return <div {...props} />; } Component.displayName = 'Inner'; const MemoComponent = React.memo(Component); MemoComponent.displayName = 'Outer'; MemoComponent.propTypes = { required: PropTypes.string.isRequired, }; expect(() => ReactNoop.render(<MemoComponent 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 **)', ); }); } });
32.312583
153
0.546481
cybersecurity-penetration-testing
/** @flow */ // This test harness mounts each test app as a separate root to test multi-root applications. import * as React from 'react'; import * as ReactDOM from 'react-dom'; import {createRoot} from 'react-dom/client'; import ListApp from '../e2e-apps/ListApp'; function mountApp(App: () => React$Node) { const container = document.createElement('div'); ((document.body: any): HTMLBodyElement).appendChild(container); const root = createRoot(container); root.render(<App />); } function mountTestApp() { mountApp(ListApp); } mountTestApp(); // ReactDOM Test Selector APIs used by Playwright e2e tests // If they don't exist, we mock them window.parent.REACT_DOM_APP = { createTestNameSelector: name => `[data-testname="${name}"]`, findAllNodes: (container, nodes) => container.querySelectorAll(nodes.join(' ')), ...ReactDOM, };
25.875
93
0.701979
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useTheme; exports.ThemeContext = void 0; 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 ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright'); exports.ThemeContext = ThemeContext; function useTheme() { const theme = (0, _react.useContext)(ThemeContext); (0, _react.useDebugValue)(theme); return theme; } //# sourceMappingURL=useTheme.js.map?foo=bar&param=some_value
23.851852
70
0.701493
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; import {defaultBrowserChromeSize} from '../constants'; import { createEventTarget, describeWithPointerEvent, testWithPointerType, resetActivePointers, } from '../index'; /** * Unit test helpers */ describeWithPointerEvent('describeWithPointerEvent', pointerEvent => { test('provides boolean to tests', () => { expect(pointerEvent).toMatchSnapshot(); }); testWithPointerType('testWithPointerType', pointerType => { expect(pointerType).toMatchSnapshot(); }); }); /** * createEventTarget */ describe('createEventTarget', () => { let node; beforeEach(() => { node = document.createElement('div'); }); afterEach(() => { node = null; resetActivePointers(); }); test('returns expected API', () => { const target = createEventTarget(node); expect(target.node).toEqual(node); expect(Object.keys(target)).toMatchInlineSnapshot(` [ "node", "blur", "click", "focus", "keydown", "keyup", "scroll", "virtualclick", "contextmenu", "pointercancel", "pointerdown", "pointerhover", "pointermove", "pointerenter", "pointerexit", "pointerup", "tap", "setBoundingClientRect", ] `); }); /** * Simple events */ describe('.blur()', () => { test('default', () => { const target = createEventTarget(node); node.addEventListener('blur', e => { expect(e.relatedTarget).toMatchInlineSnapshot(`null`); }); target.blur(); }); test('custom payload', () => { const target = createEventTarget(node); node.addEventListener('blur', e => { expect(e.relatedTarget).toMatchInlineSnapshot(`null`); }); target.blur(); }); }); describe('.click()', () => { test('default', () => { const target = createEventTarget(node); node.addEventListener('click', e => { expect(e.altKey).toEqual(false); expect(e.button).toEqual(0); expect(e.buttons).toEqual(0); expect(e.clientX).toEqual(0); expect(e.clientY).toEqual(0); expect(e.ctrlKey).toEqual(false); expect(e.detail).toEqual(1); expect(typeof e.getModifierState).toEqual('function'); expect(e.metaKey).toEqual(false); expect(e.movementX).toEqual(0); expect(e.movementY).toEqual(0); expect(e.offsetX).toEqual(0); expect(e.offsetY).toEqual(0); expect(e.pageX).toEqual(0); expect(e.pageY).toEqual(0); expect(typeof e.preventDefault).toEqual('function'); expect(e.screenX).toEqual(0); expect(e.screenY).toEqual(defaultBrowserChromeSize); expect(e.shiftKey).toEqual(false); expect(typeof e.timeStamp).toEqual('number'); }); target.click(); }); test('custom payload', () => { const target = createEventTarget(node); node.addEventListener('click', e => { expect(e.altKey).toEqual(true); expect(e.button).toEqual(1); expect(e.buttons).toEqual(4); expect(e.clientX).toEqual(10); expect(e.clientY).toEqual(20); expect(e.ctrlKey).toEqual(true); expect(e.metaKey).toEqual(true); expect(e.movementX).toEqual(1); expect(e.movementY).toEqual(2); expect(e.offsetX).toEqual(5); expect(e.offsetY).toEqual(5); expect(e.pageX).toEqual(50); expect(e.pageY).toEqual(50); expect(e.screenX).toEqual(10); expect(e.screenY).toEqual(20 + defaultBrowserChromeSize); expect(e.shiftKey).toEqual(true); }); target.click({ altKey: true, button: 1, buttons: 4, x: 10, y: 20, ctrlKey: true, metaKey: true, movementX: 1, movementY: 2, offsetX: 5, offsetY: 5, pageX: 50, pageY: 50, shiftKey: true, }); }); }); describe('.focus()', () => { test('default', () => { const target = createEventTarget(node); node.addEventListener('focus', e => { expect(e.relatedTarget).toMatchInlineSnapshot(`null`); }); target.blur(); }); test('custom payload', () => { const target = createEventTarget(node); node.addEventListener('focus', e => { expect(e.relatedTarget).toMatchInlineSnapshot(`null`); }); target.blur(); }); }); describe('.keydown()', () => { test('default', () => { const target = createEventTarget(node); node.addEventListener('keydown', e => { expect(e.altKey).toEqual(false); expect(e.ctrlKey).toEqual(false); expect(typeof e.getModifierState).toEqual('function'); expect(e.key).toEqual(''); expect(e.metaKey).toEqual(false); expect(typeof e.preventDefault).toEqual('function'); expect(e.shiftKey).toEqual(false); expect(typeof e.timeStamp).toEqual('number'); }); target.keydown(); }); test('custom payload', () => { const target = createEventTarget(node); node.addEventListener('keydown', e => { expect(e.altKey).toEqual(true); expect(e.ctrlKey).toEqual(true); expect(e.isComposing).toEqual(true); expect(e.key).toEqual('Enter'); expect(e.metaKey).toEqual(true); expect(e.shiftKey).toEqual(true); }); target.keydown({ altKey: true, ctrlKey: true, isComposing: true, key: 'Enter', metaKey: true, shiftKey: true, }); }); }); describe('.keyup()', () => { test('default', () => { const target = createEventTarget(node); node.addEventListener('keyup', e => { expect(e.altKey).toEqual(false); expect(e.ctrlKey).toEqual(false); expect(typeof e.getModifierState).toEqual('function'); expect(e.key).toEqual(''); expect(e.metaKey).toEqual(false); expect(typeof e.preventDefault).toEqual('function'); expect(e.shiftKey).toEqual(false); expect(typeof e.timeStamp).toEqual('number'); }); target.keydown(); }); test('custom payload', () => { const target = createEventTarget(node); node.addEventListener('keyup', e => { expect(e.altKey).toEqual(true); expect(e.ctrlKey).toEqual(true); expect(e.isComposing).toEqual(true); expect(e.key).toEqual('Enter'); expect(e.metaKey).toEqual(true); expect(e.shiftKey).toEqual(true); }); target.keyup({ altKey: true, ctrlKey: true, isComposing: true, key: 'Enter', metaKey: true, shiftKey: true, }); }); }); describe('.scroll()', () => { test('default', () => { const target = createEventTarget(node); node.addEventListener('scroll', e => { expect(e.type).toEqual('scroll'); }); target.scroll(); }); }); describe('.virtualclick()', () => { test('default', () => { const target = createEventTarget(node); node.addEventListener('click', e => { expect(e.altKey).toEqual(false); expect(e.button).toEqual(0); expect(e.buttons).toEqual(0); expect(e.clientX).toEqual(0); expect(e.clientY).toEqual(0); expect(e.ctrlKey).toEqual(false); expect(e.detail).toEqual(0); expect(typeof e.getModifierState).toEqual('function'); expect(e.metaKey).toEqual(false); expect(e.movementX).toEqual(0); expect(e.movementY).toEqual(0); expect(e.offsetX).toEqual(0); expect(e.offsetY).toEqual(0); expect(e.pageX).toEqual(0); expect(e.pageY).toEqual(0); expect(typeof e.preventDefault).toEqual('function'); expect(e.screenX).toEqual(0); expect(e.screenY).toEqual(0); expect(e.shiftKey).toEqual(false); expect(typeof e.timeStamp).toEqual('number'); }); target.virtualclick(); }); test('custom payload', () => { const target = createEventTarget(node); node.addEventListener('click', e => { // expect most of the custom payload to be ignored expect(e.altKey).toEqual(true); expect(e.button).toEqual(1); expect(e.buttons).toEqual(0); expect(e.clientX).toEqual(0); expect(e.clientY).toEqual(0); expect(e.ctrlKey).toEqual(true); expect(e.detail).toEqual(0); expect(e.metaKey).toEqual(true); expect(e.pageX).toEqual(0); expect(e.pageY).toEqual(0); expect(e.screenX).toEqual(0); expect(e.screenY).toEqual(0); expect(e.shiftKey).toEqual(true); }); target.virtualclick({ altKey: true, button: 1, buttons: 4, x: 10, y: 20, ctrlKey: true, metaKey: true, pageX: 50, pageY: 50, shiftKey: true, }); }); }); /** * Complex event sequences * * ...coming soon */ /** * Other APIs */ test('.setBoundingClientRect()', () => { const target = createEventTarget(node); expect(node.getBoundingClientRect()).toMatchInlineSnapshot(` { "bottom": 0, "height": 0, "left": 0, "right": 0, "top": 0, "width": 0, "x": 0, "y": 0, } `); target.setBoundingClientRect({x: 10, y: 20, width: 100, height: 200}); expect(node.getBoundingClientRect()).toMatchInlineSnapshot(` { "bottom": 220, "height": 200, "left": 10, "right": 110, "top": 20, "width": 100, } `); }); });
26.335165
74
0.557543
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 { ReactContext, ReactProviderType, StartTransitionOptions, } from 'shared/ReactTypes'; import type { Fiber, Dispatcher as DispatcherType, } from 'react-reconciler/src/ReactInternalTypes'; import ErrorStackParser from 'error-stack-parser'; import assign from 'shared/assign'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import { FunctionComponent, SimpleMemoComponent, ContextProvider, ForwardRef, } from 'react-reconciler/src/ReactWorkTags'; import {REACT_MEMO_CACHE_SENTINEL} from 'shared/ReactSymbols'; type CurrentDispatcherRef = typeof ReactSharedInternals.ReactCurrentDispatcher; // Used to track hooks called during a render type HookLogEntry = { primitive: string, stackError: Error, value: mixed, }; let hookLog: Array<HookLogEntry> = []; // Primitives type BasicStateAction<S> = (S => S) | S; type Dispatch<A> = A => void; let primitiveStackCache: null | Map<string, Array<any>> = null; type Hook = { memoizedState: any, next: Hook | null, }; function getPrimitiveStackCache(): Map<string, Array<any>> { // This initializes a cache of all primitive hooks so that the top // most stack frames added by calling the primitive hook can be removed. if (primitiveStackCache === null) { const cache = new Map<string, Array<any>>(); let readHookLog; try { // Use all hooks here to add them to the hook log. Dispatcher.useContext(({_currentValue: null}: any)); Dispatcher.useState(null); Dispatcher.useReducer((s: mixed, a: mixed) => s, null); Dispatcher.useRef(null); if (typeof Dispatcher.useCacheRefresh === 'function') { // This type check is for Flow only. Dispatcher.useCacheRefresh(); } Dispatcher.useLayoutEffect(() => {}); Dispatcher.useInsertionEffect(() => {}); Dispatcher.useEffect(() => {}); Dispatcher.useImperativeHandle(undefined, () => null); Dispatcher.useDebugValue(null); Dispatcher.useCallback(() => {}); Dispatcher.useMemo(() => null); if (typeof Dispatcher.useMemoCache === 'function') { // This type check is for Flow only. Dispatcher.useMemoCache(0); } } finally { readHookLog = hookLog; hookLog = []; } for (let i = 0; i < readHookLog.length; i++) { const hook = readHookLog[i]; cache.set(hook.primitive, ErrorStackParser.parse(hook.stackError)); } primitiveStackCache = cache; } return primitiveStackCache; } let currentFiber: null | Fiber = null; let currentHook: null | Hook = null; function nextHook(): null | Hook { const hook = currentHook; if (hook !== null) { currentHook = hook.next; } return hook; } function readContext<T>(context: ReactContext<T>): T { // For now we don't expose readContext usage in the hooks debugging info. return context._currentValue; } function use<T>(): T { // TODO: What should this do if it receives an unresolved promise? throw new Error( 'Support for `use` not yet implemented in react-debug-tools.', ); } function useContext<T>(context: ReactContext<T>): T { hookLog.push({ primitive: 'Context', stackError: new Error(), value: context._currentValue, }); return context._currentValue; } function useState<S>( initialState: (() => S) | S, ): [S, Dispatch<BasicStateAction<S>>] { const hook = nextHook(); const state: S = hook !== null ? hook.memoizedState : typeof initialState === 'function' ? // $FlowFixMe[incompatible-use]: Flow doesn't like mixed types initialState() : initialState; hookLog.push({primitive: 'State', stackError: new Error(), value: state}); return [state, (action: BasicStateAction<S>) => {}]; } function useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: I => S, ): [S, Dispatch<A>] { const hook = nextHook(); let state; if (hook !== null) { state = hook.memoizedState; } else { state = init !== undefined ? init(initialArg) : ((initialArg: any): S); } hookLog.push({ primitive: 'Reducer', stackError: new Error(), value: state, }); return [state, (action: A) => {}]; } function useRef<T>(initialValue: T): {current: T} { const hook = nextHook(); const ref = hook !== null ? hook.memoizedState : {current: initialValue}; hookLog.push({ primitive: 'Ref', stackError: new Error(), value: ref.current, }); return ref; } function useCacheRefresh(): () => void { const hook = nextHook(); hookLog.push({ primitive: 'CacheRefresh', stackError: new Error(), value: hook !== null ? hook.memoizedState : function refresh() {}, }); return () => {}; } function useLayoutEffect( create: () => (() => void) | void, inputs: Array<mixed> | void | null, ): void { nextHook(); hookLog.push({ primitive: 'LayoutEffect', stackError: new Error(), value: create, }); } function useInsertionEffect( create: () => mixed, inputs: Array<mixed> | void | null, ): void { nextHook(); hookLog.push({ primitive: 'InsertionEffect', stackError: new Error(), value: create, }); } function useEffect( create: () => (() => void) | void, inputs: Array<mixed> | void | null, ): void { nextHook(); hookLog.push({primitive: 'Effect', stackError: new Error(), value: create}); } function useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, inputs: Array<mixed> | void | null, ): void { nextHook(); // We don't actually store the instance anywhere if there is no ref callback // and if there is a ref callback it might not store it but if it does we // have no way of knowing where. So let's only enable introspection of the // ref itself if it is using the object form. let instance: ?T = undefined; if (ref !== null && typeof ref === 'object') { instance = ref.current; } hookLog.push({ primitive: 'ImperativeHandle', stackError: new Error(), value: instance, }); } function useDebugValue(value: any, formatterFn: ?(value: any) => any) { hookLog.push({ primitive: 'DebugValue', stackError: new Error(), value: typeof formatterFn === 'function' ? formatterFn(value) : value, }); } function useCallback<T>(callback: T, inputs: Array<mixed> | void | null): T { const hook = nextHook(); hookLog.push({ primitive: 'Callback', stackError: new Error(), value: hook !== null ? hook.memoizedState[0] : callback, }); return callback; } function useMemo<T>( nextCreate: () => T, inputs: Array<mixed> | void | null, ): T { const hook = nextHook(); const value = hook !== null ? hook.memoizedState[0] : nextCreate(); hookLog.push({primitive: 'Memo', stackError: new Error(), value}); return value; } function useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T { // useSyncExternalStore() composes multiple hooks internally. // Advance the current hook index the same number of times // so that subsequent hooks have the right memoized state. nextHook(); // SyncExternalStore nextHook(); // Effect const value = getSnapshot(); hookLog.push({ primitive: 'SyncExternalStore', stackError: new Error(), value, }); return value; } function useTransition(): [ boolean, (callback: () => void, options?: StartTransitionOptions) => void, ] { // useTransition() composes multiple hooks internally. // Advance the current hook index the same number of times // so that subsequent hooks have the right memoized state. nextHook(); // State nextHook(); // Callback hookLog.push({ primitive: 'Transition', stackError: new Error(), value: undefined, }); return [false, callback => {}]; } function useDeferredValue<T>(value: T, initialValue?: T): T { const hook = nextHook(); hookLog.push({ primitive: 'DeferredValue', stackError: new Error(), value: hook !== null ? hook.memoizedState : value, }); return value; } function useId(): string { const hook = nextHook(); const id = hook !== null ? hook.memoizedState : ''; hookLog.push({ primitive: 'Id', stackError: new Error(), value: id, }); return id; } // useMemoCache is an implementation detail of Forget's memoization // it should not be called directly in user-generated code function useMemoCache(size: number): Array<any> { const fiber = currentFiber; // Don't throw, in case this is called from getPrimitiveStackCache if (fiber == null) { return []; } // $FlowFixMe[incompatible-use]: updateQueue is mixed const memoCache = fiber.updateQueue?.memoCache; if (memoCache == null) { return []; } let data = memoCache.data[memoCache.index]; if (data === undefined) { data = memoCache.data[memoCache.index] = new Array(size); for (let i = 0; i < size; i++) { data[i] = REACT_MEMO_CACHE_SENTINEL; } } // We don't write anything to hookLog on purpose, so this hook remains invisible to users. memoCache.index++; return data; } const Dispatcher: DispatcherType = { use, readContext, useCacheRefresh, useCallback, useContext, useEffect, useImperativeHandle, useDebugValue, useLayoutEffect, useInsertionEffect, useMemo, useMemoCache, useReducer, useRef, useState, useTransition, useSyncExternalStore, useDeferredValue, useId, }; // create a proxy to throw a custom error // in case future versions of React adds more hooks const DispatcherProxyHandler = { get(target: DispatcherType, prop: string) { if (target.hasOwnProperty(prop)) { return target[prop]; } const error = new Error('Missing method in Dispatcher: ' + prop); // Note: This error name needs to stay in sync with react-devtools-shared // TODO: refactor this if we ever combine the devtools and debug tools packages error.name = 'ReactDebugToolsUnsupportedHookError'; throw error; }, }; // `Proxy` may not exist on some platforms const DispatcherProxy = typeof Proxy === 'undefined' ? Dispatcher : new Proxy(Dispatcher, DispatcherProxyHandler); // Inspect export type HookSource = { lineNumber: number | null, columnNumber: number | null, fileName: string | null, functionName: string | null, }; export type HooksNode = { id: number | null, isStateEditable: boolean, name: string, value: mixed, subHooks: Array<HooksNode>, hookSource?: HookSource, }; export type HooksTree = Array<HooksNode>; // Don't assume // // We can't assume that stack frames are nth steps away from anything. // E.g. we can't assume that the root call shares all frames with the stack // of a hook call. A simple way to demonstrate this is wrapping `new Error()` // in a wrapper constructor like a polyfill. That'll add an extra frame. // Similar things can happen with the call to the dispatcher. The top frame // may not be the primitive. Likewise the primitive can have fewer stack frames // such as when a call to useState got inlined to use dispatcher.useState. // // We also can't assume that the last frame of the root call is the same // frame as the last frame of the hook call because long stack traces can be // truncated to a stack trace limit. let mostLikelyAncestorIndex = 0; function findSharedIndex(hookStack: any, rootStack: any, rootIndex: number) { const source = rootStack[rootIndex].source; hookSearch: for (let i = 0; i < hookStack.length; i++) { if (hookStack[i].source === source) { // This looks like a match. Validate that the rest of both stack match up. for ( let a = rootIndex + 1, b = i + 1; a < rootStack.length && b < hookStack.length; a++, b++ ) { if (hookStack[b].source !== rootStack[a].source) { // If not, give up and try a different match. continue hookSearch; } } return i; } } return -1; } function findCommonAncestorIndex(rootStack: any, hookStack: any) { let rootIndex = findSharedIndex( hookStack, rootStack, mostLikelyAncestorIndex, ); if (rootIndex !== -1) { return rootIndex; } // If the most likely one wasn't a hit, try any other frame to see if it is shared. // If that takes more than 5 frames, something probably went wrong. for (let i = 0; i < rootStack.length && i < 5; i++) { rootIndex = findSharedIndex(hookStack, rootStack, i); if (rootIndex !== -1) { mostLikelyAncestorIndex = i; return rootIndex; } } return -1; } function isReactWrapper(functionName: any, primitiveName: string) { if (!functionName) { return false; } const expectedPrimitiveName = 'use' + primitiveName; if (functionName.length < expectedPrimitiveName.length) { return false; } return ( functionName.lastIndexOf(expectedPrimitiveName) === functionName.length - expectedPrimitiveName.length ); } function findPrimitiveIndex(hookStack: any, hook: HookLogEntry) { const stackCache = getPrimitiveStackCache(); const primitiveStack = stackCache.get(hook.primitive); if (primitiveStack === undefined) { return -1; } for (let i = 0; i < primitiveStack.length && i < hookStack.length; i++) { if (primitiveStack[i].source !== hookStack[i].source) { // If the next two frames are functions called `useX` then we assume that they're part of the // wrappers that the React packager or other packages adds around the dispatcher. if ( i < hookStack.length - 1 && isReactWrapper(hookStack[i].functionName, hook.primitive) ) { i++; } if ( i < hookStack.length - 1 && isReactWrapper(hookStack[i].functionName, hook.primitive) ) { i++; } return i; } } return -1; } function parseTrimmedStack(rootStack: any, hook: HookLogEntry) { // Get the stack trace between the primitive hook function and // the root function call. I.e. the stack frames of custom hooks. const hookStack = ErrorStackParser.parse(hook.stackError); const rootIndex = findCommonAncestorIndex(rootStack, hookStack); const primitiveIndex = findPrimitiveIndex(hookStack, hook); if ( rootIndex === -1 || primitiveIndex === -1 || rootIndex - primitiveIndex < 2 ) { // Something went wrong. Give up. return null; } return hookStack.slice(primitiveIndex, rootIndex - 1); } function parseCustomHookName(functionName: void | string): string { if (!functionName) { return ''; } let startIndex = functionName.lastIndexOf('.'); if (startIndex === -1) { startIndex = 0; } if (functionName.slice(startIndex, startIndex + 3) === 'use') { startIndex += 3; } return functionName.slice(startIndex); } function buildTree( rootStack: any, readHookLog: Array<HookLogEntry>, includeHooksSource: boolean, ): HooksTree { const rootChildren: Array<HooksNode> = []; let prevStack = null; let levelChildren = rootChildren; let nativeHookID = 0; const stackOfChildren = []; for (let i = 0; i < readHookLog.length; i++) { const hook = readHookLog[i]; const stack = parseTrimmedStack(rootStack, hook); if (stack !== null) { // Note: The indices 0 <= n < length-1 will contain the names. // The indices 1 <= n < length will contain the source locations. // That's why we get the name from n - 1 and don't check the source // of index 0. let commonSteps = 0; if (prevStack !== null) { // Compare the current level's stack to the new stack. while (commonSteps < stack.length && commonSteps < prevStack.length) { const stackSource = stack[stack.length - commonSteps - 1].source; const prevSource = prevStack[prevStack.length - commonSteps - 1].source; if (stackSource !== prevSource) { break; } commonSteps++; } // Pop back the stack as many steps as were not common. for (let j = prevStack.length - 1; j > commonSteps; j--) { levelChildren = stackOfChildren.pop(); } } // The remaining part of the new stack are custom hooks. Push them // to the tree. for (let j = stack.length - commonSteps - 1; j >= 1; j--) { const children: Array<HooksNode> = []; const stackFrame = stack[j]; const levelChild: HooksNode = { id: null, isStateEditable: false, name: parseCustomHookName(stack[j - 1].functionName), value: undefined, subHooks: children, }; if (includeHooksSource) { levelChild.hookSource = { lineNumber: stackFrame.lineNumber, columnNumber: stackFrame.columnNumber, functionName: stackFrame.functionName, fileName: stackFrame.fileName, }; } levelChildren.push(levelChild); stackOfChildren.push(levelChildren); levelChildren = children; } prevStack = stack; } const {primitive} = hook; // For now, the "id" of stateful hooks is just the stateful hook index. // Custom hooks have no ids, nor do non-stateful native hooks (e.g. Context, DebugValue). const id = primitive === 'Context' || primitive === 'DebugValue' ? null : nativeHookID++; // For the time being, only State and Reducer hooks support runtime overrides. const isStateEditable = primitive === 'Reducer' || primitive === 'State'; const levelChild: HooksNode = { id, isStateEditable, name: primitive, value: hook.value, subHooks: [], }; if (includeHooksSource) { const hookSource: HookSource = { lineNumber: null, functionName: null, fileName: null, columnNumber: null, }; if (stack && stack.length >= 1) { const stackFrame = stack[0]; hookSource.lineNumber = stackFrame.lineNumber; hookSource.functionName = stackFrame.functionName; hookSource.fileName = stackFrame.fileName; hookSource.columnNumber = stackFrame.columnNumber; } levelChild.hookSource = hookSource; } levelChildren.push(levelChild); } // Associate custom hook values (useDebugValue() hook entries) with the correct hooks. processDebugValues(rootChildren, null); return rootChildren; } // Custom hooks support user-configurable labels (via the special useDebugValue() hook). // That hook adds user-provided values to the hooks tree, // but these values aren't intended to appear alongside of the other hooks. // Instead they should be attributed to their parent custom hook. // This method walks the tree and assigns debug values to their custom hook owners. function processDebugValues( hooksTree: HooksTree, parentHooksNode: HooksNode | null, ): void { const debugValueHooksNodes: Array<HooksNode> = []; for (let i = 0; i < hooksTree.length; i++) { const hooksNode = hooksTree[i]; if (hooksNode.name === 'DebugValue' && hooksNode.subHooks.length === 0) { hooksTree.splice(i, 1); i--; debugValueHooksNodes.push(hooksNode); } else { processDebugValues(hooksNode.subHooks, hooksNode); } } // Bubble debug value labels to their custom hook owner. // If there is no parent hook, just ignore them for now. // (We may warn about this in the future.) if (parentHooksNode !== null) { if (debugValueHooksNodes.length === 1) { parentHooksNode.value = debugValueHooksNodes[0].value; } else if (debugValueHooksNodes.length > 1) { parentHooksNode.value = debugValueHooksNodes.map(({value}) => value); } } } function handleRenderFunctionError(error: any): void { // original error might be any type. if ( error instanceof Error && error.name === 'ReactDebugToolsUnsupportedHookError' ) { throw error; } // If the error is not caused by an unsupported feature, it means // that the error is caused by user's code in renderFunction. // In this case, we should wrap the original error inside a custom error // so that devtools can give a clear message about it. // $FlowFixMe[extra-arg]: Flow doesn't know about 2nd argument of Error constructor const wrapperError = new Error('Error rendering inspected component', { cause: error, }); // Note: This error name needs to stay in sync with react-devtools-shared // TODO: refactor this if we ever combine the devtools and debug tools packages wrapperError.name = 'ReactDebugToolsRenderError'; // this stage-4 proposal is not supported by all environments yet. // $FlowFixMe[prop-missing] Flow doesn't have this type yet. wrapperError.cause = error; throw wrapperError; } export function inspectHooks<Props>( renderFunction: Props => React$Node, props: Props, currentDispatcher: ?CurrentDispatcherRef, includeHooksSource: boolean = false, ): HooksTree { // DevTools will pass the current renderer's injected dispatcher. // Other apps might compile debug hooks as part of their app though. if (currentDispatcher == null) { currentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; } const previousDispatcher = currentDispatcher.current; currentDispatcher.current = DispatcherProxy; let readHookLog; let ancestorStackError; try { ancestorStackError = new Error(); renderFunction(props); } catch (error) { handleRenderFunctionError(error); } finally { readHookLog = hookLog; hookLog = []; // $FlowFixMe[incompatible-use] found when upgrading Flow currentDispatcher.current = previousDispatcher; } const rootStack = ErrorStackParser.parse(ancestorStackError); return buildTree(rootStack, readHookLog, includeHooksSource); } function setupContexts(contextMap: Map<ReactContext<any>, any>, fiber: Fiber) { let current: null | Fiber = fiber; while (current) { if (current.tag === ContextProvider) { const providerType: ReactProviderType<any> = current.type; const context: ReactContext<any> = providerType._context; if (!contextMap.has(context)) { // Store the current value that we're going to restore later. contextMap.set(context, context._currentValue); // Set the inner most provider value on the context. context._currentValue = current.memoizedProps.value; } } current = current.return; } } function restoreContexts(contextMap: Map<ReactContext<any>, any>) { contextMap.forEach((value, context) => (context._currentValue = value)); } function inspectHooksOfForwardRef<Props, Ref>( renderFunction: (Props, Ref) => React$Node, props: Props, ref: Ref, currentDispatcher: CurrentDispatcherRef, includeHooksSource: boolean, ): HooksTree { const previousDispatcher = currentDispatcher.current; let readHookLog; currentDispatcher.current = DispatcherProxy; let ancestorStackError; try { ancestorStackError = new Error(); renderFunction(props, ref); } catch (error) { handleRenderFunctionError(error); } finally { readHookLog = hookLog; hookLog = []; currentDispatcher.current = previousDispatcher; } const rootStack = ErrorStackParser.parse(ancestorStackError); return buildTree(rootStack, readHookLog, includeHooksSource); } function resolveDefaultProps(Component: any, baseProps: any) { if (Component && Component.defaultProps) { // Resolve default props. Taken from ReactElement const props = assign({}, baseProps); const defaultProps = Component.defaultProps; for (const propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } return props; } return baseProps; } export function inspectHooksOfFiber( fiber: Fiber, currentDispatcher: ?CurrentDispatcherRef, includeHooksSource: boolean = false, ): HooksTree { // DevTools will pass the current renderer's injected dispatcher. // Other apps might compile debug hooks as part of their app though. if (currentDispatcher == null) { currentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; } if ( fiber.tag !== FunctionComponent && fiber.tag !== SimpleMemoComponent && fiber.tag !== ForwardRef ) { throw new Error( 'Unknown Fiber. Needs to be a function component to inspect hooks.', ); } // Warm up the cache so that it doesn't consume the currentHook. getPrimitiveStackCache(); // Set up the current hook so that we can step through and read the // current state from them. currentHook = (fiber.memoizedState: Hook); currentFiber = fiber; const type = fiber.type; let props = fiber.memoizedProps; if (type !== fiber.elementType) { props = resolveDefaultProps(type, props); } const contextMap = new Map<ReactContext<any>, any>(); try { setupContexts(contextMap, fiber); if (fiber.tag === ForwardRef) { return inspectHooksOfForwardRef( type.render, props, fiber.ref, currentDispatcher, includeHooksSource, ); } return inspectHooks(type, props, currentDispatcher, includeHooksSource); } finally { currentFiber = null; currentHook = null; restoreContexts(contextMap); } }
28.567787
99
0.664054
null
'use strict'; /* eslint-disable no-for-of-loops/no-for-of-loops */ const crypto = require('node:crypto'); const fs = require('fs'); const fse = require('fs-extra'); const {spawnSync} = require('child_process'); const path = require('path'); const tmp = require('tmp'); const shell = require('shelljs'); const { ReactVersion, stablePackages, experimentalPackages, canaryChannelLabel, } = require('../../ReactVersions'); // Runs the build script for both stable and experimental release channels, // by configuring an environment variable. const sha = String( spawnSync('git', ['show', '-s', '--no-show-signature', '--format=%h']).stdout ).trim(); let dateString = String( spawnSync('git', [ 'show', '-s', '--no-show-signature', '--format=%cd', '--date=format:%Y%m%d', sha, ]).stdout ).trim(); // On CI environment, this string is wrapped with quotes '...'s if (dateString.startsWith("'")) { dateString = dateString.slice(1, 9); } // Build the artifacts using a placeholder React version. We'll then do a string // replace to swap it with the correct version per release channel. const PLACEHOLDER_REACT_VERSION = ReactVersion + '-PLACEHOLDER'; // TODO: We should inject the React version using a build-time parameter // instead of overwriting the source files. fs.writeFileSync( './packages/shared/ReactVersion.js', `export default '${PLACEHOLDER_REACT_VERSION}';\n` ); if (process.env.CIRCLE_NODE_TOTAL) { // In CI, we use multiple concurrent processes. Allocate half the processes to // build the stable channel, and the other half for experimental. Override // the environment variables to "trick" the underlying build script. const total = parseInt(process.env.CIRCLE_NODE_TOTAL, 10); const halfTotal = Math.floor(total / 2); const index = parseInt(process.env.CIRCLE_NODE_INDEX, 10); if (index < halfTotal) { const nodeTotal = halfTotal; const nodeIndex = index; buildForChannel('stable', nodeTotal, nodeIndex); processStable('./build'); } else { const nodeTotal = total - halfTotal; const nodeIndex = index - halfTotal; buildForChannel('experimental', nodeTotal, nodeIndex); processExperimental('./build'); } } else { // Running locally, no concurrency. Move each channel's build artifacts into // a temporary directory so that they don't conflict. buildForChannel('stable', '', ''); const stableDir = tmp.dirSync().name; crossDeviceRenameSync('./build', stableDir); processStable(stableDir); buildForChannel('experimental', '', ''); const experimentalDir = tmp.dirSync().name; crossDeviceRenameSync('./build', experimentalDir); processExperimental(experimentalDir); // Then merge the experimental folder into the stable one. processExperimental // will have already removed conflicting files. // // In CI, merging is handled automatically by CircleCI's workspace feature. mergeDirsSync(experimentalDir + '/', stableDir + '/'); // Now restore the combined directory back to its original name crossDeviceRenameSync(stableDir, './build'); } function buildForChannel(channel, nodeTotal, nodeIndex) { const {status} = spawnSync( 'node', ['./scripts/rollup/build.js', ...process.argv.slice(2)], { stdio: ['pipe', process.stdout, process.stderr], env: { ...process.env, RELEASE_CHANNEL: channel, CIRCLE_NODE_TOTAL: nodeTotal, CIRCLE_NODE_INDEX: nodeIndex, }, } ); if (status !== 0) { // Error of spawned process is already piped to this stderr process.exit(status); } } function processStable(buildDir) { if (fs.existsSync(buildDir + '/node_modules')) { // Identical to `oss-stable` but with real, semver versions. This is what // will get published to @latest. shell.cp('-r', buildDir + '/node_modules', buildDir + '/oss-stable-semver'); const defaultVersionIfNotFound = '0.0.0' + '-' + sha + '-' + dateString; const versionsMap = new Map(); for (const moduleName in stablePackages) { const version = stablePackages[moduleName]; versionsMap.set( moduleName, version + '-' + canaryChannelLabel + '-' + sha + '-' + dateString, defaultVersionIfNotFound ); } updatePackageVersions( buildDir + '/node_modules', versionsMap, defaultVersionIfNotFound, true ); fs.renameSync(buildDir + '/node_modules', buildDir + '/oss-stable'); updatePlaceholderReactVersionInCompiledArtifacts( buildDir + '/oss-stable', ReactVersion + '-' + canaryChannelLabel + '-' + sha + '-' + dateString ); // Now do the semver ones const semverVersionsMap = new Map(); for (const moduleName in stablePackages) { const version = stablePackages[moduleName]; semverVersionsMap.set(moduleName, version); } updatePackageVersions( buildDir + '/oss-stable-semver', semverVersionsMap, defaultVersionIfNotFound, false ); updatePlaceholderReactVersionInCompiledArtifacts( buildDir + '/oss-stable-semver', ReactVersion ); } if (fs.existsSync(buildDir + '/facebook-www')) { const hash = crypto.createHash('sha1'); for (const fileName of fs.readdirSync(buildDir + '/facebook-www').sort()) { const filePath = buildDir + '/facebook-www/' + fileName; const stats = fs.statSync(filePath); if (!stats.isDirectory()) { hash.update(fs.readFileSync(filePath)); fs.renameSync(filePath, filePath.replace('.js', '.classic.js')); } } updatePlaceholderReactVersionInCompiledArtifacts( buildDir + '/facebook-www', ReactVersion + '-www-classic-' + hash.digest('hex').slice(0, 8) ); } const reactNativeBuildDir = buildDir + '/react-native/implementations/'; if (fs.existsSync(reactNativeBuildDir)) { const hash = crypto.createHash('sha1'); for (const fileName of fs.readdirSync(reactNativeBuildDir).sort()) { const filePath = reactNativeBuildDir + fileName; const stats = fs.statSync(filePath); if (!stats.isDirectory()) { hash.update(fs.readFileSync(filePath)); } } updatePlaceholderReactVersionInCompiledArtifacts( reactNativeBuildDir, ReactVersion + '-' + canaryChannelLabel + '-' + hash.digest('hex').slice(0, 8) ); } // Update remaining placeholders with canary channel version updatePlaceholderReactVersionInCompiledArtifacts( buildDir, ReactVersion + '-' + canaryChannelLabel + '-' + sha + '-' + dateString ); if (fs.existsSync(buildDir + '/sizes')) { fs.renameSync(buildDir + '/sizes', buildDir + '/sizes-stable'); } } function processExperimental(buildDir, version) { if (fs.existsSync(buildDir + '/node_modules')) { const defaultVersionIfNotFound = '0.0.0' + '-experimental-' + sha + '-' + dateString; const versionsMap = new Map(); for (const moduleName in stablePackages) { versionsMap.set(moduleName, defaultVersionIfNotFound); } for (const moduleName of experimentalPackages) { versionsMap.set(moduleName, defaultVersionIfNotFound); } updatePackageVersions( buildDir + '/node_modules', versionsMap, defaultVersionIfNotFound, true ); fs.renameSync(buildDir + '/node_modules', buildDir + '/oss-experimental'); updatePlaceholderReactVersionInCompiledArtifacts( buildDir + '/oss-experimental', // TODO: The npm version for experimental releases does not include the // React version, but the runtime version does so that DevTools can do // feature detection. Decide what to do about this later. ReactVersion + '-experimental-' + sha + '-' + dateString ); } if (fs.existsSync(buildDir + '/facebook-www')) { const hash = crypto.createHash('sha1'); for (const fileName of fs.readdirSync(buildDir + '/facebook-www').sort()) { const filePath = buildDir + '/facebook-www/' + fileName; const stats = fs.statSync(filePath); if (!stats.isDirectory()) { hash.update(fs.readFileSync(filePath)); fs.renameSync(filePath, filePath.replace('.js', '.modern.js')); } } updatePlaceholderReactVersionInCompiledArtifacts( buildDir + '/facebook-www', ReactVersion + '-www-modern-' + hash.digest('hex').slice(0, 8) ); } // Update remaining placeholders with canary channel version updatePlaceholderReactVersionInCompiledArtifacts( buildDir, ReactVersion + '-' + canaryChannelLabel + '-' + sha + '-' + dateString ); if (fs.existsSync(buildDir + '/sizes')) { fs.renameSync(buildDir + '/sizes', buildDir + '/sizes-experimental'); } // Delete all other artifacts that weren't handled above. We assume they are // duplicates of the corresponding artifacts in the stable channel. Ideally, // the underlying build script should not have produced these files in the // first place. for (const pathName of fs.readdirSync(buildDir)) { if ( pathName !== 'oss-experimental' && pathName !== 'facebook-www' && pathName !== 'sizes-experimental' ) { spawnSync('rm', ['-rm', buildDir + '/' + pathName]); } } } function crossDeviceRenameSync(source, destination) { return fse.moveSync(source, destination, {overwrite: true}); } /* * Grabs the built packages in ${tmp_build_dir}/node_modules and updates the * `version` key in their package.json to 0.0.0-${date}-${commitHash} for the commit * you're building. Also updates the dependencies and peerDependencies * to match this version for all of the 'React' packages * (packages available in this repo). */ function updatePackageVersions( modulesDir, versionsMap, defaultVersionIfNotFound, pinToExactVersion ) { for (const moduleName of fs.readdirSync(modulesDir)) { let version = versionsMap.get(moduleName); if (version === undefined) { // TODO: If the module is not in the version map, we should exclude it // from the build artifacts. version = defaultVersionIfNotFound; } const packageJSONPath = path.join(modulesDir, moduleName, 'package.json'); const stats = fs.statSync(packageJSONPath); if (stats.isFile()) { const packageInfo = JSON.parse(fs.readFileSync(packageJSONPath)); // Update version packageInfo.version = version; if (packageInfo.dependencies) { for (const dep of Object.keys(packageInfo.dependencies)) { const depVersion = versionsMap.get(dep); if (depVersion !== undefined) { packageInfo.dependencies[dep] = pinToExactVersion ? depVersion : '^' + depVersion; } } } if (packageInfo.peerDependencies) { if ( !pinToExactVersion && (moduleName === 'use-sync-external-store' || moduleName === 'use-subscription') ) { // use-sync-external-store supports older versions of React, too, so // we don't override to the latest version. We should figure out some // better way to handle this. // TODO: Remove this special case. } else { for (const dep of Object.keys(packageInfo.peerDependencies)) { const depVersion = versionsMap.get(dep); if (depVersion !== undefined) { packageInfo.peerDependencies[dep] = pinToExactVersion ? depVersion : '^' + depVersion; } } } } // Write out updated package.json fs.writeFileSync(packageJSONPath, JSON.stringify(packageInfo, null, 2)); } } } function updatePlaceholderReactVersionInCompiledArtifacts( artifactsDirectory, newVersion ) { // Update the version of React in the compiled artifacts by searching for // the placeholder string and replacing it with a new one. const artifactFilenames = String( spawnSync('grep', [ '-lr', PLACEHOLDER_REACT_VERSION, '--', artifactsDirectory, ]).stdout ) .trim() .split('\n') .filter(filename => filename.endsWith('.js')); for (const artifactFilename of artifactFilenames) { const originalText = fs.readFileSync(artifactFilename, 'utf8'); const replacedText = originalText.replaceAll( PLACEHOLDER_REACT_VERSION, newVersion ); fs.writeFileSync(artifactFilename, replacedText); } } /** * cross-platform alternative to `rsync -ar` * @param {string} source * @param {string} destination */ function mergeDirsSync(source, destination) { for (const sourceFileBaseName of fs.readdirSync(source)) { const sourceFileName = path.join(source, sourceFileBaseName); const targetFileName = path.join(destination, sourceFileBaseName); const sourceFile = fs.statSync(sourceFileName); if (sourceFile.isDirectory()) { fse.ensureDirSync(targetFileName); mergeDirsSync(sourceFileName, targetFileName); } else { fs.copyFileSync(sourceFileName, targetFileName); } } }
32.321429
84
0.660439
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 { describeBuiltInComponentFrame, describeFunctionComponentFrame, describeClassComponentFrame, } from 'shared/ReactComponentStackFrame'; // DEV-only reverse linked list representing the current component stack type BuiltInComponentStackNode = { tag: 0, parent: null | ComponentStackNode, type: string, }; type FunctionComponentStackNode = { tag: 1, parent: null | ComponentStackNode, type: Function, }; type ClassComponentStackNode = { tag: 2, parent: null | ComponentStackNode, type: Function, }; export type ComponentStackNode = | BuiltInComponentStackNode | FunctionComponentStackNode | ClassComponentStackNode; export function getStackByComponentStackNode( componentStack: ComponentStackNode, ): string { try { let info = ''; let node: ComponentStackNode = componentStack; do { switch (node.tag) { case 0: info += describeBuiltInComponentFrame(node.type, null, null); break; case 1: info += describeFunctionComponentFrame(node.type, null, null); break; case 2: info += describeClassComponentFrame(node.type, null, null); break; } // $FlowFixMe[incompatible-type] we bail out when we get a null node = node.parent; } while (node); return info; } catch (x) { return '\nError generating stack: ' + x.message + '\n' + x.stack; } }
24.619048
72
0.677619
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 {__DEBUG__} from 'react-devtools-shared/src/constants'; import type {HooksTree} from 'react-debug-tools/src/ReactDebugHooks'; import type {Thenable, Wakeable} from 'shared/ReactTypes'; import type { Element, HookNames, HookSourceLocationKey, } from 'react-devtools-shared/src/frontend/types'; import type {HookSource} from 'react-debug-tools/src/ReactDebugHooks'; import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext'; import {withCallbackPerfMeasurements} from './PerformanceLoggingUtils'; import {logEvent} from './Logger'; const TIMEOUT = 30000; const Pending = 0; const Resolved = 1; const Rejected = 2; type PendingRecord = { status: 0, value: Wakeable, }; type ResolvedRecord<T> = { status: 1, value: T, }; type RejectedRecord = { status: 2, value: null, }; type Record<T> = PendingRecord | ResolvedRecord<T> | RejectedRecord; function readRecord<T>(record: Record<T>): ResolvedRecord<T> | RejectedRecord { if (record.status === Resolved) { // This is just a type refinement. return record; } else if (record.status === Rejected) { // This is just a type refinement. return record; } else { throw record.value; } } type LoadHookNamesFunction = ( hookLog: HooksTree, fetchFileWithCaching: FetchFileWithCaching | null, ) => Thenable<HookNames>; // This is intentionally a module-level Map, rather than a React-managed one. // Otherwise, refreshing the inspected element cache would also clear this cache. // TODO Rethink this if the React API constraints change. // See https://github.com/reactwg/react-18/discussions/25#discussioncomment-980435 let map: WeakMap<Element, Record<HookNames>> = new WeakMap(); export function hasAlreadyLoadedHookNames(element: Element): boolean { const record = map.get(element); return record != null && record.status === Resolved; } export function loadHookNames( element: Element, hooksTree: HooksTree, loadHookNamesFunction: LoadHookNamesFunction, fetchFileWithCaching: FetchFileWithCaching | null, ): HookNames | null { let record = map.get(element); if (__DEBUG__) { console.groupCollapsed('loadHookNames() record:'); console.log(record); console.groupEnd(); } if (!record) { const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { then(callback: () => mixed) { callbacks.add(callback); }, // Optional property used by Timeline: displayName: `Loading hook names for ${element.displayName || 'Unknown'}`, }; let timeoutID: $FlowFixMe | null; let didTimeout = false; let status = 'unknown'; let resolvedHookNames: HookNames | null = null; const wake = () => { if (timeoutID) { clearTimeout(timeoutID); timeoutID = null; } // This assumes they won't throw. callbacks.forEach(callback => callback()); callbacks.clear(); }; const handleLoadComplete = (durationMs: number): void => { // Log duration for parsing hook names logEvent({ event_name: 'load-hook-names', event_status: status, duration_ms: durationMs, inspected_element_display_name: element.displayName, inspected_element_number_of_hooks: resolvedHookNames?.size ?? null, }); }; const newRecord: Record<HookNames> = (record = { status: Pending, value: wakeable, }); withCallbackPerfMeasurements( 'loadHookNames', done => { loadHookNamesFunction(hooksTree, fetchFileWithCaching).then( function onSuccess(hookNames) { if (didTimeout) { return; } if (__DEBUG__) { console.log('[hookNamesCache] onSuccess() hookNames:', hookNames); } if (hookNames) { const resolvedRecord = ((newRecord: any): ResolvedRecord<HookNames>); resolvedRecord.status = Resolved; resolvedRecord.value = hookNames; } else { const notFoundRecord = ((newRecord: any): RejectedRecord); notFoundRecord.status = Rejected; notFoundRecord.value = null; } status = 'success'; resolvedHookNames = hookNames; done(); wake(); }, function onError(error) { if (didTimeout) { return; } if (__DEBUG__) { console.log('[hookNamesCache] onError()'); } console.error(error); const thrownRecord = ((newRecord: any): RejectedRecord); thrownRecord.status = Rejected; thrownRecord.value = null; status = 'error'; done(); wake(); }, ); // Eventually timeout and stop trying to load names. timeoutID = setTimeout(function onTimeout() { if (__DEBUG__) { console.log('[hookNamesCache] onTimeout()'); } timeoutID = null; didTimeout = true; const timedoutRecord = ((newRecord: any): RejectedRecord); timedoutRecord.status = Rejected; timedoutRecord.value = null; status = 'timeout'; done(); wake(); }, TIMEOUT); }, handleLoadComplete, ); map.set(element, record); } const response = readRecord(record).value; return response; } export function getHookSourceLocationKey({ fileName, lineNumber, columnNumber, }: HookSource): HookSourceLocationKey { if (fileName == null || lineNumber == null || columnNumber == null) { throw Error('Hook source code location not found.'); } return `${fileName}:${lineNumber}:${columnNumber}`; } export function clearHookNamesCache(): void { map = new WeakMap(); }
26.3125
122
0.619748
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React; let ReactDOM; let ReactDOMServer; let ReactFeatureFlags; describe('ReactLegacyContextDisabled', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.disableLegacyContext = true; }); function formatValue(val) { if (val === null) { return 'null'; } if (val === undefined) { return 'undefined'; } if (typeof val === 'string') { return val; } return JSON.stringify(val); } it('warns for legacy context', () => { class LegacyProvider extends React.Component { static childContextTypes = { foo() {}, }; getChildContext() { return {foo: 10}; } render() { return this.props.children; } } const lifecycleContextLog = []; class LegacyClsConsumer extends React.Component { static contextTypes = { foo() {}, }; shouldComponentUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); return true; } UNSAFE_componentWillReceiveProps(nextProps, nextContext) { lifecycleContextLog.push(nextContext); } UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); } render() { return formatValue(this.context); } } function LegacyFnConsumer(props, context) { return formatValue(context); } LegacyFnConsumer.contextTypes = {foo() {}}; function RegularFn(props, context) { return formatValue(context); } const container = document.createElement('div'); expect(() => { ReactDOM.render( <LegacyProvider> <span> <LegacyClsConsumer /> <LegacyFnConsumer /> <RegularFn /> </span> </LegacyProvider>, container, ); }).toErrorDev([ 'LegacyProvider uses the legacy childContextTypes API which is no longer supported. ' + 'Use React.createContext() instead.', 'LegacyClsConsumer uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with static contextType instead.', 'LegacyFnConsumer uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', ]); expect(container.textContent).toBe('{}undefinedundefined'); expect(lifecycleContextLog).toEqual([]); // Test update path. ReactDOM.render( <LegacyProvider> <span> <LegacyClsConsumer /> <LegacyFnConsumer /> <RegularFn /> </span> </LegacyProvider>, container, ); expect(container.textContent).toBe('{}undefinedundefined'); expect(lifecycleContextLog).toEqual([{}, {}, {}]); ReactDOM.unmountComponentAtNode(container); // test server path. let text; expect(() => { text = ReactDOMServer.renderToString( <LegacyProvider> <span> <LegacyClsConsumer /> <LegacyFnConsumer /> <RegularFn /> </span> </LegacyProvider>, container, ); }).toErrorDev([ 'LegacyProvider uses the legacy childContextTypes API which is no longer supported. ' + 'Use React.createContext() instead.', 'LegacyClsConsumer uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with static contextType instead.', 'LegacyFnConsumer uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with React.useContext() instead.', ]); expect(text).toBe('<span>{}<!-- -->undefined<!-- -->undefined</span>'); expect(lifecycleContextLog).toEqual([{}, {}, {}]); }); it('renders a tree with modern context', () => { const Ctx = React.createContext(); class Provider extends React.Component { render() { return ( <Ctx.Provider value={this.props.value}> {this.props.children} </Ctx.Provider> ); } } class RenderPropConsumer extends React.Component { render() { return <Ctx.Consumer>{value => formatValue(value)}</Ctx.Consumer>; } } const lifecycleContextLog = []; class ContextTypeConsumer extends React.Component { static contextType = Ctx; shouldComponentUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); return true; } UNSAFE_componentWillReceiveProps(nextProps, nextContext) { lifecycleContextLog.push(nextContext); } UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); } render() { return formatValue(this.context); } } function FnConsumer() { return formatValue(React.useContext(Ctx)); } const container = document.createElement('div'); ReactDOM.render( <Provider value="a"> <span> <RenderPropConsumer /> <ContextTypeConsumer /> <FnConsumer /> </span> </Provider>, container, ); expect(container.textContent).toBe('aaa'); expect(lifecycleContextLog).toEqual([]); // Test update path ReactDOM.render( <Provider value="a"> <span> <RenderPropConsumer /> <ContextTypeConsumer /> <FnConsumer /> </span> </Provider>, container, ); expect(container.textContent).toBe('aaa'); expect(lifecycleContextLog).toEqual(['a', 'a', 'a']); lifecycleContextLog.length = 0; ReactDOM.render( <Provider value="b"> <span> <RenderPropConsumer /> <ContextTypeConsumer /> <FnConsumer /> </span> </Provider>, container, ); expect(container.textContent).toBe('bbb'); if (gate(flags => flags.enableLazyContextPropagation)) { // In the lazy propagation implementation, we don't check if context // changed until after shouldComponentUpdate is run. expect(lifecycleContextLog).toEqual(['b', 'b', 'b']); } else { // In the eager implementation, a dirty flag was set when the parent // changed, so we skipped sCU. expect(lifecycleContextLog).toEqual(['b', 'b']); } ReactDOM.unmountComponentAtNode(container); }); });
27.715481
93
0.607549
Hands-On-Penetration-Testing-with-Python
"use strict"; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const { useMemo, useState } = require('react'); function Component(props) { const InnerComponent = useMemo(() => () => { const [state] = useState(0); return state; }); props.callback(InnerComponent); return null; } module.exports = { Component }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhOZXN0ZWRIb29rcy5qcyJdLCJuYW1lcyI6WyJ1c2VNZW1vIiwidXNlU3RhdGUiLCJyZXF1aXJlIiwiQ29tcG9uZW50IiwicHJvcHMiLCJJbm5lckNvbXBvbmVudCIsInN0YXRlIiwiY2FsbGJhY2siLCJtb2R1bGUiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOztBQUFBOzs7Ozs7OztBQVFBLE1BQU07QUFBQ0EsRUFBQUEsT0FBRDtBQUFVQyxFQUFBQTtBQUFWLElBQXNCQyxPQUFPLENBQUMsT0FBRCxDQUFuQzs7QUFFQSxTQUFTQyxTQUFULENBQW1CQyxLQUFuQixFQUEwQjtBQUN4QixRQUFNQyxjQUFjLEdBQUdMLE9BQU8sQ0FBQyxNQUFNLE1BQU07QUFDekMsVUFBTSxDQUFDTSxLQUFELElBQVVMLFFBQVEsQ0FBQyxDQUFELENBQXhCO0FBRUEsV0FBT0ssS0FBUDtBQUNELEdBSjZCLENBQTlCO0FBS0FGLEVBQUFBLEtBQUssQ0FBQ0csUUFBTixDQUFlRixjQUFmO0FBRUEsU0FBTyxJQUFQO0FBQ0Q7O0FBRURHLE1BQU0sQ0FBQ0MsT0FBUCxHQUFpQjtBQUFDTixFQUFBQTtBQUFELENBQWpCIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5jb25zdCB7dXNlTWVtbywgdXNlU3RhdGV9ID0gcmVxdWlyZSgncmVhY3QnKTtcblxuZnVuY3Rpb24gQ29tcG9uZW50KHByb3BzKSB7XG4gIGNvbnN0IElubmVyQ29tcG9uZW50ID0gdXNlTWVtbygoKSA9PiAoKSA9PiB7XG4gICAgY29uc3QgW3N0YXRlXSA9IHVzZVN0YXRlKDApO1xuXG4gICAgcmV0dXJuIHN0YXRlO1xuICB9KTtcbiAgcHJvcHMuY2FsbGJhY2soSW5uZXJDb21wb25lbnQpO1xuXG4gIHJldHVybiBudWxsO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHtDb21wb25lbnR9O1xuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiIsIklubmVyQ29tcG9uZW50Iiwic3RhdGUiXSwibWFwcGluZ3MiOiJDQUFEO1l5QkNBO2FMQ0EsQVdEQTtnQjNCREEifV1dXX0=
74.464286
1,628
0.913352
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'; const rule = require('../warning-args'); const {RuleTester} = require('eslint'); const ruleTester = new RuleTester(); ruleTester.run('eslint-rules/warning-args', rule, { valid: [ "console.error('hello, world');", "console.error('expected %s, got %s', 42, 24);", 'arbitraryFunction(a, b)', ], invalid: [ { code: 'console.error(null);', errors: [ { message: 'The first argument to console.error must be a string literal', }, ], }, { code: 'console.warn(null);', errors: [ { message: 'The first argument to console.warn must be a string literal', }, ], }, { code: 'var g = 5; console.error(g);', errors: [ { message: 'The first argument to console.error must be a string literal', }, ], }, { code: "console.error('expected %s, got %s');", errors: [ { message: 'Expected 3 arguments in call to console.error based on the number of ' + '"%s" substitutions, but got 1', }, ], }, { code: "console.error('foo is a bar under foobar', 'junk argument');", errors: [ { message: 'Expected 1 arguments in call to console.error based on the number of ' + '"%s" substitutions, but got 2', }, ], }, { code: "console.error('error!');", errors: [ { message: 'The console.error format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: error!', }, ], }, { code: "console.error('%s %s, %s %s: %s (%s)', 1, 2, 3, 4, 5, 6);", errors: [ { message: 'The console.error format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + '%s %s, %s %s: %s (%s)', }, ], }, ], });
23.774194
85
0.499349
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('../cjs/use-sync-external-store-shim.production.min.js'); } else { module.exports = require('../cjs/use-sync-external-store-shim.development.js'); }
28.875
84
0.689076
null
#!/usr/bin/env node 'use strict'; const clear = require('clear'); const {confirm} = require('../utils'); const theme = require('../theme'); const run = async () => { clear(); console.log( theme.caution( 'This script does not run any automated tests.' + 'You should run them manually before creating a "next" release.' ) ); await confirm('Do you want to proceed?'); clear(); }; module.exports = run;
16.56
72
0.611872
owtf
import TestCase from '../../TestCase'; import Iframe from '../../Iframe'; const React = window.React; export default class ReorderedInputsTestCase extends React.Component { state = {count: 0}; componentDidMount() { this.interval = setInterval(() => { this.setState({count: this.state.count + 1}); }, 2000); } componentWillUnmount() { clearInterval(this.interval); } renderInputs() { const inputs = [ <input key={1} defaultValue="Foo" />, <input key={2} defaultValue="Bar" />, ]; if (this.state.count % 2 === 0) { inputs.reverse(); } return inputs; } render() { return ( <TestCase title="Reordered input elements in iframes" description=""> <TestCase.Steps> <li>The two inputs below swap positions every two seconds</li> <li>Select the text in either of them</li> <li>Wait for the swap to occur</li> </TestCase.Steps> <TestCase.ExpectedResult> The selection you made should be maintained </TestCase.ExpectedResult> <Iframe height={50}>{this.renderInputs()}</Iframe> </TestCase> ); } }
24.866667
75
0.601892
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Scheduler; let act; let LegacyHidden; let Activity; let useState; let useLayoutEffect; let useEffect; let useMemo; let useRef; let startTransition; let waitForPaint; let waitFor; let assertLog; describe('Activity', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; LegacyHidden = React.unstable_LegacyHidden; Activity = React.unstable_Activity; useState = React.useState; useLayoutEffect = React.useLayoutEffect; useEffect = React.useEffect; useMemo = React.useMemo; useRef = React.useRef; startTransition = React.startTransition; const InternalTestUtils = require('internal-test-utils'); waitForPaint = InternalTestUtils.waitForPaint; waitFor = InternalTestUtils.waitFor; assertLog = InternalTestUtils.assertLog; }); function Text(props) { Scheduler.log(props.text); return <span prop={props.text}>{props.children}</span>; } function LoggedText({text, children}) { useEffect(() => { Scheduler.log(`mount ${text}`); return () => { Scheduler.log(`unmount ${text}`); }; }); useLayoutEffect(() => { Scheduler.log(`mount layout ${text}`); return () => { Scheduler.log(`unmount layout ${text}`); }; }); return <Text text={text}>{children}</Text>; } // @gate enableLegacyHidden it('unstable-defer-without-hiding should never toggle the visibility of its children', async () => { function App({mode}) { return ( <> <Text text="Normal" /> <LegacyHidden mode={mode}> <Text text="Deferred" /> </LegacyHidden> </> ); } // Test the initial mount const root = ReactNoop.createRoot(); await act(async () => { root.render(<App mode="unstable-defer-without-hiding" />); await waitForPaint(['Normal']); expect(root).toMatchRenderedOutput(<span prop="Normal" />); }); assertLog(['Deferred']); expect(root).toMatchRenderedOutput( <> <span prop="Normal" /> <span prop="Deferred" /> </>, ); // Now try after an update await act(() => { root.render(<App mode="visible" />); }); assertLog(['Normal', 'Deferred']); expect(root).toMatchRenderedOutput( <> <span prop="Normal" /> <span prop="Deferred" /> </>, ); await act(async () => { root.render(<App mode="unstable-defer-without-hiding" />); await waitForPaint(['Normal']); expect(root).toMatchRenderedOutput( <> <span prop="Normal" /> <span prop="Deferred" /> </>, ); }); assertLog(['Deferred']); expect(root).toMatchRenderedOutput( <> <span prop="Normal" /> <span prop="Deferred" /> </>, ); }); // @gate www it('does not defer in legacy mode', async () => { let setState; function Foo() { const [state, _setState] = useState('A'); setState = _setState; return <Text text={state} />; } const root = ReactNoop.createLegacyRoot(); await act(() => { root.render( <> <LegacyHidden mode="hidden"> <Foo /> </LegacyHidden> <Text text="Outside" /> </>, ); ReactNoop.flushSync(); // Should not defer the hidden tree assertLog(['A', 'Outside']); }); expect(root).toMatchRenderedOutput( <> <span prop="A" /> <span prop="Outside" /> </>, ); // Test that the children can be updated await act(() => { setState('B'); }); assertLog(['B']); expect(root).toMatchRenderedOutput( <> <span prop="B" /> <span prop="Outside" /> </>, ); }); // @gate www it('does defer in concurrent mode', async () => { let setState; function Foo() { const [state, _setState] = useState('A'); setState = _setState; return <Text text={state} />; } const root = ReactNoop.createRoot(); await act(async () => { root.render( <> <LegacyHidden mode="hidden"> <Foo /> </LegacyHidden> <Text text="Outside" /> </>, ); // Should defer the hidden tree. await waitForPaint(['Outside']); }); // The hidden tree was rendered at lower priority. assertLog(['A']); expect(root).toMatchRenderedOutput( <> <span prop="A" /> <span prop="Outside" /> </>, ); // Test that the children can be updated await act(() => { setState('B'); }); assertLog(['B']); expect(root).toMatchRenderedOutput( <> <span prop="B" /> <span prop="Outside" /> </>, ); }); // @gate enableActivity it('mounts without layout effects when hidden', async () => { function Child({text}) { useLayoutEffect(() => { Scheduler.log('Mount layout'); return () => { Scheduler.log('Unmount layout'); }; }, []); return <Text text="Child" />; } const root = ReactNoop.createRoot(); // Mount hidden tree. await act(() => { root.render( <Activity mode="hidden"> <Child /> </Activity>, ); }); // No layout effect. assertLog(['Child']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); // Unhide the tree. The layout effect is mounted. await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); }); assertLog(['Child', 'Mount layout']); expect(root).toMatchRenderedOutput(<span prop="Child" />); }); // @gate enableActivity it('mounts/unmounts layout effects when visibility changes (starting visible)', async () => { function Child({text}) { useLayoutEffect(() => { Scheduler.log('Mount layout'); return () => { Scheduler.log('Unmount layout'); }; }, []); return <Text text="Child" />; } const root = ReactNoop.createRoot(); await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); }); assertLog(['Child', 'Mount layout']); expect(root).toMatchRenderedOutput(<span prop="Child" />); // Hide the tree. The layout effect is unmounted. await act(() => { root.render( <Activity mode="hidden"> <Child /> </Activity>, ); }); assertLog(['Unmount layout', 'Child']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); // Unhide the tree. The layout effect is re-mounted. await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); }); assertLog(['Child', 'Mount layout']); expect(root).toMatchRenderedOutput(<span prop="Child" />); }); // @gate enableActivity it('nested offscreen does not call componentWillUnmount when hidden', async () => { // This is a bug that appeared during production test of <unstable_Activity />. // It is a very specific scenario with nested Offscreens. The inner offscreen // goes from visible to hidden in synchronous update. class ClassComponent extends React.Component { render() { return <Text text="child" />; } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } componentDidMount() { Scheduler.log('componentDidMount'); } } const root = ReactNoop.createRoot(); await act(() => { // Outer and inner offscreen are hidden. root.render( <Activity mode={'hidden'}> <Activity mode={'hidden'}> <ClassComponent /> </Activity> </Activity>, ); }); assertLog(['child']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="child" />); await act(() => { // Inner offscreen is visible. root.render( <Activity mode={'hidden'}> <Activity mode={'visible'}> <ClassComponent /> </Activity> </Activity>, ); }); assertLog(['child']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="child" />); await act(() => { // Inner offscreen is hidden. root.render( <Activity mode={'hidden'}> <Activity mode={'hidden'}> <ClassComponent /> </Activity> </Activity>, ); }); assertLog(['child']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="child" />); await act(() => { // Inner offscreen is visible. root.render( <Activity mode={'hidden'}> <Activity mode={'visible'}> <ClassComponent /> </Activity> </Activity>, ); }); Scheduler.unstable_clearLog(); await act(() => { // Outer offscreen is visible. // Inner offscreen is hidden. root.render( <Activity mode={'visible'}> <Activity mode={'hidden'}> <ClassComponent /> </Activity> </Activity>, ); }); assertLog(['child']); await act(() => { // Outer offscreen is hidden. // Inner offscreen is visible. root.render( <Activity mode={'hidden'}> <Activity mode={'visible'}> <ClassComponent /> </Activity> </Activity>, ); }); assertLog(['child']); }); // @gate enableActivity it('mounts/unmounts layout effects when visibility changes (starting hidden)', async () => { function Child({text}) { useLayoutEffect(() => { Scheduler.log('Mount layout'); return () => { Scheduler.log('Unmount layout'); }; }, []); return <Text text="Child" />; } const root = ReactNoop.createRoot(); await act(() => { // Start the tree hidden. The layout effect is not mounted. root.render( <Activity mode="hidden"> <Child /> </Activity>, ); }); assertLog(['Child']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); // Show the tree. The layout effect is mounted. await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); }); assertLog(['Child', 'Mount layout']); expect(root).toMatchRenderedOutput(<span prop="Child" />); // Hide the tree again. The layout effect is un-mounted. await act(() => { root.render( <Activity mode="hidden"> <Child /> </Activity>, ); }); assertLog(['Unmount layout', 'Child']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); }); // @gate enableActivity it('hides children of offscreen after layout effects are destroyed', async () => { const root = ReactNoop.createRoot(); function Child({text}) { useLayoutEffect(() => { Scheduler.log('Mount layout'); return () => { // The child should not be hidden yet. expect(root).toMatchRenderedOutput(<span prop="Child" />); Scheduler.log('Unmount layout'); }; }, []); return <Text text="Child" />; } await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); }); assertLog(['Child', 'Mount layout']); expect(root).toMatchRenderedOutput(<span prop="Child" />); // Hide the tree. The layout effect is unmounted. await act(() => { root.render( <Activity mode="hidden"> <Child /> </Activity>, ); }); assertLog(['Unmount layout', 'Child']); // After the layout effect is unmounted, the child is hidden. expect(root).toMatchRenderedOutput(<span hidden={true} prop="Child" />); }); // @gate enableLegacyHidden it('does not toggle effects for LegacyHidden component', async () => { // LegacyHidden is meant to be the same as offscreen except it doesn't // do anything to effects. Only used by www, as a temporary migration step. function Child({text}) { useLayoutEffect(() => { Scheduler.log('Mount layout'); return () => { Scheduler.log('Unmount layout'); }; }, []); return <Text text="Child" />; } const root = ReactNoop.createRoot(); await act(() => { root.render( <LegacyHidden mode="visible"> <Child /> </LegacyHidden>, ); }); assertLog(['Child', 'Mount layout']); await act(() => { root.render( <LegacyHidden mode="hidden"> <Child /> </LegacyHidden>, ); }); assertLog(['Child']); await act(() => { root.render( <LegacyHidden mode="visible"> <Child /> </LegacyHidden>, ); }); assertLog(['Child']); await act(() => { root.render(null); }); assertLog(['Unmount layout']); }); // @gate enableActivity it('hides new insertions into an already hidden tree', async () => { const root = ReactNoop.createRoot(); await act(() => { root.render( <Activity mode="hidden"> <span>Hi</span> </Activity>, ); }); expect(root).toMatchRenderedOutput(<span hidden={true}>Hi</span>); // Insert a new node into the hidden tree await act(() => { root.render( <Activity mode="hidden"> <span>Hi</span> <span>Something new</span> </Activity>, ); }); expect(root).toMatchRenderedOutput( <> <span hidden={true}>Hi</span> {/* This new node should also be hidden */} <span hidden={true}>Something new</span> </>, ); }); // @gate enableActivity it('hides updated nodes inside an already hidden tree', async () => { const root = ReactNoop.createRoot(); await act(() => { root.render( <Activity mode="hidden"> <span>Hi</span> </Activity>, ); }); expect(root).toMatchRenderedOutput(<span hidden={true}>Hi</span>); // Set the `hidden` prop to on an already hidden node await act(() => { root.render( <Activity mode="hidden"> <span hidden={false}>Hi</span> </Activity>, ); }); // It should still be hidden, because the Activity container overrides it expect(root).toMatchRenderedOutput(<span hidden={true}>Hi</span>); // Unhide the boundary await act(() => { root.render( <Activity mode="visible"> <span hidden={true}>Hi</span> </Activity>, ); }); // It should still be hidden, because of the prop expect(root).toMatchRenderedOutput(<span hidden={true}>Hi</span>); // Remove the `hidden` prop await act(() => { root.render( <Activity mode="visible"> <span>Hi</span> </Activity>, ); }); // Now it's visible expect(root).toMatchRenderedOutput(<span>Hi</span>); }); // @gate enableActivity it('revealing a hidden tree at high priority does not cause tearing', async () => { // When revealing an offscreen tree, we need to include updates that were // previously deferred because the tree was hidden, even if they are lower // priority than the current render. However, we should *not* include low // priority updates that are entangled with updates outside of the hidden // tree, because that can cause tearing. // // This test covers a scenario where an update multiple updates inside a // hidden tree share the same lane, but are processed at different times // because of the timing of when they were scheduled. // This functions checks whether the "outer" and "inner" states are // consistent in the rendered output. let currentOuter = null; let currentInner = null; function areOuterAndInnerConsistent() { return ( currentOuter === null || currentInner === null || currentOuter === currentInner ); } let setInner; function Child() { const [inner, _setInner] = useState(0); setInner = _setInner; useEffect(() => { currentInner = inner; return () => { currentInner = null; }; }, [inner]); return <Text text={'Inner: ' + inner} />; } let setOuter; function App({show}) { const [outer, _setOuter] = useState(0); setOuter = _setOuter; useEffect(() => { currentOuter = outer; return () => { currentOuter = null; }; }, [outer]); return ( <> <Text text={'Outer: ' + outer} /> <Activity mode={show ? 'visible' : 'hidden'}> <Child /> </Activity> </> ); } // Render a hidden tree const root = ReactNoop.createRoot(); await act(() => { root.render(<App show={false} />); }); assertLog(['Outer: 0', 'Inner: 0']); expect(root).toMatchRenderedOutput( <> <span prop="Outer: 0" /> <span hidden={true} prop="Inner: 0" /> </>, ); expect(areOuterAndInnerConsistent()).toBe(true); await act(async () => { // Update a value both inside and outside the hidden tree. These values // must always be consistent. setOuter(1); setInner(1); // Only the outer updates finishes because the inner update is inside a // hidden tree. The outer update is deferred to a later render. await waitForPaint(['Outer: 1']); expect(root).toMatchRenderedOutput( <> <span prop="Outer: 1" /> <span hidden={true} prop="Inner: 0" /> </>, ); // Before the inner update can finish, we receive another pair of updates. if (gate(flags => flags.enableUnifiedSyncLane)) { React.startTransition(() => { setOuter(2); setInner(2); }); } else { setOuter(2); setInner(2); } // Also, before either of these new updates are processed, the hidden // tree is revealed at high priority. ReactNoop.flushSync(() => { root.render(<App show={true} />); }); assertLog([ 'Outer: 1', // There are two pending updates on Inner, but only the first one // is processed, even though they share the same lane. If the second // update were erroneously processed, then Inner would be inconsistent // with Outer. 'Inner: 1', ]); expect(root).toMatchRenderedOutput( <> <span prop="Outer: 1" /> <span prop="Inner: 1" /> </>, ); expect(areOuterAndInnerConsistent()).toBe(true); }); assertLog(['Outer: 2', 'Inner: 2']); expect(root).toMatchRenderedOutput( <> <span prop="Outer: 2" /> <span prop="Inner: 2" /> </>, ); expect(areOuterAndInnerConsistent()).toBe(true); }); // @gate enableActivity it('regression: Activity instance is sometimes null during setState', async () => { let setState; function Child() { const [state, _setState] = useState('Initial'); setState = _setState; return <Text text={state} />; } const root = ReactNoop.createRoot(); await act(() => { root.render(<Activity hidden={false} />); }); assertLog([]); expect(root).toMatchRenderedOutput(null); await act(async () => { // Partially render a component startTransition(() => { root.render( <Activity hidden={false}> <Child /> <Text text="Sibling" /> </Activity>, ); }); await waitFor(['Initial']); // Before it finishes rendering, the whole tree gets deleted ReactNoop.flushSync(() => { root.render(null); }); // Something attempts to update the never-mounted component. When this // regression test was written, we would walk up the component's return // path and reach an unmounted Activity component fiber. Its `stateNode` // would be null because it was nulled out when it was deleted, but there // was no null check before we accessed it. A weird edge case but we must // account for it. expect(() => { setState('Updated'); }).toErrorDev( "Can't perform a React state update on a component that hasn't mounted yet", ); }); expect(root).toMatchRenderedOutput(null); }); // @gate enableActivity it('class component setState callbacks do not fire until tree is visible', async () => { const root = ReactNoop.createRoot(); let child; class Child extends React.Component { state = {text: 'A'}; render() { child = this; return <Text text={this.state.text} />; } } // Initial render await act(() => { root.render( <Activity mode="hidden"> <Child /> </Activity>, ); }); assertLog(['A']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="A" />); // Schedule an update to a hidden class component. The update will finish // rendering in the background, but the callback shouldn't fire yet, because // the component isn't visible. await act(() => { child.setState({text: 'B'}, () => { Scheduler.log('B update finished'); }); }); assertLog(['B']); expect(root).toMatchRenderedOutput(<span hidden={true} prop="B" />); // Now reveal the hidden component. Simultaneously, schedule another // update with a callback to the same component. When the component is // revealed, both the B callback and C callback should fire, in that order. await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); child.setState({text: 'C'}, () => { Scheduler.log('C update finished'); }); }); assertLog(['C', 'B update finished', 'C update finished']); expect(root).toMatchRenderedOutput(<span prop="C" />); }); // @gate enableActivity it('does not call componentDidUpdate when reappearing a hidden class component', async () => { class Child extends React.Component { componentDidMount() { Scheduler.log('componentDidMount'); } componentDidUpdate() { Scheduler.log('componentDidUpdate'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return 'Child'; } } // Initial mount const root = ReactNoop.createRoot(); await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); }); assertLog(['componentDidMount']); // Hide the class component await act(() => { root.render( <Activity mode="hidden"> <Child /> </Activity>, ); }); assertLog(['componentWillUnmount']); // Reappear the class component. componentDidMount should fire, not // componentDidUpdate. await act(() => { root.render( <Activity mode="visible"> <Child /> </Activity>, ); }); assertLog(['componentDidMount']); }); // @gate enableActivity it( 'when reusing old components (hidden -> visible), layout effects fire ' + 'with same timing as if it were brand new', async () => { function Child({label}) { useLayoutEffect(() => { Scheduler.log('Mount ' + label); return () => { Scheduler.log('Unmount ' + label); }; }, [label]); return label; } // Initial mount const root = ReactNoop.createRoot(); await act(() => { root.render( <Activity mode="visible"> <Child key="B" label="B" /> </Activity>, ); }); assertLog(['Mount B']); // Hide the component await act(() => { root.render( <Activity mode="hidden"> <Child key="B" label="B" /> </Activity>, ); }); assertLog(['Unmount B']); // Reappear the component and also add some new siblings. await act(() => { root.render( <Activity mode="visible"> <Child key="A" label="A" /> <Child key="B" label="B" /> <Child key="C" label="C" /> </Activity>, ); }); // B's effect should fire in between A and C even though it's been reused // from a previous render. In other words, it's the same order as if all // three siblings were brand new. assertLog(['Mount A', 'Mount B', 'Mount C']); }, ); // @gate enableActivity it( 'when reusing old components (hidden -> visible), layout effects fire ' + 'with same timing as if it were brand new (includes setState callback)', async () => { class Child extends React.Component { componentDidMount() { Scheduler.log('Mount ' + this.props.label); } componentWillUnmount() { Scheduler.log('Unmount ' + this.props.label); } render() { return this.props.label; } } // Initial mount const bRef = React.createRef(); const root = ReactNoop.createRoot(); await act(() => { root.render( <Activity mode="visible"> <Child key="B" ref={bRef} label="B" /> </Activity>, ); }); assertLog(['Mount B']); // We're going to schedule an update on a hidden component, so stash a // reference to its setState before the ref gets detached const setStateB = bRef.current.setState.bind(bRef.current); // Hide the component await act(() => { root.render( <Activity mode="hidden"> <Child key="B" ref={bRef} label="B" /> </Activity>, ); }); assertLog(['Unmount B']); // Reappear the component and also add some new siblings. await act(() => { setStateB(null, () => { Scheduler.log('setState callback B'); }); root.render( <Activity mode="visible"> <Child key="A" label="A" /> <Child key="B" ref={bRef} label="B" /> <Child key="C" label="C" /> </Activity>, ); }); // B's effect should fire in between A and C even though it's been reused // from a previous render. In other words, it's the same order as if all // three siblings were brand new. assertLog(['Mount A', 'Mount B', 'setState callback B', 'Mount C']); }, ); // @gate enableActivity it('defer passive effects when prerendering a new Activity tree', async () => { function Child({label}) { useEffect(() => { Scheduler.log('Mount ' + label); return () => { Scheduler.log('Unmount ' + label); }; }, [label]); return <Text text={label} />; } function App({showMore}) { return ( <> <Child label="Shell" /> <Activity mode={showMore ? 'visible' : 'hidden'}> <Child label="More" /> </Activity> </> ); } const root = ReactNoop.createRoot(); // Mount the app without showing the extra content await act(() => { root.render(<App showMore={false} />); }); assertLog([ // First mount the outer visible shell 'Shell', 'Mount Shell', // Then prerender the hidden extra context. The passive effects in the // hidden tree should not fire 'More', // Does not fire // 'Mount More', ]); // The hidden content has been prerendered expect(root).toMatchRenderedOutput( <> <span prop="Shell" /> <span hidden={true} prop="More" /> </>, ); // Reveal the prerendered tree await act(() => { root.render(<App showMore={true} />); }); assertLog([ 'Shell', 'More', // Mount the passive effects in the newly revealed tree, the ones that // were skipped during pre-rendering. 'Mount More', ]); }); // @gate enableLegacyHidden it('do not defer passive effects when prerendering a new LegacyHidden tree', async () => { function Child({label}) { useEffect(() => { Scheduler.log('Mount ' + label); return () => { Scheduler.log('Unmount ' + label); }; }, [label]); return <Text text={label} />; } function App({showMore}) { return ( <> <Child label="Shell" /> <LegacyHidden mode={showMore ? 'visible' : 'unstable-defer-without-hiding'}> <Child label="More" /> </LegacyHidden> </> ); } const root = ReactNoop.createRoot(); // Mount the app without showing the extra content await act(() => { root.render(<App showMore={false} />); }); assertLog([ // First mount the outer visible shell 'Shell', 'Mount Shell', // Then prerender the hidden extra context. Unlike Activity, the passive // effects in the hidden tree *should* fire 'More', 'Mount More', ]); // The hidden content has been prerendered expect(root).toMatchRenderedOutput( <> <span prop="Shell" /> <span prop="More" /> </>, ); // Reveal the prerendered tree await act(() => { root.render(<App showMore={true} />); }); assertLog(['Shell', 'More']); }); // @gate enableActivity it('passive effects are connected and disconnected when the visibility changes', async () => { function Child({step}) { useEffect(() => { Scheduler.log(`Commit mount [${step}]`); return () => { Scheduler.log(`Commit unmount [${step}]`); }; }, [step]); return <Text text={step} />; } function App({show, step}) { return ( <Activity mode={show ? 'visible' : 'hidden'}> {useMemo( () => ( <Child step={step} /> ), [step], )} </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App show={true} step={1} />); }); assertLog([1, 'Commit mount [1]']); expect(root).toMatchRenderedOutput(<span prop={1} />); // Hide the tree. This will unmount the effect. await act(() => { root.render(<App show={false} step={1} />); }); assertLog(['Commit unmount [1]']); expect(root).toMatchRenderedOutput(<span hidden={true} prop={1} />); // Update. await act(() => { root.render(<App show={false} step={2} />); }); // The update is prerendered but no effects are fired assertLog([2]); expect(root).toMatchRenderedOutput(<span hidden={true} prop={2} />); // Reveal the tree. await act(() => { root.render(<App show={true} step={2} />); }); // The update doesn't render because it was already prerendered, but we do // fire the effect. assertLog(['Commit mount [2]']); expect(root).toMatchRenderedOutput(<span prop={2} />); }); // @gate enableActivity it('passive effects are unmounted on hide in the same order as during a deletion: parent before child', async () => { function Child({label}) { useEffect(() => { Scheduler.log('Mount Child'); return () => { Scheduler.log('Unmount Child'); }; }, []); return <div>Hi</div>; } function Parent() { useEffect(() => { Scheduler.log('Mount Parent'); return () => { Scheduler.log('Unmount Parent'); }; }, []); return <Child />; } function App({show}) { return ( <Activity mode={show ? 'visible' : 'hidden'}> <Parent /> </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App show={true} />); }); assertLog(['Mount Child', 'Mount Parent']); // First demonstrate what happens during a normal deletion await act(() => { root.render(null); }); assertLog(['Unmount Parent', 'Unmount Child']); // Now redo the same thing but hide instead of deleting await act(() => { root.render(<App show={true} />); }); assertLog(['Mount Child', 'Mount Parent']); await act(() => { root.render(<App show={false} />); }); // The order is the same as during a deletion: parent before child assertLog(['Unmount Parent', 'Unmount Child']); }); // TODO: As of now, there's no way to hide a tree without also unmounting its // effects. (Except for Suspense, which has its own tests associated with it.) // Re-enable this test once we add this ability. For example, we'll likely add // either an option or a heuristic to mount passive effects inside a hidden // tree after a delay. // @gate enableActivity it.skip("don't defer passive effects when prerendering in a tree whose effects are already connected", async () => { function Child({label}) { useEffect(() => { Scheduler.log('Mount ' + label); return () => { Scheduler.log('Unmount ' + label); }; }, [label]); return <Text text={label} />; } function App({showMore, step}) { return ( <> <Child label={'Shell ' + step} /> <Activity mode={showMore ? 'visible' : 'hidden'}> <Child label={'More ' + step} /> </Activity> </> ); } const root = ReactNoop.createRoot(); // Mount the app, including the extra content await act(() => { root.render(<App showMore={true} step={1} />); }); assertLog(['Shell 1', 'More 1', 'Mount Shell 1', 'Mount More 1']); expect(root).toMatchRenderedOutput( <> <span prop="Shell 1" /> <span prop="More 1" /> </>, ); // Hide the extra content. while also updating one of its props await act(() => { root.render(<App showMore={false} step={2} />); }); assertLog([ // First update the outer visible shell 'Shell 2', 'Unmount Shell 1', 'Mount Shell 2', // Then prerender the update to the hidden content. Since the effects // are already connected inside the hidden tree, we don't defer updates // to them. 'More 2', 'Unmount More 1', 'Mount More 2', ]); }); // @gate enableActivity it('does not mount effects when prerendering a nested Activity boundary', async () => { function Child({label}) { useEffect(() => { Scheduler.log('Mount ' + label); return () => { Scheduler.log('Unmount ' + label); }; }, [label]); return <Text text={label} />; } function App({showOuter, showInner}) { return ( <Activity mode={showOuter ? 'visible' : 'hidden'}> {useMemo( () => ( <div> <Child label="Outer" /> {showInner ? ( <Activity mode="visible"> <div> <Child label="Inner" /> </div> </Activity> ) : null} </div> ), [showInner], )} </Activity> ); } const root = ReactNoop.createRoot(); // Prerender the outer contents. No effects should mount. await act(() => { root.render(<App showOuter={false} showInner={false} />); }); assertLog(['Outer']); expect(root).toMatchRenderedOutput( <div hidden={true}> <span prop="Outer" /> </div>, ); // Prerender the inner contents. No effects should mount. await act(() => { root.render(<App showOuter={false} showInner={true} />); }); assertLog(['Outer', 'Inner']); expect(root).toMatchRenderedOutput( <div hidden={true}> <span prop="Outer" /> <div> <span prop="Inner" /> </div> </div>, ); // Reveal the prerendered tree await act(() => { root.render(<App showOuter={true} showInner={true} />); }); // The effects fire, but the tree is not re-rendered because it already // prerendered. assertLog(['Mount Outer', 'Mount Inner']); expect(root).toMatchRenderedOutput( <div> <span prop="Outer" /> <div> <span prop="Inner" /> </div> </div>, ); }); // @gate enableActivity it('reveal an outer Activity boundary without revealing an inner one', async () => { function Child({label}) { useEffect(() => { Scheduler.log('Mount ' + label); return () => { Scheduler.log('Unmount ' + label); }; }, [label]); return <Text text={label} />; } function App({showOuter, showInner}) { return ( <Activity mode={showOuter ? 'visible' : 'hidden'}> {useMemo( () => ( <div> <Child label="Outer" /> <Activity mode={showInner ? 'visible' : 'hidden'}> <div> <Child label="Inner" /> </div> </Activity> </div> ), [showInner], )} </Activity> ); } const root = ReactNoop.createRoot(); // Prerender the whole tree. await act(() => { root.render(<App showOuter={false} showInner={false} />); }); assertLog(['Outer', 'Inner']); // Both the inner and the outer tree should be hidden. Hiding the inner tree // is arguably redundant, but the advantage of hiding both is that later you // can reveal the outer tree without having to examine the inner one. expect(root).toMatchRenderedOutput( <div hidden={true}> <span prop="Outer" /> <div hidden={true}> <span prop="Inner" /> </div> </div>, ); // Reveal the outer contents. The inner tree remains hidden. await act(() => { root.render(<App showOuter={true} showInner={false} />); }); assertLog(['Mount Outer']); expect(root).toMatchRenderedOutput( <div> <span prop="Outer" /> <div hidden={true}> <span prop="Inner" /> </div> </div>, ); }); describe('manual interactivity', () => { // @gate enableActivity it('should attach ref only for mode null', async () => { let offscreenRef; function App({mode}) { offscreenRef = useRef(null); return ( <Activity mode={mode} ref={ref => { offscreenRef.current = ref; }}> <div /> </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App mode={'manual'} />); }); expect(offscreenRef.current).not.toBeNull(); await act(() => { root.render(<App mode={'visible'} />); }); expect(offscreenRef.current).toBeNull(); await act(() => { root.render(<App mode={'hidden'} />); }); expect(offscreenRef.current).toBeNull(); await act(() => { root.render(<App mode={'manual'} />); }); expect(offscreenRef.current).not.toBeNull(); }); // @gate enableActivity it('should lower update priority for detached Activity', async () => { let updateChildState; let updateHighPriorityComponentState; let offscreenRef; function Child() { const [state, _stateUpdate] = useState(0); updateChildState = _stateUpdate; const text = 'Child ' + state; return <Text text={text} />; } function HighPriorityComponent(props) { const [state, _stateUpdate] = useState(0); updateHighPriorityComponentState = _stateUpdate; const text = 'HighPriorityComponent ' + state; return ( <> <Text text={text} /> {props.children} </> ); } function App() { offscreenRef = useRef(null); return ( <> <HighPriorityComponent> <Activity mode={'manual'} ref={offscreenRef}> <Child /> </Activity> </HighPriorityComponent> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['HighPriorityComponent 0', 'Child 0']); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 0" /> <span prop="Child 0" /> </>, ); expect(offscreenRef.current).not.toBeNull(); // Activity is attached by default. State updates from offscreen are **not defered**. await act(async () => { updateChildState(1); updateHighPriorityComponentState(1); await waitForPaint(['HighPriorityComponent 1', 'Child 1']); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 1" /> <span prop="Child 1" /> </>, ); }); await act(() => { offscreenRef.current.detach(); }); // Activity is detached. State updates from offscreen are **defered**. await act(async () => { updateChildState(2); updateHighPriorityComponentState(2); await waitForPaint(['HighPriorityComponent 2']); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 2" /> <span prop="Child 1" /> </>, ); }); assertLog(['Child 2']); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 2" /> <span prop="Child 2" /> </>, ); await act(() => { offscreenRef.current.attach(); }); // Activity is attached. State updates from offscreen are **not defered**. await act(async () => { updateChildState(3); updateHighPriorityComponentState(3); await waitForPaint(['HighPriorityComponent 3', 'Child 3']); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 3" /> <span prop="Child 3" /> </>, ); }); }); // @gate enableActivity it('defers detachment if called during commit', async () => { let updateChildState; let updateHighPriorityComponentState; let offscreenRef; let nextRenderTriggerDetach = false; let nextRenderTriggerAttach = false; function Child() { const [state, _stateUpdate] = useState(0); updateChildState = _stateUpdate; const text = 'Child ' + state; return <Text text={text} />; } function HighPriorityComponent(props) { const [state, _stateUpdate] = useState(0); updateHighPriorityComponentState = _stateUpdate; const text = 'HighPriorityComponent ' + state; useLayoutEffect(() => { if (nextRenderTriggerDetach) { _stateUpdate(state + 1); updateChildState(state + 1); offscreenRef.current.detach(); nextRenderTriggerDetach = false; } if (nextRenderTriggerAttach) { offscreenRef.current.attach(); nextRenderTriggerAttach = false; } }); return ( <> <Text text={text} /> {props.children} </> ); } function App() { offscreenRef = useRef(null); return ( <> <HighPriorityComponent> <Activity mode={'manual'} ref={offscreenRef}> <Child /> </Activity> </HighPriorityComponent> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['HighPriorityComponent 0', 'Child 0']); nextRenderTriggerDetach = true; // Activity is attached and gets detached inside useLayoutEffect. // State updates from offscreen are **defered**. await act(async () => { updateChildState(1); updateHighPriorityComponentState(1); await waitForPaint([ 'HighPriorityComponent 1', 'Child 1', 'HighPriorityComponent 2', ]); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 2" /> <span prop="Child 1" /> </>, ); }); assertLog(['Child 2']); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 2" /> <span prop="Child 2" /> </>, ); nextRenderTriggerAttach = true; // Activity is detached. State updates from offscreen are **defered**. // Activity is attached inside useLayoutEffect; await act(async () => { updateChildState(3); updateHighPriorityComponentState(3); await waitForPaint(['HighPriorityComponent 3', 'Child 3']); expect(root).toMatchRenderedOutput( <> <span prop="HighPriorityComponent 3" /> <span prop="Child 3" /> </>, ); }); }); }); // @gate enableActivity it('should detach ref if Activity is unmounted', async () => { let offscreenRef; function App({showOffscreen}) { offscreenRef = useRef(null); return showOffscreen ? ( <Activity mode={'manual'} ref={ref => { offscreenRef.current = ref; }}> <div /> </Activity> ) : null; } const root = ReactNoop.createRoot(); await act(() => { root.render(<App showOffscreen={true} />); }); expect(offscreenRef.current).not.toBeNull(); await act(() => { root.render(<App showOffscreen={false} />); }); expect(offscreenRef.current).toBeNull(); await act(() => { root.render(<App showOffscreen={true} />); }); expect(offscreenRef.current).not.toBeNull(); }); // @gate enableActivity it('should detach ref when parent Activity is hidden', async () => { let offscreenRef; function App({mode}) { offscreenRef = useRef(null); return ( <Activity mode={mode}> <Activity mode={'manual'} ref={offscreenRef}> <div /> </Activity> </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App mode={'hidden'} />); }); expect(offscreenRef.current).toBeNull(); await act(() => { root.render(<App mode={'visible'} />); }); expect(offscreenRef.current).not.toBeNull(); await act(() => { root.render(<App mode={'hidden'} />); }); expect(offscreenRef.current).toBeNull(); }); // @gate enableActivity it('should change _current', async () => { let offscreenRef; const root = ReactNoop.createRoot(); function App({children}) { offscreenRef = useRef(null); return ( <Activity mode={'manual'} ref={offscreenRef}> {children} </Activity> ); } await act(() => { root.render( <App> <div /> </App>, ); }); expect(offscreenRef.current).not.toBeNull(); const firstFiber = offscreenRef.current._current; await act(() => { root.render( <App> <span /> </App>, ); }); expect(offscreenRef.current._current === firstFiber).toBeFalsy(); }); // @gate enableActivity it('does not mount tree until attach is called', async () => { let offscreenRef; let spanRef; function Child() { spanRef = useRef(null); useEffect(() => { Scheduler.log('Mount Child'); return () => { Scheduler.log('Unmount Child'); }; }); useLayoutEffect(() => { Scheduler.log('Mount Layout Child'); return () => { Scheduler.log('Unmount Layout Child'); }; }); return <span ref={spanRef}>Child</span>; } function App() { return ( <Activity mode={'manual'} ref={el => (offscreenRef = el)}> <Child /> </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); expect(offscreenRef).not.toBeNull(); expect(spanRef.current).not.toBeNull(); assertLog(['Mount Layout Child', 'Mount Child']); await act(() => { offscreenRef.detach(); }); expect(spanRef.current).toBeNull(); assertLog(['Unmount Layout Child', 'Unmount Child']); // Calling attach on already attached Activity. await act(() => { offscreenRef.detach(); }); assertLog([]); await act(() => { offscreenRef.attach(); }); expect(spanRef.current).not.toBeNull(); assertLog(['Mount Layout Child', 'Mount Child']); // Calling attach on already attached Activity offscreenRef.attach(); assertLog([]); }); // @gate enableActivity it('handles nested manual offscreens', async () => { let outerOffscreen; let innerOffscreen; function App() { return ( <LoggedText text={'outer'}> <Activity mode={'manual'} ref={el => (outerOffscreen = el)}> <LoggedText text={'middle'}> <Activity mode={'manual'} ref={el => (innerOffscreen = el)}> <LoggedText text={'inner'} /> </Activity> </LoggedText> </Activity> </LoggedText> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog([ 'outer', 'middle', 'inner', 'mount layout inner', 'mount layout middle', 'mount layout outer', 'mount inner', 'mount middle', 'mount outer', ]); expect(outerOffscreen).not.toBeNull(); expect(innerOffscreen).not.toBeNull(); await act(() => { outerOffscreen.detach(); }); expect(innerOffscreen).toBeNull(); assertLog([ 'unmount layout middle', 'unmount layout inner', 'unmount middle', 'unmount inner', ]); await act(() => { outerOffscreen.attach(); }); assertLog([ 'mount layout inner', 'mount layout middle', 'mount inner', 'mount middle', ]); await act(() => { innerOffscreen.detach(); }); assertLog(['unmount layout inner', 'unmount inner']); // Calling detach on already detached Activity. await act(() => { innerOffscreen.detach(); }); assertLog([]); await act(() => { innerOffscreen.attach(); }); assertLog(['mount layout inner', 'mount inner']); await act(() => { innerOffscreen.detach(); outerOffscreen.attach(); }); assertLog(['unmount layout inner', 'unmount inner']); }); // @gate enableActivity it('batches multiple attach and detach calls scheduled from an event handler', async () => { function Child() { useEffect(() => { Scheduler.log('attach child'); return () => { Scheduler.log('detach child'); }; }, []); return 'child'; } const offscreen = React.createRef(null); function App() { return ( <Activity ref={offscreen} mode="manual"> <Child /> </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['attach child']); await act(() => { const instance = offscreen.current; // Detach then immediately attach the instance. instance.detach(); instance.attach(); }); assertLog([]); await act(() => { const instance = offscreen.current; instance.detach(); }); assertLog(['detach child']); await act(() => { const instance = offscreen.current; // Attach then immediately detach. instance.attach(); instance.detach(); }); assertLog([]); }); // @gate enableActivity it('batches multiple attach and detach calls scheduled from an effect', async () => { function Child() { useEffect(() => { Scheduler.log('attach child'); return () => { Scheduler.log('detach child'); }; }, []); return 'child'; } function App() { const offscreen = useRef(null); useLayoutEffect(() => { const instance = offscreen.current; // Detach then immediately attach the instance. instance.detach(); instance.attach(); }, []); return ( <Activity ref={offscreen} mode="manual"> <Child /> </Activity> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['attach child']); }); });
25.128578
119
0.533482
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ let React; let DOMAct; let TestRenderer; let TestAct; global.__DEV__ = process.env.NODE_ENV !== 'production'; expect.extend(require('../toWarnDev')); describe('unmocked scheduler', () => { beforeEach(() => { jest.resetModules(); React = require('react'); DOMAct = React.unstable_act; TestRenderer = require('react-test-renderer'); TestAct = TestRenderer.act; }); it('flushes work only outside the outermost act() corresponding to its own renderer', () => { let log = []; function Effecty() { React.useEffect(() => { log.push('called'); }, []); return null; } // in legacy mode, this tests whether an act only flushes its own effects TestAct(() => { DOMAct(() => { TestRenderer.create(<Effecty />); }); expect(log).toEqual([]); }); expect(log).toEqual(['called']); log = []; // for doublechecking, we flip it inside out, and assert on the outermost DOMAct(() => { TestAct(() => { TestRenderer.create(<Effecty />); }); expect(log).toEqual([]); }); expect(log).toEqual(['called']); }); }); describe('mocked scheduler', () => { beforeEach(() => { jest.resetModules(); jest.mock('scheduler', () => require.requireActual('scheduler/unstable_mock') ); React = require('react'); DOMAct = React.unstable_act; TestRenderer = require('react-test-renderer'); TestAct = TestRenderer.act; }); afterEach(() => { jest.unmock('scheduler'); }); it('flushes work only outside the outermost act()', () => { let log = []; function Effecty() { React.useEffect(() => { log.push('called'); }, []); return null; } // with a mocked scheduler, this tests whether it flushes all work only on the outermost act TestAct(() => { DOMAct(() => { TestRenderer.create(<Effecty />); }); expect(log).toEqual([]); }); expect(log).toEqual(['called']); log = []; // for doublechecking, we flip it inside out, and assert on the outermost DOMAct(() => { TestAct(() => { TestRenderer.create(<Effecty />); }); expect(log).toEqual([]); }); expect(log).toEqual(['called']); }); });
23.683168
96
0.567416
PenetrationTestingScripts
import {printStore} from 'react-devtools-shared/src/devtools/utils'; // test() is part of Jest's serializer API export function test(maybeState) { if (maybeState === null || typeof maybeState !== 'object') { return false; } const hasOwnProperty = Object.prototype.hasOwnProperty.bind(maybeState); // Duck typing at its finest. return ( hasOwnProperty('inspectedElementID') && hasOwnProperty('ownerFlatTree') && hasOwnProperty('ownerSubtreeLeafElementID') ); } // print() is part of Jest's serializer API export function print(state, serialize, indent) { // This is a big of a hack but it works around having to pass in a meta object e.g. {store, state}. // DevTools tests depend on a global Store object anyway (initialized via setupTest). const store = global.store; return printStore(store, false, state); }
31.730769
101
0.716471
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-4E
// @flow let size: number = -1; // This utility copied from "dom-helpers" package. export function getScrollbarSize(recalculate?: boolean = false): number { if (size === -1 || recalculate) { const div = document.createElement('div'); const style = div.style; style.width = '50px'; style.height = '50px'; style.overflow = 'scroll'; ((document.body: any): HTMLBodyElement).appendChild(div); size = div.offsetWidth - div.clientWidth; ((document.body: any): HTMLBodyElement).removeChild(div); } return size; } export type RTLOffsetType = | 'negative' | 'positive-descending' | 'positive-ascending'; let cachedRTLResult: RTLOffsetType | null = null; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements. // Chrome does not seem to adhere; its scrollLeft values are positive (measured relative to the left). // Safari's elastic bounce makes detecting this even more complicated wrt potential false positives. // The safest way to check this is to intentionally set a negative offset, // and then verify that the subsequent "scroll" event matches the negative offset. // If it does not match, then we can assume a non-standard RTL scroll implementation. export function getRTLOffsetType(recalculate?: boolean = false): RTLOffsetType { if (cachedRTLResult === null || recalculate) { const outerDiv = document.createElement('div'); const outerStyle = outerDiv.style; outerStyle.width = '50px'; outerStyle.height = '50px'; outerStyle.overflow = 'scroll'; outerStyle.direction = 'rtl'; const innerDiv = document.createElement('div'); const innerStyle = innerDiv.style; innerStyle.width = '100px'; innerStyle.height = '100px'; outerDiv.appendChild(innerDiv); ((document.body: any): HTMLBodyElement).appendChild(outerDiv); if (outerDiv.scrollLeft > 0) { cachedRTLResult = 'positive-descending'; } else { outerDiv.scrollLeft = 1; if (outerDiv.scrollLeft === 0) { cachedRTLResult = 'negative'; } else { cachedRTLResult = 'positive-ascending'; } } ((document.body: any): HTMLBodyElement).removeChild(outerDiv); return cachedRTLResult; } return cachedRTLResult; }
30
102
0.69275
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 */ const assign = Object.assign; export default assign;
18.923077
66
0.705426
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type Source = { fileName: string, lineNumber: number, }; export type ReactElement = { $$typeof: any, type: any, key: any, ref: any, props: any, // ReactFiber _owner: any, // __DEV__ _store: {validated: boolean, ...}, _self: React$Element<any>, _shadowChildren: any, _source: Source, };
16.6
66
0.633776
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 type {Thenable} from 'shared/ReactTypes.js'; import type {Response as FlightResponse} from 'react-client/src/ReactFlightClient'; import type {ReactServerValue} from 'react-client/src/ReactFlightReplyClient'; import { createResponse, getRoot, reportGlobalError, processBinaryChunk, close, } from 'react-client/src/ReactFlightClient'; import { processReply, createServerReference, } from 'react-client/src/ReactFlightReplyClient'; type CallServerCallback = <A, T>(string, args: A) => Promise<T>; export type Options = { callServer?: CallServerCallback, }; function createResponseFromOptions(options: void | Options) { return createResponse( null, null, options && options.callServer ? options.callServer : undefined, undefined, // nonce ); } function startReadingFromStream( response: FlightResponse, stream: ReadableStream, ): void { const reader = stream.getReader(); function progress({ done, value, }: { done: boolean, value: ?any, ... }): void | Promise<void> { if (done) { close(response); return; } const buffer: Uint8Array = (value: any); processBinaryChunk(response, buffer); return reader.read().then(progress).catch(error); } function error(e: any) { reportGlobalError(response, e); } reader.read().then(progress).catch(error); } function createFromReadableStream<T>( stream: ReadableStream, options?: Options, ): Thenable<T> { const response: FlightResponse = createResponseFromOptions(options); startReadingFromStream(response, stream); return getRoot(response); } function createFromFetch<T>( promiseForResponse: Promise<Response>, options?: Options, ): Thenable<T> { const response: FlightResponse = createResponseFromOptions(options); promiseForResponse.then( function (r) { startReadingFromStream(response, (r.body: any)); }, function (e) { reportGlobalError(response, e); }, ); return getRoot(response); } function encodeReply( value: ReactServerValue, ): Promise< string | URLSearchParams | FormData, > /* We don't use URLSearchParams yet but maybe */ { return new Promise((resolve, reject) => { processReply(value, '', resolve, reject); }); } export { createFromFetch, createFromReadableStream, encodeReply, createServerReference, };
21.839286
83
0.700039
owtf
import React from 'react'; import {useState, Suspense} from 'react'; import {BrowserRouter, Switch, Route} from 'react-router-dom'; import HomePage from './HomePage'; import AboutPage from './AboutPage'; import ThemeContext from './shared/ThemeContext'; export default function App() { const [theme, setTheme] = useState('slategrey'); function handleToggleClick() { if (theme === 'slategrey') { setTheme('hotpink'); } else { setTheme('slategrey'); } } return ( <BrowserRouter> <ThemeContext.Provider value={theme}> <div style={{fontFamily: 'sans-serif'}}> <div style={{ margin: 20, padding: 20, border: '1px solid black', minHeight: 300, }}> <button onClick={handleToggleClick}>Toggle Theme Context</button> <br /> <Suspense fallback={<Spinner />}> <Switch> <Route path="/about"> <AboutPage /> </Route> <Route path="/"> <HomePage /> </Route> </Switch> </Suspense> </div> </div> </ThemeContext.Provider> </BrowserRouter> ); } function Spinner() { return null; }
23.811321
77
0.512938
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFlightServer';
21.363636
66
0.693878
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'); const ReactFeatureFlags = require('shared/ReactFeatureFlags'); let React; let ReactDOM; let ReactTestUtils; let ReactDOMServer; 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, clientCleanRender} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('property to attribute mapping', function () { describe('string properties', function () { itRenders('simple numbers', async render => { const e = await render(<div width={30} />); expect(e.getAttribute('width')).toBe('30'); }); itRenders('simple strings', async render => { const e = await render(<div width={'30'} />); expect(e.getAttribute('width')).toBe('30'); }); itRenders('no string prop with true value', async render => { const e = await render(<a href={true} />, 1); expect(e.hasAttribute('href')).toBe(false); }); itRenders('no string prop with false value', async render => { const e = await render(<a href={false} />, 1); expect(e.hasAttribute('href')).toBe(false); }); itRenders('no string prop with null value', async render => { const e = await render(<div width={null} />); expect(e.hasAttribute('width')).toBe(false); }); itRenders('no string prop with function value', async render => { const e = await render(<div width={function () {}} />, 1); expect(e.hasAttribute('width')).toBe(false); }); itRenders('no string prop with symbol value', async render => { const e = await render(<div width={Symbol('foo')} />, 1); expect(e.hasAttribute('width')).toBe(false); }); }); describe('boolean properties', function () { itRenders('boolean prop with true value', async render => { const e = await render(<div hidden={true} />); expect(e.getAttribute('hidden')).toBe(''); }); itRenders('boolean prop with false value', async render => { const e = await render(<div hidden={false} />); expect(e.getAttribute('hidden')).toBe(null); }); itRenders('boolean prop with self value', async render => { const e = await render(<div hidden="hidden" />); expect(e.getAttribute('hidden')).toBe(''); }); // this does not seem like correct behavior, since hidden="" in HTML indicates // that the boolean property is present. however, it is how the current code // behaves, so the test is included here. itRenders('boolean prop with "" value', async render => { const e = await render(<div hidden="" />); expect(e.getAttribute('hidden')).toBe(null); }); // this seems like it might mask programmer error, but it's existing behavior. itRenders('boolean prop with string value', async render => { const e = await render(<div hidden="foo" />); expect(e.getAttribute('hidden')).toBe(''); }); // this seems like it might mask programmer error, but it's existing behavior. itRenders('boolean prop with array value', async render => { const e = await render(<div hidden={['foo', 'bar']} />); expect(e.getAttribute('hidden')).toBe(''); }); // this seems like it might mask programmer error, but it's existing behavior. itRenders('boolean prop with object value', async render => { const e = await render(<div hidden={{foo: 'bar'}} />); expect(e.getAttribute('hidden')).toBe(''); }); // this seems like it might mask programmer error, but it's existing behavior. itRenders('boolean prop with non-zero number value', async render => { const e = await render(<div hidden={10} />); expect(e.getAttribute('hidden')).toBe(''); }); // this seems like it might mask programmer error, but it's existing behavior. itRenders('boolean prop with zero value', async render => { const e = await render(<div hidden={0} />); expect(e.getAttribute('hidden')).toBe(null); }); itRenders('no boolean prop with null value', async render => { const e = await render(<div hidden={null} />); expect(e.hasAttribute('hidden')).toBe(false); }); itRenders('no boolean prop with function value', async render => { const e = await render(<div hidden={function () {}} />, 1); expect(e.hasAttribute('hidden')).toBe(false); }); itRenders('no boolean prop with symbol value', async render => { const e = await render(<div hidden={Symbol('foo')} />, 1); expect(e.hasAttribute('hidden')).toBe(false); }); }); describe('download property (combined boolean/string attribute)', function () { itRenders('download prop with true value', async render => { const e = await render(<a download={true} />); expect(e.getAttribute('download')).toBe(''); }); itRenders('download prop with false value', async render => { const e = await render(<a download={false} />); expect(e.getAttribute('download')).toBe(null); }); itRenders('download prop with string value', async render => { const e = await render(<a download="myfile" />); expect(e.getAttribute('download')).toBe('myfile'); }); itRenders('download prop with string "false" value', async render => { const e = await render(<a download="false" />); expect(e.getAttribute('download')).toBe('false'); }); itRenders('download prop with string "true" value', async render => { const e = await render(<a download={'true'} />); expect(e.getAttribute('download')).toBe('true'); }); itRenders('download prop with number 0 value', async render => { const e = await render(<a download={0} />); expect(e.getAttribute('download')).toBe('0'); }); itRenders('no download prop with null value', async render => { const e = await render(<div download={null} />); expect(e.hasAttribute('download')).toBe(false); }); itRenders('no download prop with undefined value', async render => { const e = await render(<div download={undefined} />); expect(e.hasAttribute('download')).toBe(false); }); itRenders('no download prop with function value', async render => { const e = await render(<div download={function () {}} />, 1); expect(e.hasAttribute('download')).toBe(false); }); itRenders('no download prop with symbol value', async render => { const e = await render(<div download={Symbol('foo')} />, 1); expect(e.hasAttribute('download')).toBe(false); }); }); describe('className property', function () { itRenders('className prop with string value', async render => { const e = await render(<div className="myClassName" />); expect(e.getAttribute('class')).toBe('myClassName'); }); itRenders('className prop with empty string value', async render => { const e = await render(<div className="" />); expect(e.getAttribute('class')).toBe(''); }); itRenders('no className prop with true value', async render => { const e = await render(<div className={true} />, 1); expect(e.hasAttribute('class')).toBe(false); }); itRenders('no className prop with false value', async render => { const e = await render(<div className={false} />, 1); expect(e.hasAttribute('class')).toBe(false); }); itRenders('no className prop with null value', async render => { const e = await render(<div className={null} />); expect(e.hasAttribute('className')).toBe(false); }); itRenders('badly cased className with a warning', async render => { const e = await render(<div classname="test" />, 1); expect(e.hasAttribute('class')).toBe(false); expect(e.hasAttribute('classname')).toBe(true); }); itRenders( 'className prop when given the alias with a warning', async render => { const e = await render(<div class="test" />, 1); expect(e.className).toBe('test'); }, ); itRenders( 'className prop when given a badly cased alias', async render => { const e = await render(<div cLASs="test" />, 1); expect(e.className).toBe('test'); }, ); }); describe('htmlFor property', function () { itRenders('htmlFor with string value', async render => { const e = await render(<div htmlFor="myFor" />); expect(e.getAttribute('for')).toBe('myFor'); }); itRenders('no badly cased htmlfor', async render => { const e = await render(<div htmlfor="myFor" />, 1); expect(e.hasAttribute('for')).toBe(false); expect(e.getAttribute('htmlfor')).toBe('myFor'); }); itRenders('htmlFor with an empty string', async render => { const e = await render(<div htmlFor="" />); expect(e.getAttribute('for')).toBe(''); }); itRenders('no htmlFor prop with true value', async render => { const e = await render(<div htmlFor={true} />, 1); expect(e.hasAttribute('for')).toBe(false); }); itRenders('no htmlFor prop with false value', async render => { const e = await render(<div htmlFor={false} />, 1); expect(e.hasAttribute('for')).toBe(false); }); itRenders('no htmlFor prop with null value', async render => { const e = await render(<div htmlFor={null} />); expect(e.hasAttribute('htmlFor')).toBe(false); }); }); describe('numeric properties', function () { itRenders( 'positive numeric property with positive value', async render => { const e = await render(<input size={2} />); expect(e.getAttribute('size')).toBe('2'); }, ); itRenders('numeric property with zero value', async render => { const e = await render(<ol start={0} />); expect(e.getAttribute('start')).toBe('0'); }); itRenders( 'no positive numeric property with zero value', async render => { const e = await render(<input size={0} />); expect(e.hasAttribute('size')).toBe(false); }, ); itRenders('no numeric prop with function value', async render => { const e = await render(<ol start={function () {}} />, 1); expect(e.hasAttribute('start')).toBe(false); }); itRenders('no numeric prop with symbol value', async render => { const e = await render(<ol start={Symbol('foo')} />, 1); expect(e.hasAttribute('start')).toBe(false); }); itRenders( 'no positive numeric prop with function value', async render => { const e = await render(<input size={function () {}} />, 1); expect(e.hasAttribute('size')).toBe(false); }, ); itRenders('no positive numeric prop with symbol value', async render => { const e = await render(<input size={Symbol('foo')} />, 1); expect(e.hasAttribute('size')).toBe(false); }); }); describe('props with special meaning in React', function () { itRenders('no ref attribute', async render => { class RefComponent extends React.Component { render() { return <div ref={React.createRef()} />; } } const e = await render(<RefComponent />); expect(e.getAttribute('ref')).toBe(null); }); itRenders('no children attribute', async render => { const e = await render(React.createElement('div', {}, 'foo')); expect(e.getAttribute('children')).toBe(null); }); itRenders('no key attribute', async render => { const e = await render(<div key="foo" />); expect(e.getAttribute('key')).toBe(null); }); itRenders('no dangerouslySetInnerHTML attribute', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: '<foo />'}} />, ); expect(e.getAttribute('dangerouslySetInnerHTML')).toBe(null); }); itRenders('no suppressContentEditableWarning attribute', async render => { const e = await render(<div suppressContentEditableWarning={true} />); expect(e.getAttribute('suppressContentEditableWarning')).toBe(null); }); itRenders('no suppressHydrationWarning attribute', async render => { const e = await render(<span suppressHydrationWarning={true} />); expect(e.getAttribute('suppressHydrationWarning')).toBe(null); }); }); describe('inline styles', function () { itRenders('simple styles', async render => { const e = await render(<div style={{color: 'red', width: '30px'}} />); expect(e.style.color).toBe('red'); expect(e.style.width).toBe('30px'); }); itRenders('relevant styles with px', async render => { const e = await render( <div style={{ left: 0, margin: 16, opacity: 0.5, padding: '4px', }} />, ); expect(e.style.left).toBe('0px'); expect(e.style.margin).toBe('16px'); expect(e.style.opacity).toBe('0.5'); expect(e.style.padding).toBe('4px'); }); itRenders('custom properties', async render => { const e = await render(<div style={{'--foo': 5}} />); expect(e.style.getPropertyValue('--foo')).toBe('5'); }); itRenders('camel cased custom properties', async render => { const e = await render(<div style={{'--someColor': '#000000'}} />); expect(e.style.getPropertyValue('--someColor')).toBe('#000000'); }); itRenders('no undefined styles', async render => { const e = await render( <div style={{color: undefined, width: '30px'}} />, ); expect(e.style.color).toBe(''); expect(e.style.width).toBe('30px'); }); itRenders('no null styles', async render => { const e = await render(<div style={{color: null, width: '30px'}} />); expect(e.style.color).toBe(''); expect(e.style.width).toBe('30px'); }); itRenders('no empty styles', async render => { const e = await render(<div style={{color: null, width: null}} />); expect(e.style.color).toBe(''); expect(e.style.width).toBe(''); expect(e.hasAttribute('style')).toBe(false); }); itRenders('unitless-number rules with prefixes', async render => { const {style} = await render( <div style={{ lineClamp: 10, // TODO: requires https://github.com/jsdom/cssstyle/pull/112 // WebkitLineClamp: 10, // TODO: revisit once cssstyle or jsdom figures out // if they want to support other vendors or not // MozFlexGrow: 10, // msFlexGrow: 10, // msGridRow: 10, // msGridRowEnd: 10, // msGridRowSpan: 10, // msGridRowStart: 10, // msGridColumn: 10, // msGridColumnEnd: 10, // msGridColumnSpan: 10, // msGridColumnStart: 10, }} />, ); expect(style.lineClamp).toBe('10'); // see comment at inline styles above // expect(style.WebkitLineClamp).toBe('10'); // expect(style.MozFlexGrow).toBe('10'); // jsdom is inconsistent in the style property name // it uses on the client and when processing server markup. // But it should be there either way. //expect(style.MsFlexGrow || style.msFlexGrow).toBe('10'); // expect(style.MsGridRow || style.msGridRow).toBe('10'); // expect(style.MsGridRowEnd || style.msGridRowEnd).toBe('10'); // expect(style.MsGridRowSpan || style.msGridRowSpan).toBe('10'); // expect(style.MsGridRowStart || style.msGridRowStart).toBe('10'); // expect(style.MsGridColumn || style.msGridColumn).toBe('10'); // expect(style.MsGridColumnEnd || style.msGridColumnEnd).toBe('10'); // expect(style.MsGridColumnSpan || style.msGridColumnSpan).toBe('10'); // expect(style.MsGridColumnStart || style.msGridColumnStart).toBe('10'); }); }); describe('aria attributes', function () { itRenders('simple strings', async render => { const e = await render(<div aria-label="hello" />); expect(e.getAttribute('aria-label')).toBe('hello'); }); // this probably is just masking programmer error, but it is existing behavior. itRenders('aria string prop with false value', async render => { const e = await render(<div aria-label={false} />); expect(e.getAttribute('aria-label')).toBe('false'); }); itRenders('no aria prop with null value', async render => { const e = await render(<div aria-label={null} />); expect(e.hasAttribute('aria-label')).toBe(false); }); itRenders('"aria" attribute with a warning', async render => { // Reserved for future use. const e = await render(<div aria="hello" />, 1); expect(e.getAttribute('aria')).toBe('hello'); }); }); describe('cased attributes', function () { itRenders( 'badly cased aliased HTML attribute with a warning', async render => { const e = await render(<form acceptcharset="utf-8" />, 1); expect(e.hasAttribute('accept-charset')).toBe(false); expect(e.getAttribute('acceptcharset')).toBe('utf-8'); }, ); itRenders('badly cased SVG attribute with a warning', async render => { const e = await render( <svg> <text textlength="10" /> </svg>, 1, ); // The discrepancy is expected as long as we emit a warning // both on the client and the server. if (render === clientCleanRender) { // On the client, "textlength" is treated as a case-sensitive // SVG attribute so the wrong attribute ("textlength") gets set. expect(e.firstChild.getAttribute('textlength')).toBe('10'); expect(e.firstChild.hasAttribute('textLength')).toBe(false); } else { // When parsing HTML (including the hydration case), the browser // correctly maps "textlength" to "textLength" SVG attribute. // So it happens to work on the initial render. expect(e.firstChild.getAttribute('textLength')).toBe('10'); expect(e.firstChild.hasAttribute('textlength')).toBe(false); } }); itRenders('no badly cased aliased SVG attribute alias', async render => { const e = await render( <svg> <text strokedasharray="10 10" /> </svg>, 1, ); expect(e.firstChild.hasAttribute('stroke-dasharray')).toBe(false); expect(e.firstChild.getAttribute('strokedasharray')).toBe('10 10'); }); itRenders( 'no badly cased original SVG attribute that is aliased', async render => { const e = await render( <svg> <text stroke-dasharray="10 10" /> </svg>, 1, ); expect(e.firstChild.getAttribute('stroke-dasharray')).toBe('10 10'); }, ); }); describe('unknown attributes', function () { itRenders('unknown attributes', async render => { const e = await render(<div foo="bar" />); expect(e.getAttribute('foo')).toBe('bar'); }); itRenders('unknown data- attributes', async render => { const e = await render(<div data-foo="bar" />); expect(e.getAttribute('data-foo')).toBe('bar'); }); itRenders('badly cased reserved attributes', async render => { const e = await render(<div CHILDREN="5" />, 1); expect(e.getAttribute('CHILDREN')).toBe('5'); }); itRenders('"data" attribute', async render => { // For `<object />` acts as `src`. const e = await render(<object data="hello" />); expect(e.getAttribute('data')).toBe('hello'); }); itRenders('no unknown data- attributes with null value', async render => { const e = await render(<div data-foo={null} />); expect(e.hasAttribute('data-foo')).toBe(false); }); itRenders('unknown data- attributes with casing', async render => { const e = await render(<div data-fooBar="true" />, 1); expect(e.getAttribute('data-foobar')).toBe('true'); }); itRenders('unknown data- attributes with boolean true', async render => { const e = await render(<div data-foobar={true} />); expect(e.getAttribute('data-foobar')).toBe('true'); }); itRenders('unknown data- attributes with boolean false', async render => { const e = await render(<div data-foobar={false} />); expect(e.getAttribute('data-foobar')).toBe('false'); }); itRenders( 'no unknown data- attributes with casing and null value', async render => { const e = await render(<div data-fooBar={null} />, 1); expect(e.hasAttribute('data-foobar')).toBe(false); }, ); itRenders('custom attributes for non-standard elements', async render => { // This test suite generally assumes that we get exactly // the same warnings (or none) for all scenarios including // SSR + innerHTML, hydration, and client-side rendering. // However this particular warning fires only when creating // DOM nodes on the client side. We force it to fire early // so that it gets deduplicated later, and doesn't fail the test. expect(() => { ReactDOM.render(<nonstandard />, document.createElement('div')); }).toErrorDev('The tag <nonstandard> is unrecognized in this browser.'); const e = await render(<nonstandard foo="bar" />); expect(e.getAttribute('foo')).toBe('bar'); }); itRenders('SVG tags with dashes in them', async render => { const e = await render( <svg> <font-face accentHeight={10} /> </svg>, ); expect(e.firstChild.hasAttribute('accentHeight')).toBe(false); expect(e.firstChild.getAttribute('accent-height')).toBe('10'); }); itRenders('cased custom attributes', async render => { const e = await render(<div fooBar="test" />, 1); expect(e.getAttribute('foobar')).toBe('test'); }); }); itRenders('no HTML events', async render => { const e = await render(<div onClick={() => {}} />); expect(e.getAttribute('onClick')).toBe(null); expect(e.getAttribute('onClick')).toBe(null); expect(e.getAttribute('click')).toBe(null); }); itRenders('no unknown events', async render => { const e = await render(<div onunknownevent='alert("hack")' />, 1); expect(e.getAttribute('onunknownevent')).toBe(null); }); itRenders('custom attribute named `on`', async render => { const e = await render(<div on="tap:do-something" />); expect(e.getAttribute('on')).toEqual('tap:do-something'); }); }); // These tests mostly verify the existing behavior. // It may not always make sense but we can't change it in minors. describe('custom elements', () => { itRenders('class for custom elements', async render => { const e = await render(<div is="custom-element" class="test" />, 0); expect(e.getAttribute('class')).toBe('test'); }); itRenders('className for is elements', async render => { const e = await render(<div is="custom-element" className="test" />, 0); expect(e.getAttribute('className')).toBe(null); expect(e.getAttribute('class')).toBe('test'); }); itRenders('className for custom elements', async render => { const e = await render(<custom-element className="test" />, 0); if (ReactFeatureFlags.enableCustomElementPropertySupport) { expect(e.getAttribute('className')).toBe(null); expect(e.getAttribute('class')).toBe('test'); } else { expect(e.getAttribute('className')).toBe('test'); expect(e.getAttribute('class')).toBe(null); } }); itRenders('htmlFor property on is elements', async render => { const e = await render(<div is="custom-element" htmlFor="test" />); expect(e.getAttribute('htmlFor')).toBe(null); expect(e.getAttribute('for')).toBe('test'); }); itRenders('htmlFor attribute on custom elements', async render => { const e = await render(<custom-element htmlFor="test" />); expect(e.getAttribute('htmlFor')).toBe('test'); expect(e.getAttribute('for')).toBe(null); }); itRenders('for attribute on custom elements', async render => { const e = await render(<div is="custom-element" for="test" />); expect(e.getAttribute('htmlFor')).toBe(null); expect(e.getAttribute('for')).toBe('test'); }); itRenders('unknown attributes for custom elements', async render => { const e = await render(<custom-element foo="bar" />); expect(e.getAttribute('foo')).toBe('bar'); }); itRenders('unknown `on*` attributes for custom elements', async render => { const e = await render(<custom-element onunknown="bar" />); expect(e.getAttribute('onunknown')).toBe('bar'); }); itRenders('unknown boolean `true` attributes as strings', async render => { const e = await render(<custom-element foo={true} />); if (ReactFeatureFlags.enableCustomElementPropertySupport) { expect(e.getAttribute('foo')).toBe(''); } else { expect(e.getAttribute('foo')).toBe('true'); } }); itRenders('unknown boolean `false` attributes as strings', async render => { const e = await render(<custom-element foo={false} />); if (ReactFeatureFlags.enableCustomElementPropertySupport) { expect(e.getAttribute('foo')).toBe(null); } else { expect(e.getAttribute('foo')).toBe('false'); } }); itRenders( 'no unknown attributes for custom elements with null value', async render => { const e = await render(<custom-element foo={null} />); expect(e.hasAttribute('foo')).toBe(false); }, ); itRenders( 'unknown attributes for custom elements using is', async render => { const e = await render(<div is="custom-element" foo="bar" />); expect(e.getAttribute('foo')).toBe('bar'); }, ); itRenders( 'no unknown attributes for custom elements using is with null value', async render => { const e = await render(<div is="custom-element" foo={null} />); expect(e.hasAttribute('foo')).toBe(false); }, ); }); });
36.477212
93
0.584147
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './ReactDOMFizzServerBun.js';
21.636364
66
0.697581
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. */ 'use strict'; let React; let ReactNoop; let Scheduler; let act; let startTransition; let useDeferredValue; let useMemo; let useState; let Suspense; let Activity; let assertLog; let waitForPaint; let textCache; describe('ReactDeferredValue', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; startTransition = React.startTransition; useDeferredValue = React.useDeferredValue; useMemo = React.useMemo; useState = React.useState; Suspense = React.Suspense; Activity = React.unstable_Activity; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; waitForPaint = InternalTestUtils.waitForPaint; textCache = new Map(); }); function resolveText(text) { const record = textCache.get(text); if (record === undefined) { const newRecord = { status: 'resolved', value: text, }; textCache.set(text, newRecord); } else if (record.status === 'pending') { const thenable = record.value; record.status = 'resolved'; record.value = text; thenable.pings.forEach(t => t()); } } function readText(text) { const record = textCache.get(text); if (record !== undefined) { switch (record.status) { case 'pending': Scheduler.log(`Suspend! [${text}]`); throw record.value; case 'rejected': throw record.value; case 'resolved': return record.value; } } else { Scheduler.log(`Suspend! [${text}]`); const thenable = { pings: [], then(resolve) { if (newRecord.status === 'pending') { thenable.pings.push(resolve); } else { Promise.resolve().then(() => resolve(newRecord.value)); } }, }; const newRecord = { status: 'pending', value: thenable, }; textCache.set(text, newRecord); throw thenable; } } function Text({text}) { Scheduler.log(text); return text; } function AsyncText({text}) { readText(text); Scheduler.log(text); return text; } it('does not cause an infinite defer loop if the original value isn\t memoized', async () => { function App({value}) { // The object passed to useDeferredValue is never the same as the previous // render. A naive implementation would endlessly spawn deferred renders. const {value: deferredValue} = useDeferredValue({value}); const child = useMemo( () => <Text text={'Original: ' + value} />, [value], ); const deferredChild = useMemo( () => <Text text={'Deferred: ' + deferredValue} />, [deferredValue], ); return ( <div> <div>{child}</div> <div>{deferredChild}</div> </div> ); } const root = ReactNoop.createRoot(); // Initial render await act(() => { root.render(<App value={1} />); }); assertLog(['Original: 1', 'Deferred: 1']); // If it's an urgent update, the value is deferred await act(async () => { root.render(<App value={2} />); await waitForPaint(['Original: 2']); // The deferred value updates in a separate render await waitForPaint(['Deferred: 2']); }); expect(root).toMatchRenderedOutput( <div> <div>Original: 2</div> <div>Deferred: 2</div> </div>, ); // But if it updates during a transition, it doesn't defer await act(async () => { startTransition(() => { root.render(<App value={3} />); }); // The deferred value updates in the same render as the original await waitForPaint(['Original: 3', 'Deferred: 3']); }); expect(root).toMatchRenderedOutput( <div> <div>Original: 3</div> <div>Deferred: 3</div> </div>, ); }); it('does not defer during a transition', async () => { function App({value}) { const deferredValue = useDeferredValue(value); const child = useMemo( () => <Text text={'Original: ' + value} />, [value], ); const deferredChild = useMemo( () => <Text text={'Deferred: ' + deferredValue} />, [deferredValue], ); return ( <div> <div>{child}</div> <div>{deferredChild}</div> </div> ); } const root = ReactNoop.createRoot(); // Initial render await act(() => { root.render(<App value={1} />); }); assertLog(['Original: 1', 'Deferred: 1']); // If it's an urgent update, the value is deferred await act(async () => { root.render(<App value={2} />); await waitForPaint(['Original: 2']); // The deferred value updates in a separate render await waitForPaint(['Deferred: 2']); }); expect(root).toMatchRenderedOutput( <div> <div>Original: 2</div> <div>Deferred: 2</div> </div>, ); // But if it updates during a transition, it doesn't defer await act(async () => { startTransition(() => { root.render(<App value={3} />); }); // The deferred value updates in the same render as the original await waitForPaint(['Original: 3', 'Deferred: 3']); }); expect(root).toMatchRenderedOutput( <div> <div>Original: 3</div> <div>Deferred: 3</div> </div>, ); }); it("works if there's a render phase update", async () => { function App({value: propValue}) { const [value, setValue] = useState(null); if (value !== propValue) { setValue(propValue); } const deferredValue = useDeferredValue(value); const child = useMemo( () => <Text text={'Original: ' + value} />, [value], ); const deferredChild = useMemo( () => <Text text={'Deferred: ' + deferredValue} />, [deferredValue], ); return ( <div> <div>{child}</div> <div>{deferredChild}</div> </div> ); } const root = ReactNoop.createRoot(); // Initial render await act(() => { root.render(<App value={1} />); }); assertLog(['Original: 1', 'Deferred: 1']); // If it's an urgent update, the value is deferred await act(async () => { root.render(<App value={2} />); await waitForPaint(['Original: 2']); // The deferred value updates in a separate render await waitForPaint(['Deferred: 2']); }); expect(root).toMatchRenderedOutput( <div> <div>Original: 2</div> <div>Deferred: 2</div> </div>, ); // But if it updates during a transition, it doesn't defer await act(async () => { startTransition(() => { root.render(<App value={3} />); }); // The deferred value updates in the same render as the original await waitForPaint(['Original: 3', 'Deferred: 3']); }); expect(root).toMatchRenderedOutput( <div> <div>Original: 3</div> <div>Deferred: 3</div> </div>, ); }); it('regression test: during urgent update, reuse previous value, not initial value', async () => { function App({value: propValue}) { const [value, setValue] = useState(null); if (value !== propValue) { setValue(propValue); } const deferredValue = useDeferredValue(value); const child = useMemo( () => <Text text={'Original: ' + value} />, [value], ); const deferredChild = useMemo( () => <Text text={'Deferred: ' + deferredValue} />, [deferredValue], ); return ( <div> <div>{child}</div> <div>{deferredChild}</div> </div> ); } const root = ReactNoop.createRoot(); // Initial render await act(async () => { root.render(<App value={1} />); await waitForPaint(['Original: 1', 'Deferred: 1']); expect(root).toMatchRenderedOutput( <div> <div>Original: 1</div> <div>Deferred: 1</div> </div>, ); }); await act(async () => { startTransition(() => { root.render(<App value={2} />); }); // In the regression, the memoized value was not updated during non-urgent // updates, so this would flip the deferred value back to the initial // value (1) instead of reusing the current one (2). await waitForPaint(['Original: 2', 'Deferred: 2']); expect(root).toMatchRenderedOutput( <div> <div>Original: 2</div> <div>Deferred: 2</div> </div>, ); }); await act(async () => { root.render(<App value={3} />); await waitForPaint(['Original: 3']); expect(root).toMatchRenderedOutput( <div> <div>Original: 3</div> <div>Deferred: 2</div> </div>, ); await waitForPaint(['Deferred: 3']); expect(root).toMatchRenderedOutput( <div> <div>Original: 3</div> <div>Deferred: 3</div> </div>, ); }); }); // @gate enableUseDeferredValueInitialArg it('supports initialValue argument', async () => { function App() { const value = useDeferredValue('Final', 'Initial'); return <Text text={value} />; } const root = ReactNoop.createRoot(); await act(async () => { root.render(<App />); await waitForPaint(['Initial']); expect(root).toMatchRenderedOutput('Initial'); }); assertLog(['Final']); expect(root).toMatchRenderedOutput('Final'); }); // @gate enableUseDeferredValueInitialArg it('defers during initial render when initialValue is provided, even if render is not sync', async () => { function App() { const value = useDeferredValue('Final', 'Initial'); return <Text text={value} />; } const root = ReactNoop.createRoot(); await act(async () => { // Initial mount is a transition, but it should defer anyway startTransition(() => root.render(<App />)); await waitForPaint(['Initial']); expect(root).toMatchRenderedOutput('Initial'); }); assertLog(['Final']); expect(root).toMatchRenderedOutput('Final'); }); // @gate enableUseDeferredValueInitialArg it( 'if a suspended render spawns a deferred task, we can switch to the ' + 'deferred task without finishing the original one (no Suspense boundary)', async () => { function App() { const text = useDeferredValue('Final', 'Loading...'); return <AsyncText text={text} />; } const root = ReactNoop.createRoot(); await act(() => root.render(<App />)); assertLog([ 'Suspend! [Loading...]', // The initial value suspended, so we attempt the final value, which // also suspends. 'Suspend! [Final]', ]); expect(root).toMatchRenderedOutput(null); // The final value loads, so we can skip the initial value entirely. await act(() => resolveText('Final')); assertLog(['Final']); expect(root).toMatchRenderedOutput('Final'); // When the initial value finally loads, nothing happens because we no // longer need it. await act(() => resolveText('Loading...')); assertLog([]); expect(root).toMatchRenderedOutput('Final'); }, ); // @gate enableUseDeferredValueInitialArg it( 'if a suspended render spawns a deferred task, we can switch to the ' + 'deferred task without finishing the original one (no Suspense boundary, ' + 'synchronous parent update)', async () => { function App() { const text = useDeferredValue('Final', 'Loading...'); return <AsyncText text={text} />; } const root = ReactNoop.createRoot(); // TODO: This made me realize that we don't warn if an update spawns a // deferred task without being wrapped with `act`. Usually it would work // anyway because the parent task has to wrapped with `act`... but not // if it was flushed with `flushSync` instead. await act(() => { ReactNoop.flushSync(() => root.render(<App />)); }); assertLog([ 'Suspend! [Loading...]', // The initial value suspended, so we attempt the final value, which // also suspends. 'Suspend! [Final]', ]); expect(root).toMatchRenderedOutput(null); // The final value loads, so we can skip the initial value entirely. await act(() => resolveText('Final')); assertLog(['Final']); expect(root).toMatchRenderedOutput('Final'); // When the initial value finally loads, nothing happens because we no // longer need it. await act(() => resolveText('Loading...')); assertLog([]); expect(root).toMatchRenderedOutput('Final'); }, ); // @gate enableUseDeferredValueInitialArg it( 'if a suspended render spawns a deferred task, we can switch to the ' + 'deferred task without finishing the original one (Suspense boundary)', async () => { function App() { const text = useDeferredValue('Final', 'Loading...'); return <AsyncText text={text} />; } const root = ReactNoop.createRoot(); await act(() => root.render( <Suspense fallback={<Text text="Fallback" />}> <App /> </Suspense>, ), ); assertLog([ 'Suspend! [Loading...]', 'Fallback', // The initial value suspended, so we attempt the final value, which // also suspends. 'Suspend! [Final]', ]); expect(root).toMatchRenderedOutput('Fallback'); // The final value loads, so we can skip the initial value entirely. await act(() => resolveText('Final')); assertLog(['Final']); expect(root).toMatchRenderedOutput('Final'); // When the initial value finally loads, nothing happens because we no // longer need it. await act(() => resolveText('Loading...')); assertLog([]); expect(root).toMatchRenderedOutput('Final'); }, ); // @gate enableUseDeferredValueInitialArg it( 'if a suspended render spawns a deferred task that also suspends, we can ' + 'finish the original task if that one loads first', async () => { function App() { const text = useDeferredValue('Final', 'Loading...'); return <AsyncText text={text} />; } const root = ReactNoop.createRoot(); await act(() => root.render(<App />)); assertLog([ 'Suspend! [Loading...]', // The initial value suspended, so we attempt the final value, which // also suspends. 'Suspend! [Final]', ]); expect(root).toMatchRenderedOutput(null); // The initial value resolves first, so we render that. await act(() => resolveText('Loading...')); assertLog([ 'Loading...', // Still waiting for the final value. 'Suspend! [Final]', ]); expect(root).toMatchRenderedOutput('Loading...'); // The final value loads, so we can switch to that. await act(() => resolveText('Final')); assertLog(['Final']); expect(root).toMatchRenderedOutput('Final'); }, ); // @gate enableUseDeferredValueInitialArg it( 'if there are multiple useDeferredValues in the same tree, only the ' + 'first level defers; subsequent ones go straight to the final value, to ' + 'avoid a waterfall', async () => { function App() { const showContent = useDeferredValue(true, false); if (!showContent) { return <Text text="App Preview" />; } return <Content />; } function Content() { const text = useDeferredValue('Content', 'Content Preview'); return <AsyncText text={text} />; } const root = ReactNoop.createRoot(); resolveText('App Preview'); await act(() => root.render(<App />)); assertLog([ // The App shows an immediate preview 'App Preview', // Then we switch to showing the content. The Content component also // contains a useDeferredValue, but since we already showed a preview // in a parent component, we skip the preview in the inner one and // go straight to attempting the final value. // // (Note that this is intentionally different from how nested Suspense // boundaries work, where we always prefer to show the innermost // loading state.) 'Suspend! [Content]', ]); // Still showing the App preview state because the inner // content suspended. expect(root).toMatchRenderedOutput('App Preview'); // Finish loading the content await act(() => resolveText('Content')); // We didn't even attempt to render Content Preview. assertLog(['Content']); expect(root).toMatchRenderedOutput('Content'); }, ); // @gate enableUseDeferredValueInitialArg it('avoids a useDeferredValue waterfall when separated by a Suspense boundary', async () => { // Same as the previous test but with a Suspense boundary separating the // two useDeferredValue hooks. function App() { const showContent = useDeferredValue(true, false); if (!showContent) { return <Text text="App Preview" />; } return ( <Suspense fallback={<Text text="Loading..." />}> <Content /> </Suspense> ); } function Content() { const text = useDeferredValue('Content', 'Content Preview'); return <AsyncText text={text} />; } const root = ReactNoop.createRoot(); resolveText('App Preview'); await act(() => root.render(<App />)); assertLog([ // The App shows an immediate preview 'App Preview', // Then we switch to showing the content. The Content component also // contains a useDeferredValue, but since we already showed a preview // in a parent component, we skip the preview in the inner one and // go straight to attempting the final value. 'Suspend! [Content]', 'Loading...', ]); // The content suspended, so we show a Suspense fallback expect(root).toMatchRenderedOutput('Loading...'); // Finish loading the content await act(() => resolveText('Content')); // We didn't even attempt to render Content Preview. assertLog(['Content']); expect(root).toMatchRenderedOutput('Content'); }); // @gate enableUseDeferredValueInitialArg // @gate enableActivity it('useDeferredValue can spawn a deferred task while prerendering a hidden tree', async () => { function App() { const text = useDeferredValue('Final', 'Preview'); return ( <div> <AsyncText text={text} /> </div> ); } let revealContent; function Container({children}) { const [shouldShow, setState] = useState(false); revealContent = () => setState(true); return ( <Activity mode={shouldShow ? 'visible' : 'hidden'}>{children}</Activity> ); } const root = ReactNoop.createRoot(); // Prerender a hidden tree resolveText('Preview'); await act(() => root.render( <Container> <App /> </Container>, ), ); assertLog(['Preview', 'Suspend! [Final]']); expect(root).toMatchRenderedOutput(<div hidden={true}>Preview</div>); // Finish loading the content await act(() => resolveText('Final')); assertLog(['Final']); expect(root).toMatchRenderedOutput(<div hidden={true}>Final</div>); // Now reveal the hidden tree. It should toggle the visibility without // having to re-render anything inside the prerendered tree. await act(() => revealContent()); assertLog([]); expect(root).toMatchRenderedOutput(<div>Final</div>); }); // @gate enableUseDeferredValueInitialArg // @gate enableActivity it('useDeferredValue can prerender the initial value inside a hidden tree', async () => { function App({text}) { const renderedText = useDeferredValue(text, `Preview [${text}]`); return ( <div> <Text text={renderedText} /> </div> ); } let revealContent; function Container({children}) { const [shouldShow, setState] = useState(false); revealContent = () => setState(true); return ( <Activity mode={shouldShow ? 'visible' : 'hidden'}>{children}</Activity> ); } const root = ReactNoop.createRoot(); // Prerender some content await act(() => { root.render( <Container> <App text="A" /> </Container>, ); }); assertLog(['Preview [A]', 'A']); expect(root).toMatchRenderedOutput(<div hidden={true}>A</div>); await act(async () => { // While the tree is still hidden, update the pre-rendered tree. root.render( <Container> <App text="B" /> </Container>, ); // We should switch to pre-rendering the new preview. await waitForPaint(['Preview [B]']); expect(root).toMatchRenderedOutput(<div hidden={true}>Preview [B]</div>); // Before the prerender is complete, reveal the hidden tree. Because we // consider revealing a hidden tree to be the same as mounting a new one, // we should not skip the preview state. revealContent(); // Because the preview state was already prerendered, we can reveal it // without any addditional work. await waitForPaint([]); expect(root).toMatchRenderedOutput(<div>Preview [B]</div>); }); // Finally, finish rendering the final value. assertLog(['B']); expect(root).toMatchRenderedOutput(<div>B</div>); }); // @gate enableUseDeferredValueInitialArg // @gate enableActivity it( 'useDeferredValue skips the preview state when revealing a hidden tree ' + 'if the final value is referentially identical', async () => { function App({text}) { const renderedText = useDeferredValue(text, `Preview [${text}]`); return ( <div> <Text text={renderedText} /> </div> ); } function Container({text, shouldShow}) { return ( <Activity mode={shouldShow ? 'visible' : 'hidden'}> <App text={text} /> </Activity> ); } const root = ReactNoop.createRoot(); // Prerender some content await act(() => root.render(<Container text="A" shouldShow={false} />)); assertLog(['Preview [A]', 'A']); expect(root).toMatchRenderedOutput(<div hidden={true}>A</div>); // Reveal the prerendered tree. Because the final value is referentially // equal to what was already prerendered, we can skip the preview state // and go straight to the final one. The practical upshot of this is // that we can completely prerender the final value without having to // do additional rendering work when the tree is revealed. await act(() => root.render(<Container text="A" shouldShow={true} />)); assertLog(['A']); expect(root).toMatchRenderedOutput(<div>A</div>); }, ); // @gate enableUseDeferredValueInitialArg // @gate enableActivity it( 'useDeferredValue does not skip the preview state when revealing a ' + 'hidden tree if the final value is different from the currently rendered one', async () => { function App({text}) { const renderedText = useDeferredValue(text, `Preview [${text}]`); return ( <div> <Text text={renderedText} /> </div> ); } function Container({text, shouldShow}) { return ( <Activity mode={shouldShow ? 'visible' : 'hidden'}> <App text={text} /> </Activity> ); } const root = ReactNoop.createRoot(); // Prerender some content await act(() => root.render(<Container text="A" shouldShow={false} />)); assertLog(['Preview [A]', 'A']); expect(root).toMatchRenderedOutput(<div hidden={true}>A</div>); // Reveal the prerendered tree. Because the final value is different from // what was already prerendered, we can't bail out. Since we treat // revealing a hidden tree the same as a new mount, show the preview state // before switching to the final one. await act(async () => { root.render(<Container text="B" shouldShow={true} />); // First commit the preview state await waitForPaint(['Preview [B]']); expect(root).toMatchRenderedOutput(<div>Preview [B]</div>); }); // Then switch to the final state assertLog(['B']); expect(root).toMatchRenderedOutput(<div>B</div>); }, ); // @gate enableActivity it( 'useDeferredValue does not show "previous" value when revealing a hidden ' + 'tree (no initial value)', async () => { function App({text}) { const renderedText = useDeferredValue(text); return ( <div> <Text text={renderedText} /> </div> ); } function Container({text, shouldShow}) { return ( <Activity mode={shouldShow ? 'visible' : 'hidden'}> <App text={text} /> </Activity> ); } const root = ReactNoop.createRoot(); // Prerender some content await act(() => root.render(<Container text="A" shouldShow={false} />)); assertLog(['A']); expect(root).toMatchRenderedOutput(<div hidden={true}>A</div>); // Update the prerendered tree and reveal it at the same time. Even though // this is a sync update, we should update B immediately rather than stay // on the old value (A), because conceptually this is a new tree. await act(() => root.render(<Container text="B" shouldShow={true} />)); assertLog(['B']); expect(root).toMatchRenderedOutput(<div>B</div>); }, ); });
29.023783
108
0.580837
Python-Penetration-Testing-Cookbook
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListItem = ListItem; exports.List = List; var React = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ListItem({ item, removeItem, toggleItem }) { const handleDelete = (0, React.useCallback)(() => { removeItem(item); }, [item, removeItem]); const handleToggle = (0, React.useCallback)(() => { toggleItem(item); }, [item, toggleItem]); return /*#__PURE__*/React.createElement("li", { __source: { fileName: _jsxFileName, lineNumber: 23, columnNumber: 5 } }, /*#__PURE__*/React.createElement("button", { onClick: handleDelete, __source: { fileName: _jsxFileName, lineNumber: 24, columnNumber: 7 } }, "Delete"), /*#__PURE__*/React.createElement("label", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, /*#__PURE__*/React.createElement("input", { checked: item.isComplete, onChange: handleToggle, type: "checkbox", __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 9 } }), ' ', item.text)); } function List(props) { const [newItemText, setNewItemText] = (0, React.useState)(''); const [items, setItems] = (0, React.useState)([{ id: 1, isComplete: true, text: 'First' }, { id: 2, isComplete: true, text: 'Second' }, { id: 3, isComplete: false, text: 'Third' }]); const [uid, setUID] = (0, React.useState)(4); const handleClick = (0, React.useCallback)(() => { if (newItemText !== '') { setItems([...items, { id: uid, isComplete: false, text: newItemText }]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = (0, React.useCallback)(event => { if (event.key === 'Enter') { handleClick(); } }, [handleClick]); const handleChange = (0, React.useCallback)(event => { setNewItemText(event.currentTarget.value); }, [setNewItemText]); const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]); const toggleItem = (0, React.useCallback)(itemToToggle => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); setItems(items.slice(0, index).concat({ ...itemToToggle, isComplete: !itemToToggle.isComplete }).concat(items.slice(index + 1))); }, [items]); return /*#__PURE__*/React.createElement(React.Fragment, { __source: { fileName: _jsxFileName, lineNumber: 102, columnNumber: 5 } }, /*#__PURE__*/React.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 103, columnNumber: 7 } }, "List"), /*#__PURE__*/React.createElement("input", { type: "text", placeholder: "New list item...", value: newItemText, onChange: handleChange, onKeyPress: handleKeyPress, __source: { fileName: _jsxFileName, lineNumber: 104, columnNumber: 7 } }), /*#__PURE__*/React.createElement("button", { disabled: newItemText === '', onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 111, columnNumber: 7 } }, /*#__PURE__*/React.createElement("span", { role: "img", "aria-label": "Add item", __source: { fileName: _jsxFileName, lineNumber: 112, columnNumber: 9 } }, "Add")), /*#__PURE__*/React.createElement("ul", { __source: { fileName: _jsxFileName, lineNumber: 116, columnNumber: 7 } }, items.map(item => /*#__PURE__*/React.createElement(ListItem, { key: item.id, item: item, removeItem: removeItem, toggleItem: toggleItem, __source: { fileName: _jsxFileName, lineNumber: 118, columnNumber: 11 } })))); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlRvRG9MaXN0LmpzIl0sIm5hbWVzIjpbIkxpc3RJdGVtIiwiaXRlbSIsInJlbW92ZUl0ZW0iLCJ0b2dnbGVJdGVtIiwiaGFuZGxlRGVsZXRlIiwiaGFuZGxlVG9nZ2xlIiwiaXNDb21wbGV0ZSIsInRleHQiLCJMaXN0IiwicHJvcHMiLCJuZXdJdGVtVGV4dCIsInNldE5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJzZXRJdGVtcyIsImlkIiwidWlkIiwic2V0VUlEIiwiaGFuZGxlQ2xpY2siLCJoYW5kbGVLZXlQcmVzcyIsImV2ZW50Iiwia2V5IiwiaGFuZGxlQ2hhbmdlIiwiY3VycmVudFRhcmdldCIsInZhbHVlIiwiaXRlbVRvUmVtb3ZlIiwiZmlsdGVyIiwiaXRlbVRvVG9nZ2xlIiwiaW5kZXgiLCJmaW5kSW5kZXgiLCJzbGljZSIsImNvbmNhdCIsIm1hcCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFHQSxTQUFBQSxRQUFBLENBQUE7QUFBQUMsRUFBQUEsSUFBQTtBQUFBQyxFQUFBQSxVQUFBO0FBQUFDLEVBQUFBO0FBQUEsQ0FBQSxFQUFBO0FBQ0EsUUFBQUMsWUFBQSxHQUFBLHVCQUFBLE1BQUE7QUFDQUYsSUFBQUEsVUFBQSxDQUFBRCxJQUFBLENBQUE7QUFDQSxHQUZBLEVBRUEsQ0FBQUEsSUFBQSxFQUFBQyxVQUFBLENBRkEsQ0FBQTtBQUlBLFFBQUFHLFlBQUEsR0FBQSx1QkFBQSxNQUFBO0FBQ0FGLElBQUFBLFVBQUEsQ0FBQUYsSUFBQSxDQUFBO0FBQ0EsR0FGQSxFQUVBLENBQUFBLElBQUEsRUFBQUUsVUFBQSxDQUZBLENBQUE7QUFJQSxzQkFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDQTtBQUFBLElBQUEsT0FBQSxFQUFBQyxZQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGNBREEsZUFFQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDQTtBQUNBLElBQUEsT0FBQSxFQUFBSCxJQUFBLENBQUFLLFVBREE7QUFFQSxJQUFBLFFBQUEsRUFBQUQsWUFGQTtBQUdBLElBQUEsSUFBQSxFQUFBLFVBSEE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFEQSxFQUtBLEdBTEEsRUFNQUosSUFBQSxDQUFBTSxJQU5BLENBRkEsQ0FEQTtBQWFBOztBQUVBLFNBQUFDLElBQUEsQ0FBQUMsS0FBQSxFQUFBO0FBQ0EsUUFBQSxDQUFBQyxXQUFBLEVBQUFDLGNBQUEsSUFBQSxvQkFBQSxFQUFBLENBQUE7QUFDQSxRQUFBLENBQUFDLEtBQUEsRUFBQUMsUUFBQSxJQUFBLG9CQUFBLENBQ0E7QUFBQUMsSUFBQUEsRUFBQSxFQUFBLENBQUE7QUFBQVIsSUFBQUEsVUFBQSxFQUFBLElBQUE7QUFBQUMsSUFBQUEsSUFBQSxFQUFBO0FBQUEsR0FEQSxFQUVBO0FBQUFPLElBQUFBLEVBQUEsRUFBQSxDQUFBO0FBQUFSLElBQUFBLFVBQUEsRUFBQSxJQUFBO0FBQUFDLElBQUFBLElBQUEsRUFBQTtBQUFBLEdBRkEsRUFHQTtBQUFBTyxJQUFBQSxFQUFBLEVBQUEsQ0FBQTtBQUFBUixJQUFBQSxVQUFBLEVBQUEsS0FBQTtBQUFBQyxJQUFBQSxJQUFBLEVBQUE7QUFBQSxHQUhBLENBQUEsQ0FBQTtBQUtBLFFBQUEsQ0FBQVEsR0FBQSxFQUFBQyxNQUFBLElBQUEsb0JBQUEsQ0FBQSxDQUFBO0FBRUEsUUFBQUMsV0FBQSxHQUFBLHVCQUFBLE1BQUE7QUFDQSxRQUFBUCxXQUFBLEtBQUEsRUFBQSxFQUFBO0FBQ0FHLE1BQUFBLFFBQUEsQ0FBQSxDQUNBLEdBQUFELEtBREEsRUFFQTtBQUNBRSxRQUFBQSxFQUFBLEVBQUFDLEdBREE7QUFFQVQsUUFBQUEsVUFBQSxFQUFBLEtBRkE7QUFHQUMsUUFBQUEsSUFBQSxFQUFBRztBQUhBLE9BRkEsQ0FBQSxDQUFBO0FBUUFNLE1BQUFBLE1BQUEsQ0FBQUQsR0FBQSxHQUFBLENBQUEsQ0FBQTtBQUNBSixNQUFBQSxjQUFBLENBQUEsRUFBQSxDQUFBO0FBQ0E7QUFDQSxHQWJBLEVBYUEsQ0FBQUQsV0FBQSxFQUFBRSxLQUFBLEVBQUFHLEdBQUEsQ0FiQSxDQUFBO0FBZUEsUUFBQUcsY0FBQSxHQUFBLHVCQUNBQyxLQUFBLElBQUE7QUFDQSxRQUFBQSxLQUFBLENBQUFDLEdBQUEsS0FBQSxPQUFBLEVBQUE7QUFDQUgsTUFBQUEsV0FBQTtBQUNBO0FBQ0EsR0FMQSxFQU1BLENBQUFBLFdBQUEsQ0FOQSxDQUFBO0FBU0EsUUFBQUksWUFBQSxHQUFBLHVCQUNBRixLQUFBLElBQUE7QUFDQVIsSUFBQUEsY0FBQSxDQUFBUSxLQUFBLENBQUFHLGFBQUEsQ0FBQUMsS0FBQSxDQUFBO0FBQ0EsR0FIQSxFQUlBLENBQUFaLGNBQUEsQ0FKQSxDQUFBO0FBT0EsUUFBQVQsVUFBQSxHQUFBLHVCQUNBc0IsWUFBQSxJQUFBWCxRQUFBLENBQUFELEtBQUEsQ0FBQWEsTUFBQSxDQUFBeEIsSUFBQSxJQUFBQSxJQUFBLEtBQUF1QixZQUFBLENBQUEsQ0FEQSxFQUVBLENBQUFaLEtBQUEsQ0FGQSxDQUFBO0FBS0EsUUFBQVQsVUFBQSxHQUFBLHVCQUNBdUIsWUFBQSxJQUFBO0FBQ0E7QUFDQTtBQUNBLFVBQUFDLEtBQUEsR0FBQWYsS0FBQSxDQUFBZ0IsU0FBQSxDQUFBM0IsSUFBQSxJQUFBQSxJQUFBLENBQUFhLEVBQUEsS0FBQVksWUFBQSxDQUFBWixFQUFBLENBQUE7QUFFQUQsSUFBQUEsUUFBQSxDQUNBRCxLQUFBLENBQ0FpQixLQURBLENBQ0EsQ0FEQSxFQUNBRixLQURBLEVBRUFHLE1BRkEsQ0FFQSxFQUNBLEdBQUFKLFlBREE7QUFFQXBCLE1BQUFBLFVBQUEsRUFBQSxDQUFBb0IsWUFBQSxDQUFBcEI7QUFGQSxLQUZBLEVBTUF3QixNQU5BLENBTUFsQixLQUFBLENBQUFpQixLQUFBLENBQUFGLEtBQUEsR0FBQSxDQUFBLENBTkEsQ0FEQSxDQUFBO0FBU0EsR0FmQSxFQWdCQSxDQUFBZixLQUFBLENBaEJBLENBQUE7QUFtQkEsc0JBQ0Esb0JBQUEsY0FBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxZQURBLGVBRUE7QUFDQSxJQUFBLElBQUEsRUFBQSxNQURBO0FBRUEsSUFBQSxXQUFBLEVBQUEsa0JBRkE7QUFHQSxJQUFBLEtBQUEsRUFBQUYsV0FIQTtBQUlBLElBQUEsUUFBQSxFQUFBVyxZQUpBO0FBS0EsSUFBQSxVQUFBLEVBQUFILGNBTEE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFGQSxlQVNBO0FBQUEsSUFBQSxRQUFBLEVBQUFSLFdBQUEsS0FBQSxFQUFBO0FBQUEsSUFBQSxPQUFBLEVBQUFPLFdBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0E7QUFBQSxJQUFBLElBQUEsRUFBQSxLQUFBO0FBQUEsa0JBQUEsVUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxXQURBLENBVEEsZUFjQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxLQUNBTCxLQUFBLENBQUFtQixHQUFBLENBQUE5QixJQUFBLGlCQUNBLG9CQUFBLFFBQUE7QUFDQSxJQUFBLEdBQUEsRUFBQUEsSUFBQSxDQUFBYSxFQURBO0FBRUEsSUFBQSxJQUFBLEVBQUFiLElBRkE7QUFHQSxJQUFBLFVBQUEsRUFBQUMsVUFIQTtBQUlBLElBQUEsVUFBQSxFQUFBQyxVQUpBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLElBREEsQ0FEQSxDQWRBLENBREE7QUEyQkEiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0ICogYXMgUmVhY3QgZnJvbSAncmVhY3QnO1xuaW1wb3J0IHtGcmFnbWVudCwgdXNlQ2FsbGJhY2ssIHVzZVN0YXRlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBmdW5jdGlvbiBMaXN0SXRlbSh7aXRlbSwgcmVtb3ZlSXRlbSwgdG9nZ2xlSXRlbX0pIHtcbiAgY29uc3QgaGFuZGxlRGVsZXRlID0gdXNlQ2FsbGJhY2soKCkgPT4ge1xuICAgIHJlbW92ZUl0ZW0oaXRlbSk7XG4gIH0sIFtpdGVtLCByZW1vdmVJdGVtXSk7XG5cbiAgY29uc3QgaGFuZGxlVG9nZ2xlID0gdXNlQ2FsbGJhY2soKCkgPT4ge1xuICAgIHRvZ2dsZUl0ZW0oaXRlbSk7XG4gIH0sIFtpdGVtLCB0b2dnbGVJdGVtXSk7XG5cbiAgcmV0dXJuIChcbiAgICA8bGk+XG4gICAgICA8YnV0dG9uIG9uQ2xpY2s9e2hhbmRsZURlbGV0ZX0+RGVsZXRlPC9idXR0b24+XG4gICAgICA8bGFiZWw+XG4gICAgICAgIDxpbnB1dFxuICAgICAgICAgIGNoZWNrZWQ9e2l0ZW0uaXNDb21wbGV0ZX1cbiAgICAgICAgICBvbkNoYW5nZT17aGFuZGxlVG9nZ2xlfVxuICAgICAgICAgIHR5cGU9XCJjaGVja2JveFwiXG4gICAgICAgIC8+eycgJ31cbiAgICAgICAge2l0ZW0udGV4dH1cbiAgICAgIDwvbGFiZWw+XG4gICAgPC9saT5cbiAgKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIExpc3QocHJvcHMpIHtcbiAgY29uc3QgW25ld0l0ZW1UZXh0LCBzZXROZXdJdGVtVGV4dF0gPSB1c2VTdGF0ZSgnJyk7XG4gIGNvbnN0IFtpdGVtcywgc2V0SXRlbXNdID0gdXNlU3RhdGUoW1xuICAgIHtpZDogMSwgaXNDb21wbGV0ZTogdHJ1ZSwgdGV4dDogJ0ZpcnN0J30sXG4gICAge2lkOiAyLCBpc0NvbXBsZXRlOiB0cnVlLCB0ZXh0OiAnU2Vjb25kJ30sXG4gICAge2lkOiAzLCBpc0NvbXBsZXRlOiBmYWxzZSwgdGV4dDogJ1RoaXJkJ30sXG4gIF0pO1xuICBjb25zdCBbdWlkLCBzZXRVSURdID0gdXNlU3RhdGUoNCk7XG5cbiAgY29uc3QgaGFuZGxlQ2xpY2sgPSB1c2VDYWxsYmFjaygoKSA9PiB7XG4gICAgaWYgKG5ld0l0ZW1UZXh0ICE9PSAnJykge1xuICAgICAgc2V0SXRlbXMoW1xuICAgICAgICAuLi5pdGVtcyxcbiAgICAgICAge1xuICAgICAgICAgIGlkOiB1aWQsXG4gICAgICAgICAgaXNDb21wbGV0ZTogZmFsc2UsXG4gICAgICAgICAgdGV4dDogbmV3SXRlbVRleHQsXG4gICAgICAgIH0sXG4gICAgICBdKTtcbiAgICAgIHNldFVJRCh1aWQgKyAxKTtcbiAgICAgIHNldE5ld0l0ZW1UZXh0KCcnKTtcbiAgICB9XG4gIH0sIFtuZXdJdGVtVGV4dCwgaXRlbXMsIHVpZF0pO1xuXG4gIGNvbnN0IGhhbmRsZUtleVByZXNzID0gdXNlQ2FsbGJhY2soXG4gICAgZXZlbnQgPT4ge1xuICAgICAgaWYgKGV2ZW50LmtleSA9PT0gJ0VudGVyJykge1xuICAgICAgICBoYW5kbGVDbGljaygpO1xuICAgICAgfVxuICAgIH0sXG4gICAgW2hhbmRsZUNsaWNrXSxcbiAgKTtcblxuICBjb25zdCBoYW5kbGVDaGFuZ2UgPSB1c2VDYWxsYmFjayhcbiAgICBldmVudCA9PiB7XG4gICAgICBzZXROZXdJdGVtVGV4dChldmVudC5jdXJyZW50VGFyZ2V0LnZhbHVlKTtcbiAgICB9LFxuICAgIFtzZXROZXdJdGVtVGV4dF0sXG4gICk7XG5cbiAgY29uc3QgcmVtb3ZlSXRlbSA9IHVzZUNhbGxiYWNrKFxuICAgIGl0ZW1Ub1JlbW92ZSA9PiBzZXRJdGVtcyhpdGVtcy5maWx0ZXIoaXRlbSA9PiBpdGVtICE9PSBpdGVtVG9SZW1vdmUpKSxcbiAgICBbaXRlbXNdLFxuICApO1xuXG4gIGNvbnN0IHRvZ2dsZUl0ZW0gPSB1c2VDYWxsYmFjayhcbiAgICBpdGVtVG9Ub2dnbGUgPT4ge1xuICAgICAgLy8gRG9udCB1c2UgaW5kZXhPZigpXG4gICAgICAvLyBiZWNhdXNlIGVkaXRpbmcgcHJvcHMgaW4gRGV2VG9vbHMgY3JlYXRlcyBhIG5ldyBPYmplY3QuXG4gICAgICBjb25zdCBpbmRleCA9IGl0ZW1zLmZpbmRJbmRleChpdGVtID0+IGl0ZW0uaWQgPT09IGl0ZW1Ub1RvZ2dsZS5pZCk7XG5cbiAgICAgIHNldEl0ZW1zKFxuICAgICAgICBpdGVtc1xuICAgICAgICAgIC5zbGljZSgwLCBpbmRleClcbiAgICAgICAgICAuY29uY2F0KHtcbiAgICAgICAgICAgIC4uLml0ZW1Ub1RvZ2dsZSxcbiAgICAgICAgICAgIGlzQ29tcGxldGU6ICFpdGVtVG9Ub2dnbGUuaXNDb21wbGV0ZSxcbiAgICAgICAgICB9KVxuICAgICAgICAgIC5jb25jYXQoaXRlbXMuc2xpY2UoaW5kZXggKyAxKSksXG4gICAgICApO1xuICAgIH0sXG4gICAgW2l0ZW1zXSxcbiAgKTtcblxuICByZXR1cm4gKFxuICAgIDxGcmFnbWVudD5cbiAgICAgIDxoMT5MaXN0PC9oMT5cbiAgICAgIDxpbnB1dFxuICAgICAgICB0eXBlPVwidGV4dFwiXG4gICAgICAgIHBsYWNlaG9sZGVyPVwiTmV3IGxpc3QgaXRlbS4uLlwiXG4gICAgICAgIHZhbHVlPXtuZXdJdGVtVGV4dH1cbiAgICAgICAgb25DaGFuZ2U9e2hhbmRsZUNoYW5nZX1cbiAgICAgICAgb25LZXlQcmVzcz17aGFuZGxlS2V5UHJlc3N9XG4gICAgICAvPlxuICAgICAgPGJ1dHRvbiBkaXNhYmxlZD17bmV3SXRlbVRleHQgPT09ICcnfSBvbkNsaWNrPXtoYW5kbGVDbGlja30+XG4gICAgICAgIDxzcGFuIHJvbGU9XCJpbWdcIiBhcmlhLWxhYmVsPVwiQWRkIGl0ZW1cIj5cbiAgICAgICAgICBBZGRcbiAgICAgICAgPC9zcGFuPlxuICAgICAgPC9idXR0b24+XG4gICAgICA8dWw+XG4gICAgICAgIHtpdGVtcy5tYXAoaXRlbSA9PiAoXG4gICAgICAgICAgPExpc3RJdGVtXG4gICAgICAgICAgICBrZXk9e2l0ZW0uaWR9XG4gICAgICAgICAgICBpdGVtPXtpdGVtfVxuICAgICAgICAgICAgcmVtb3ZlSXRlbT17cmVtb3ZlSXRlbX1cbiAgICAgICAgICAgIHRvZ2dsZUl0ZW09e3RvZ2dsZUl0ZW19XG4gICAgICAgICAgLz5cbiAgICAgICAgKSl9XG4gICAgICA8L3VsPlxuICAgIDwvRnJhZ21lbnQ+XG4gICk7XG59XG4iXX0=
84.24375
8,672
0.853131
owtf
'use client'; import * as React from 'react'; import {useFormStatus} from 'react-dom'; import ErrorBoundary from './ErrorBoundary.js'; function ButtonDisabledWhilePending({action, children}) { const {pending} = useFormStatus(); return ( <button disabled={pending} formAction={action}> {children} </button> ); } export default function Button({action, children}) { return ( <ErrorBoundary> <form> <ButtonDisabledWhilePending action={action}> {children} </ButtonDisabledWhilePending> </form> </ErrorBoundary> ); }
20.703704
57
0.654701
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 {InspectorData, TouchedViewDataAtPoint} from './ReactNativeTypes'; // Modules provided by RN: import { ReactNativeViewConfigRegistry, UIManager, deepFreezeAndThrowOnMutationInDev, } from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; import {create, diff} from './ReactNativeAttributePayload'; import { precacheFiberNode, uncacheFiberNode, updateFiberProps, } from './ReactNativeComponentTree'; import ReactNativeFiberHostComponent from './ReactNativeFiberHostComponent'; import { DefaultEventPriority, type EventPriority, } from 'react-reconciler/src/ReactEventPriorities'; import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; const {get: getViewConfigForType} = ReactNativeViewConfigRegistry; export type Type = string; export type Props = Object; export type Container = number; export type Instance = ReactNativeFiberHostComponent; export type TextInstance = number; export type HydratableInstance = Instance | TextInstance; export type PublicInstance = Instance; export type HostContext = $ReadOnly<{ isInAParentText: boolean, }>; export type UpdatePayload = Object; // Unused export type ChildSet = void; // Unused export type TimeoutHandle = TimeoutID; export type NoTimeout = -1; export type TransitionStatus = mixed; export type RendererInspectionConfig = $ReadOnly<{ getInspectorDataForInstance?: (instance: Fiber | null) => InspectorData, // Deprecated. Replaced with getInspectorDataForViewAtPoint. getInspectorDataForViewTag?: (tag: number) => Object, getInspectorDataForViewAtPoint?: ( inspectedView: Object, locationX: number, locationY: number, callback: (viewData: TouchedViewDataAtPoint) => mixed, ) => void, }>; // Counter for uniquely identifying views. // % 10 === 1 means it is a rootTag. // % 2 === 0 means it is a Fabric tag. let nextReactTag = 3; function allocateTag() { let tag = nextReactTag; if (tag % 10 === 1) { tag += 2; } nextReactTag = tag + 2; return tag; } function recursivelyUncacheFiberNode(node: Instance | TextInstance) { if (typeof node === 'number') { // Leaf node (eg text) uncacheFiberNode(node); } else { uncacheFiberNode((node: any)._nativeTag); (node: any)._children.forEach(recursivelyUncacheFiberNode); } } export * from 'react-reconciler/src/ReactFiberConfigWithNoPersistence'; export * from 'react-reconciler/src/ReactFiberConfigWithNoHydration'; export * from 'react-reconciler/src/ReactFiberConfigWithNoScopes'; export * from 'react-reconciler/src/ReactFiberConfigWithNoTestSelectors'; export * from 'react-reconciler/src/ReactFiberConfigWithNoMicrotasks'; export * from 'react-reconciler/src/ReactFiberConfigWithNoResources'; export * from 'react-reconciler/src/ReactFiberConfigWithNoSingletons'; export function appendInitialChild( parentInstance: Instance, child: Instance | TextInstance, ): void { parentInstance._children.push(child); } export function createInstance( type: string, props: Props, rootContainerInstance: Container, hostContext: HostContext, internalInstanceHandle: Object, ): Instance { const tag = allocateTag(); const viewConfig = getViewConfigForType(type); if (__DEV__) { for (const key in viewConfig.validAttributes) { if (props.hasOwnProperty(key)) { deepFreezeAndThrowOnMutationInDev(props[key]); } } } const updatePayload = create(props, viewConfig.validAttributes); UIManager.createView( tag, // reactTag viewConfig.uiViewClassName, // viewName rootContainerInstance, // rootTag updatePayload, // props ); const component = new ReactNativeFiberHostComponent( tag, viewConfig, internalInstanceHandle, ); precacheFiberNode(internalInstanceHandle, tag); updateFiberProps(tag, props); // Not sure how to avoid this cast. Flow is okay if the component is defined // in the same file but if it's external it can't see the types. return ((component: any): Instance); } export function createTextInstance( text: string, rootContainerInstance: Container, hostContext: HostContext, internalInstanceHandle: Object, ): TextInstance { if (!hostContext.isInAParentText) { throw new Error('Text strings must be rendered within a <Text> component.'); } const tag = allocateTag(); UIManager.createView( tag, // reactTag 'RCTRawText', // viewName rootContainerInstance, // rootTag {text: text}, // props ); precacheFiberNode(internalInstanceHandle, tag); return tag; } export function finalizeInitialChildren( parentInstance: Instance, type: string, props: Props, hostContext: HostContext, ): boolean { // Don't send a no-op message over the bridge. if (parentInstance._children.length === 0) { return false; } // Map from child objects to native tags. // Either way we need to pass a copy of the Array to prevent it from being frozen. const nativeTags = parentInstance._children.map(child => typeof child === 'number' ? child // Leaf node (eg text) : child._nativeTag, ); UIManager.setChildren( parentInstance._nativeTag, // containerTag nativeTags, // reactTags ); return false; } export function getRootHostContext( rootContainerInstance: Container, ): HostContext { return {isInAParentText: false}; } export function getChildHostContext( parentHostContext: HostContext, type: string, ): HostContext { const prevIsInAParentText = parentHostContext.isInAParentText; const isInAParentText = type === 'AndroidTextInput' || // Android type === 'RCTMultilineTextInputView' || // iOS type === 'RCTSinglelineTextInputView' || // iOS type === 'RCTText' || type === 'RCTVirtualText'; if (prevIsInAParentText !== isInAParentText) { return {isInAParentText}; } else { return parentHostContext; } } export function getPublicInstance(instance: Instance): PublicInstance { // $FlowExpectedError[prop-missing] For compatibility with Fabric if (instance.canonical != null && instance.canonical.publicInstance != null) { // $FlowFixMe[incompatible-return] return instance.canonical.publicInstance; } return instance; } export function prepareForCommit(containerInfo: Container): null | Object { // Noop return null; } export function resetAfterCommit(containerInfo: Container): void { // Noop } export const isPrimaryRenderer = true; export const warnsIfNotActing = true; export const scheduleTimeout = setTimeout; export const cancelTimeout = clearTimeout; export const noTimeout = -1; export function shouldSetTextContent(type: string, props: Props): boolean { // TODO (bvaughn) Revisit this decision. // Always returning false simplifies the createInstance() implementation, // But creates an additional child Fiber for raw text children. // No additional native views are created though. // It's not clear to me which is better so I'm deferring for now. // More context @ github.com/facebook/react/pull/8560#discussion_r92111303 return false; } export function getCurrentEventPriority(): EventPriority { return DefaultEventPriority; } export function shouldAttemptEagerTransition(): boolean { return false; } // ------------------- // Mutation // ------------------- export const supportsMutation = true; export function appendChild( parentInstance: Instance, child: Instance | TextInstance, ): void { const childTag = typeof child === 'number' ? child : child._nativeTag; const children = parentInstance._children; const index = children.indexOf(child); if (index >= 0) { children.splice(index, 1); children.push(child); UIManager.manageChildren( parentInstance._nativeTag, // containerTag [index], // moveFromIndices [children.length - 1], // moveToIndices [], // addChildReactTags [], // addAtIndices [], // removeAtIndices ); } else { children.push(child); UIManager.manageChildren( parentInstance._nativeTag, // containerTag [], // moveFromIndices [], // moveToIndices [childTag], // addChildReactTags [children.length - 1], // addAtIndices [], // removeAtIndices ); } } export function appendChildToContainer( parentInstance: Container, child: Instance | TextInstance, ): void { const childTag = typeof child === 'number' ? child : child._nativeTag; UIManager.setChildren( parentInstance, // containerTag [childTag], // reactTags ); } export function commitTextUpdate( textInstance: TextInstance, oldText: string, newText: string, ): void { UIManager.updateView( textInstance, // reactTag 'RCTRawText', // viewName {text: newText}, // props ); } export function commitMount( instance: Instance, type: string, newProps: Props, internalInstanceHandle: Object, ): void { // Noop } export function commitUpdate( instance: Instance, updatePayloadTODO: Object, type: string, oldProps: Props, newProps: Props, internalInstanceHandle: Object, ): void { const viewConfig = instance.viewConfig; updateFiberProps(instance._nativeTag, newProps); const updatePayload = diff(oldProps, newProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. if (updatePayload != null) { UIManager.updateView( instance._nativeTag, // reactTag viewConfig.uiViewClassName, // viewName updatePayload, // props ); } } export function insertBefore( parentInstance: Instance, child: Instance | TextInstance, beforeChild: Instance | TextInstance, ): void { const children = (parentInstance: any)._children; const index = children.indexOf(child); // Move existing child or add new child? if (index >= 0) { children.splice(index, 1); const beforeChildIndex = children.indexOf(beforeChild); children.splice(beforeChildIndex, 0, child); UIManager.manageChildren( (parentInstance: any)._nativeTag, // containerID [index], // moveFromIndices [beforeChildIndex], // moveToIndices [], // addChildReactTags [], // addAtIndices [], // removeAtIndices ); } else { const beforeChildIndex = children.indexOf(beforeChild); children.splice(beforeChildIndex, 0, child); const childTag = typeof child === 'number' ? child : child._nativeTag; UIManager.manageChildren( (parentInstance: any)._nativeTag, // containerID [], // moveFromIndices [], // moveToIndices [childTag], // addChildReactTags [beforeChildIndex], // addAtIndices [], // removeAtIndices ); } } export function insertInContainerBefore( parentInstance: Container, child: Instance | TextInstance, beforeChild: Instance | TextInstance, ): void { // TODO (bvaughn): Remove this check when... // We create a wrapper object for the container in ReactNative render() // Or we refactor to remove wrapper objects entirely. // For more info on pros/cons see PR #8560 description. if (typeof parentInstance === 'number') { throw new Error('Container does not support insertBefore operation'); } } export function removeChild( parentInstance: Instance, child: Instance | TextInstance, ): void { recursivelyUncacheFiberNode(child); const children = parentInstance._children; const index = children.indexOf(child); children.splice(index, 1); UIManager.manageChildren( parentInstance._nativeTag, // containerID [], // moveFromIndices [], // moveToIndices [], // addChildReactTags [], // addAtIndices [index], // removeAtIndices ); } export function removeChildFromContainer( parentInstance: Container, child: Instance | TextInstance, ): void { recursivelyUncacheFiberNode(child); UIManager.manageChildren( parentInstance, // containerID [], // moveFromIndices [], // moveToIndices [], // addChildReactTags [], // addAtIndices [0], // removeAtIndices ); } export function resetTextContent(instance: Instance): void { // Noop } export function hideInstance(instance: Instance): void { const viewConfig = instance.viewConfig; const updatePayload = create( {style: {display: 'none'}}, viewConfig.validAttributes, ); UIManager.updateView( instance._nativeTag, viewConfig.uiViewClassName, updatePayload, ); } export function hideTextInstance(textInstance: TextInstance): void { throw new Error('Not yet implemented.'); } export function unhideInstance(instance: Instance, props: Props): void { const viewConfig = instance.viewConfig; const updatePayload = diff( {...props, style: [props.style, {display: 'none'}]}, props, viewConfig.validAttributes, ); UIManager.updateView( instance._nativeTag, viewConfig.uiViewClassName, updatePayload, ); } export function clearContainer(container: Container): void { // TODO Implement this for React Native // UIManager does not expose a "remove all" type method. } export function unhideTextInstance( textInstance: TextInstance, text: string, ): void { throw new Error('Not yet implemented.'); } export function getInstanceFromNode(node: any): empty { throw new Error('Not yet implemented.'); } export function beforeActiveInstanceBlur(internalInstanceHandle: Object) { // noop } export function afterActiveInstanceBlur() { // noop } export function preparePortalMount(portalInstance: Instance): void { // noop } export function detachDeletedInstance(node: Instance): 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;
25.799629
84
0.714345
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactFabric; let ReactNativePrivateInterface; let createReactNativeComponentClass; let StrictMode; let act; const DISPATCH_COMMAND_REQUIRES_HOST_COMPONENT = "Warning: dispatchCommand was called with a ref that isn't a " + 'native component. Use React.forwardRef to get access to the underlying native component'; const SEND_ACCESSIBILITY_EVENT_REQUIRES_HOST_COMPONENT = "sendAccessibilityEvent was called with a ref that isn't a " + 'native component. Use React.forwardRef to get access to the underlying native component'; jest.mock('shared/ReactFeatureFlags', () => require('shared/forks/ReactFeatureFlags.native-oss'), ); describe('ReactFabric', () => { beforeEach(() => { jest.resetModules(); require('react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager'); React = require('react'); StrictMode = React.StrictMode; ReactFabric = require('react-native-renderer/fabric'); ReactNativePrivateInterface = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'); createReactNativeComponentClass = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface') .ReactNativeViewConfigRegistry.register; act = require('internal-test-utils').act; }); it('should be able to create and render a native component', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); await act(() => { ReactFabric.render(<View foo="test" />, 1); }); expect(nativeFabricUIManager.createNode).toBeCalled(); expect(nativeFabricUIManager.appendChild).not.toBeCalled(); expect(nativeFabricUIManager.completeRoot).toBeCalled(); }); it('should be able to create and update a native component', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); const firstNode = {}; nativeFabricUIManager.createNode.mockReturnValue(firstNode); await act(() => { ReactFabric.render(<View foo="foo" />, 11); }); expect(nativeFabricUIManager.createNode).toHaveBeenCalledTimes(1); await act(() => { ReactFabric.render(<View foo="bar" />, 11); }); expect(nativeFabricUIManager.createNode).toHaveBeenCalledTimes(1); expect(nativeFabricUIManager.cloneNodeWithNewProps).toHaveBeenCalledTimes( 1, ); expect(nativeFabricUIManager.cloneNodeWithNewProps.mock.calls[0][0]).toBe( firstNode, ); expect( nativeFabricUIManager.cloneNodeWithNewProps.mock.calls[0][1], ).toEqual({ foo: 'bar', }); }); it('should not call FabricUIManager.cloneNode after render for properties that have not changed', async () => { const Text = createReactNativeComponentClass('RCTText', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTText', })); await act(() => { ReactFabric.render(<Text foo="a">1</Text>, 11); }); expect(nativeFabricUIManager.cloneNode).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewChildren).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewProps).not.toBeCalled(); expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps, ).not.toBeCalled(); // If no properties have changed, we shouldn't call cloneNode. await act(() => { ReactFabric.render(<Text foo="a">1</Text>, 11); }); expect(nativeFabricUIManager.cloneNode).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewChildren).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewProps).not.toBeCalled(); expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps, ).not.toBeCalled(); // Only call cloneNode for the changed property (and not for text). await act(() => { ReactFabric.render(<Text foo="b">1</Text>, 11); }); expect(nativeFabricUIManager.cloneNode).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewChildren).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewProps).toHaveBeenCalledTimes( 1, ); expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps, ).not.toBeCalled(); // Only call cloneNode for the changed text (and no other properties). await act(() => { ReactFabric.render(<Text foo="b">2</Text>, 11); }); expect(nativeFabricUIManager.cloneNode).not.toBeCalled(); expect( nativeFabricUIManager.cloneNodeWithNewChildren, ).toHaveBeenCalledTimes(1); expect(nativeFabricUIManager.cloneNodeWithNewProps).toHaveBeenCalledTimes( 1, ); expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps, ).not.toBeCalled(); // Call cloneNode for both changed text and properties. await act(() => { ReactFabric.render(<Text foo="c">3</Text>, 11); }); expect(nativeFabricUIManager.cloneNode).not.toBeCalled(); expect( nativeFabricUIManager.cloneNodeWithNewChildren, ).toHaveBeenCalledTimes(1); expect(nativeFabricUIManager.cloneNodeWithNewProps).toHaveBeenCalledTimes( 1, ); expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps, ).toHaveBeenCalledTimes(1); }); it('should only pass props diffs to FabricUIManager.cloneNode', async () => { const Text = createReactNativeComponentClass('RCTText', () => ({ validAttributes: {foo: true, bar: true}, uiViewClassName: 'RCTText', })); await act(() => { ReactFabric.render( <Text foo="a" bar="a"> 1 </Text>, 11, ); }); expect(nativeFabricUIManager.cloneNode).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewChildren).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewProps).not.toBeCalled(); expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps, ).not.toBeCalled(); await act(() => { ReactFabric.render( <Text foo="a" bar="b"> 1 </Text>, 11, ); }); expect( nativeFabricUIManager.cloneNodeWithNewProps.mock.calls[0][1], ).toEqual({ bar: 'b', }); expect( nativeFabricUIManager.__dumpHierarchyForJestTestsOnly(), ).toMatchSnapshot(); await act(() => { ReactFabric.render( <Text foo="b" bar="b"> 2 </Text>, 11, ); }); const argIndex = gate(flags => flags.passChildrenWhenCloningPersistedNodes) ? 2 : 1; expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps.mock.calls[0][ argIndex ], ).toEqual({ foo: 'b', }); expect( nativeFabricUIManager.__dumpHierarchyForJestTestsOnly(), ).toMatchSnapshot(); }); it('should not clone nodes without children when updating props', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); const Component = ({foo}) => ( <View> <View foo={foo} /> </View> ); await act(() => ReactFabric.render(<Component foo={true} />, 11)); expect(nativeFabricUIManager.completeRoot).toBeCalled(); jest.clearAllMocks(); await act(() => ReactFabric.render(<Component foo={false} />, 11)); expect(nativeFabricUIManager.cloneNode).not.toBeCalled(); expect(nativeFabricUIManager.cloneNodeWithNewProps).toHaveBeenCalledTimes( 1, ); expect(nativeFabricUIManager.cloneNodeWithNewProps).toHaveBeenCalledWith( expect.anything(), {foo: false}, ); expect( nativeFabricUIManager.cloneNodeWithNewChildren, ).toHaveBeenCalledTimes(1); if (gate(flags => flags.passChildrenWhenCloningPersistedNodes)) { expect( nativeFabricUIManager.cloneNodeWithNewChildren, ).toHaveBeenCalledWith(expect.anything(), [ expect.objectContaining({props: {foo: false}}), ]); expect(nativeFabricUIManager.appendChild).not.toBeCalled(); } else { expect( nativeFabricUIManager.cloneNodeWithNewChildren, ).toHaveBeenCalledWith(expect.anything()); expect(nativeFabricUIManager.appendChild).toHaveBeenCalledTimes(1); } expect( nativeFabricUIManager.cloneNodeWithNewChildrenAndProps, ).not.toBeCalled(); expect(nativeFabricUIManager.completeRoot).toBeCalled(); }); it('should call dispatchCommand for native refs', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); nativeFabricUIManager.dispatchCommand.mockClear(); let viewRef; await act(() => { ReactFabric.render( <View ref={ref => { viewRef = ref; }} />, 11, ); }); expect(nativeFabricUIManager.dispatchCommand).not.toBeCalled(); ReactFabric.dispatchCommand(viewRef, 'updateCommand', [10, 20]); expect(nativeFabricUIManager.dispatchCommand).toHaveBeenCalledTimes(1); expect(nativeFabricUIManager.dispatchCommand).toHaveBeenCalledWith( expect.any(Object), 'updateCommand', [10, 20], ); }); it('should warn and no-op if calling dispatchCommand on non native refs', async () => { class BasicClass extends React.Component { render() { return <React.Fragment />; } } nativeFabricUIManager.dispatchCommand.mockReset(); let viewRef; await act(() => { ReactFabric.render( <BasicClass ref={ref => { viewRef = ref; }} />, 11, ); }); expect(nativeFabricUIManager.dispatchCommand).not.toBeCalled(); expect(() => { ReactFabric.dispatchCommand(viewRef, 'updateCommand', [10, 20]); }).toErrorDev([DISPATCH_COMMAND_REQUIRES_HOST_COMPONENT], { withoutStack: true, }); expect(nativeFabricUIManager.dispatchCommand).not.toBeCalled(); }); it('should call sendAccessibilityEvent for native refs', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); nativeFabricUIManager.sendAccessibilityEvent.mockClear(); let viewRef; await act(() => { ReactFabric.render( <View ref={ref => { viewRef = ref; }} />, 11, ); }); expect(nativeFabricUIManager.sendAccessibilityEvent).not.toBeCalled(); ReactFabric.sendAccessibilityEvent(viewRef, 'focus'); expect(nativeFabricUIManager.sendAccessibilityEvent).toHaveBeenCalledTimes( 1, ); expect(nativeFabricUIManager.sendAccessibilityEvent).toHaveBeenCalledWith( expect.any(Object), 'focus', ); }); it('should warn and no-op if calling sendAccessibilityEvent on non native refs', async () => { class BasicClass extends React.Component { render() { return <React.Fragment />; } } nativeFabricUIManager.sendAccessibilityEvent.mockReset(); let viewRef; await act(() => { ReactFabric.render( <BasicClass ref={ref => { viewRef = ref; }} />, 11, ); }); expect(nativeFabricUIManager.sendAccessibilityEvent).not.toBeCalled(); expect(() => { ReactFabric.sendAccessibilityEvent(viewRef, 'eventTypeName'); }).toErrorDev([SEND_ACCESSIBILITY_EVENT_REQUIRES_HOST_COMPONENT], { withoutStack: true, }); expect(nativeFabricUIManager.sendAccessibilityEvent).not.toBeCalled(); }); it('returns the correct instance and calls it in the callback', () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); let a; let b; const c = ReactFabric.render( <View foo="foo" ref={v => (a = v)} />, 11, function () { b = this; }, ); expect(a).toBeTruthy(); expect(a).toBe(b); expect(a).toBe(c); }); it('renders and reorders children', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {title: true}, uiViewClassName: 'RCTView', })); class Component extends React.Component { render() { const chars = this.props.chars.split(''); return ( <View> {chars.map(text => ( <View key={text} title={text} /> ))} </View> ); } } // Mini multi-child stress test: lots of reorders, some adds, some removes. const before = 'abcdefghijklmnopqrst'; const after = 'mxhpgwfralkeoivcstzy'; await act(() => { ReactFabric.render(<Component chars={before} />, 11); }); expect( nativeFabricUIManager.__dumpHierarchyForJestTestsOnly(), ).toMatchSnapshot(); await act(() => { ReactFabric.render(<Component chars={after} />, 11); }); expect( nativeFabricUIManager.__dumpHierarchyForJestTestsOnly(), ).toMatchSnapshot(); }); it('recreates host parents even if only children changed', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {title: true}, uiViewClassName: 'RCTView', })); const before = 'abcdefghijklmnopqrst'; const after = 'mxhpgwfralkeoivcstzy'; class Component extends React.Component { state = { chars: before, }; render() { const chars = this.state.chars.split(''); return ( <View> {chars.map(text => ( <View key={text} title={text} /> ))} </View> ); } } const ref = React.createRef(); // Wrap in a host node. await act(() => { ReactFabric.render( <View> <Component ref={ref} /> </View>, 11, ); }); expect( nativeFabricUIManager.__dumpHierarchyForJestTestsOnly(), ).toMatchSnapshot(); // Call setState() so that we skip over the top-level host node. // It should still get recreated despite a bailout. ref.current.setState({ chars: after, }); expect( nativeFabricUIManager.__dumpHierarchyForJestTestsOnly(), ).toMatchSnapshot(); }); it('calls setState with no arguments', async () => { let mockArgs; class Component extends React.Component { componentDidMount() { this.setState({}, (...args) => (mockArgs = args)); } render() { return false; } } await act(() => { ReactFabric.render(<Component />, 11); }); expect(mockArgs.length).toEqual(0); }); it('should call complete after inserting children', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); const snapshots = []; nativeFabricUIManager.completeRoot.mockImplementation( function (rootTag, newChildSet) { snapshots.push( nativeFabricUIManager.__dumpChildSetForJestTestsOnly(newChildSet), ); }, ); await act(() => { ReactFabric.render( <View foo="a"> <View foo="b" /> </View>, 22, ); }); expect(snapshots).toMatchSnapshot(); }); it('should not throw when <View> is used inside of a <Text> ancestor', async () => { const Image = createReactNativeComponentClass('RCTImage', () => ({ validAttributes: {}, uiViewClassName: 'RCTImage', })); const Text = createReactNativeComponentClass('RCTText', () => ({ validAttributes: {}, uiViewClassName: 'RCTText', })); const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {}, uiViewClassName: 'RCTView', })); await act(() => { ReactFabric.render( <Text> <View /> </Text>, 11, ); }); await act(() => { ReactFabric.render( <Text> <Image /> </Text>, 11, ); }); }); it('should console error for text not inside of a <Text> ancestor', async () => { const ScrollView = createReactNativeComponentClass('RCTScrollView', () => ({ validAttributes: {}, uiViewClassName: 'RCTScrollView', })); const Text = createReactNativeComponentClass('RCTText', () => ({ validAttributes: {}, uiViewClassName: 'RCTText', })); const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {}, uiViewClassName: 'RCTView', })); await expect(async () => { await act(() => { ReactFabric.render(<View>this should warn</View>, 11); }); }).toErrorDev(['Text strings must be rendered within a <Text> component.']); await expect(async () => { await act(() => { ReactFabric.render( <Text> <ScrollView>hi hello hi</ScrollView> </Text>, 11, ); }); }).toErrorDev(['Text strings must be rendered within a <Text> component.']); }); it('should not throw for text inside of an indirect <Text> ancestor', async () => { const Text = createReactNativeComponentClass('RCTText', () => ({ validAttributes: {}, uiViewClassName: 'RCTText', })); const Indirection = () => 'Hi'; await act(() => { ReactFabric.render( <Text> <Indirection /> </Text>, 11, ); }); }); it('dispatches events to the last committed props', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {}, uiViewClassName: 'RCTView', directEventTypes: { topTouchStart: { registrationName: 'onTouchStart', }, }, })); const touchStart = jest.fn(); const touchStart2 = jest.fn(); await act(() => { ReactFabric.render(<View onTouchStart={touchStart} />, 11); }); expect(nativeFabricUIManager.createNode.mock.calls.length).toBe(1); expect(nativeFabricUIManager.registerEventHandler.mock.calls.length).toBe( 1, ); const [, , , , instanceHandle] = nativeFabricUIManager.createNode.mock.calls[0]; const [dispatchEvent] = nativeFabricUIManager.registerEventHandler.mock.calls[0]; const touchEvent = { touches: [], changedTouches: [], }; expect(touchStart).not.toBeCalled(); dispatchEvent(instanceHandle, 'topTouchStart', touchEvent); expect(touchStart).toBeCalled(); expect(touchStart2).not.toBeCalled(); await act(() => { ReactFabric.render(<View onTouchStart={touchStart2} />, 11); }); // Intentionally dispatch to the same instanceHandle again. dispatchEvent(instanceHandle, 'topTouchStart', touchEvent); // The current semantics dictate that we always dispatch to the last committed // props even though the actual scheduling of the event could have happened earlier. // This could change in the future. expect(touchStart2).toBeCalled(); }); describe('skipBubbling', () => { it('should skip bubbling to ancestor if specified', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {}, uiViewClassName: 'RCTView', bubblingEventTypes: { topDefaultBubblingEvent: { phasedRegistrationNames: { captured: 'onDefaultBubblingEventCapture', bubbled: 'onDefaultBubblingEvent', }, }, topBubblingEvent: { phasedRegistrationNames: { captured: 'onBubblingEventCapture', bubbled: 'onBubblingEvent', skipBubbling: false, }, }, topSkipBubblingEvent: { phasedRegistrationNames: { captured: 'onSkippedBubblingEventCapture', bubbled: 'onSkippedBubblingEvent', skipBubbling: true, }, }, }, })); const ancestorBubble = jest.fn(); const ancestorCapture = jest.fn(); const targetBubble = jest.fn(); const targetCapture = jest.fn(); const event = {}; await act(() => { ReactFabric.render( <View onSkippedBubblingEventCapture={ancestorCapture} onDefaultBubblingEventCapture={ancestorCapture} onBubblingEventCapture={ancestorCapture} onSkippedBubblingEvent={ancestorBubble} onDefaultBubblingEvent={ancestorBubble} onBubblingEvent={ancestorBubble}> <View onSkippedBubblingEventCapture={targetCapture} onDefaultBubblingEventCapture={targetCapture} onBubblingEventCapture={targetCapture} onSkippedBubblingEvent={targetBubble} onDefaultBubblingEvent={targetBubble} onBubblingEvent={targetBubble} /> </View>, 11, ); }); expect(nativeFabricUIManager.createNode.mock.calls.length).toBe(2); expect(nativeFabricUIManager.registerEventHandler.mock.calls.length).toBe( 1, ); const [, , , , childInstance] = nativeFabricUIManager.createNode.mock.calls[0]; const [dispatchEvent] = nativeFabricUIManager.registerEventHandler.mock.calls[0]; dispatchEvent(childInstance, 'topDefaultBubblingEvent', event); expect(targetBubble).toHaveBeenCalledTimes(1); expect(targetCapture).toHaveBeenCalledTimes(1); expect(ancestorCapture).toHaveBeenCalledTimes(1); expect(ancestorBubble).toHaveBeenCalledTimes(1); ancestorBubble.mockReset(); ancestorCapture.mockReset(); targetBubble.mockReset(); targetCapture.mockReset(); dispatchEvent(childInstance, 'topBubblingEvent', event); expect(targetBubble).toHaveBeenCalledTimes(1); expect(targetCapture).toHaveBeenCalledTimes(1); expect(ancestorCapture).toHaveBeenCalledTimes(1); expect(ancestorBubble).toHaveBeenCalledTimes(1); ancestorBubble.mockReset(); ancestorCapture.mockReset(); targetBubble.mockReset(); targetCapture.mockReset(); dispatchEvent(childInstance, 'topSkipBubblingEvent', event); expect(targetBubble).toHaveBeenCalledTimes(1); expect(targetCapture).toHaveBeenCalledTimes(1); expect(ancestorCapture).toHaveBeenCalledTimes(1); expect(ancestorBubble).not.toBeCalled(); }); }); it('dispatches event with target as instance', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: { id: true, }, uiViewClassName: 'RCTView', directEventTypes: { topTouchStart: { registrationName: 'onTouchStart', }, topTouchEnd: { registrationName: 'onTouchEnd', }, }, })); function getViewById(id) { const [reactTag, , , , instanceHandle] = nativeFabricUIManager.createNode.mock.calls.find( args => args[3] && args[3].id === id, ); return {reactTag, instanceHandle}; } const ref1 = React.createRef(); const ref2 = React.createRef(); await act(() => { ReactFabric.render( <View id="parent"> <View ref={ref1} id="one" onResponderStart={event => { expect(ref1.current).not.toBeNull(); // Check for referential equality expect(ref1.current).toBe(event.target); expect(ref1.current).toBe(event.currentTarget); }} onStartShouldSetResponder={() => true} /> <View ref={ref2} id="two" onResponderStart={event => { expect(ref2.current).not.toBeNull(); // Check for referential equality expect(ref2.current).toBe(event.target); expect(ref2.current).toBe(event.currentTarget); }} onStartShouldSetResponder={() => true} /> </View>, 1, ); }); const [dispatchEvent] = nativeFabricUIManager.registerEventHandler.mock.calls[0]; dispatchEvent(getViewById('one').instanceHandle, 'topTouchStart', { target: getViewById('one').reactTag, identifier: 17, touches: [], changedTouches: [], }); dispatchEvent(getViewById('one').instanceHandle, 'topTouchEnd', { target: getViewById('one').reactTag, identifier: 17, touches: [], changedTouches: [], }); dispatchEvent(getViewById('two').instanceHandle, 'topTouchStart', { target: getViewById('two').reactTag, identifier: 17, touches: [], changedTouches: [], }); dispatchEvent(getViewById('two').instanceHandle, 'topTouchEnd', { target: getViewById('two').reactTag, identifier: 17, touches: [], changedTouches: [], }); expect.assertions(6); }); it('findHostInstance_DEPRECATED should warn if used to find a host component inside StrictMode', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); let parent = undefined; let child = undefined; class ContainsStrictModeChild extends React.Component { render() { return ( <StrictMode> <View ref={n => (child = n)} /> </StrictMode> ); } } await act(() => { ReactFabric.render( <ContainsStrictModeChild ref={n => (parent = n)} />, 11, ); }); let match; expect( () => (match = ReactFabric.findHostInstance_DEPRECATED(parent)), ).toErrorDev([ 'Warning: findHostInstance_DEPRECATED is deprecated in StrictMode. ' + 'findHostInstance_DEPRECATED was passed an instance of ContainsStrictModeChild which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node' + '\n in RCTView (at **)' + '\n in ContainsStrictModeChild (at **)', ]); expect(match).toBe(child); }); it('findHostInstance_DEPRECATED should warn if passed a component that is inside StrictMode', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); let parent = undefined; let child = undefined; class IsInStrictMode extends React.Component { render() { return <View ref={n => (child = n)} />; } } await act(() => { ReactFabric.render( <StrictMode> <IsInStrictMode ref={n => (parent = n)} /> </StrictMode>, 11, ); }); let match; expect( () => (match = ReactFabric.findHostInstance_DEPRECATED(parent)), ).toErrorDev([ 'Warning: findHostInstance_DEPRECATED is deprecated in StrictMode. ' + 'findHostInstance_DEPRECATED was passed an instance of IsInStrictMode which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node' + '\n in RCTView (at **)' + '\n in IsInStrictMode (at **)', ]); expect(match).toBe(child); }); it('findNodeHandle should warn if used to find a host component inside StrictMode', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); let parent = undefined; let child = undefined; class ContainsStrictModeChild extends React.Component { render() { return ( <StrictMode> <View ref={n => (child = n)} /> </StrictMode> ); } } await act(() => { ReactFabric.render( <ContainsStrictModeChild ref={n => (parent = n)} />, 11, ); }); let match; expect(() => (match = ReactFabric.findNodeHandle(parent))).toErrorDev([ 'Warning: findNodeHandle is deprecated in StrictMode. ' + 'findNodeHandle was passed an instance of ContainsStrictModeChild which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node' + '\n in RCTView (at **)' + '\n in ContainsStrictModeChild (at **)', ]); expect(match).toBe( ReactNativePrivateInterface.getNativeTagFromPublicInstance(child), ); }); it('findNodeHandle should warn if passed a component that is inside StrictMode', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); let parent = undefined; let child = undefined; class IsInStrictMode extends React.Component { render() { return <View ref={n => (child = n)} />; } } await act(() => { ReactFabric.render( <StrictMode> <IsInStrictMode ref={n => (parent = n)} /> </StrictMode>, 11, ); }); let match; expect(() => (match = ReactFabric.findNodeHandle(parent))).toErrorDev([ 'Warning: findNodeHandle is deprecated in StrictMode. ' + 'findNodeHandle was passed an instance of IsInStrictMode which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node' + '\n in RCTView (at **)' + '\n in IsInStrictMode (at **)', ]); expect(match).toBe( ReactNativePrivateInterface.getNativeTagFromPublicInstance(child), ); }); it('should no-op if calling sendAccessibilityEvent on unmounted refs', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); nativeFabricUIManager.sendAccessibilityEvent.mockReset(); let viewRef; await act(() => { ReactFabric.render( <View ref={ref => { viewRef = ref; }} />, 11, ); }); const dangerouslyRetainedViewRef = viewRef; await act(() => { ReactFabric.stopSurface(11); }); ReactFabric.sendAccessibilityEvent( dangerouslyRetainedViewRef, 'eventTypeName', ); expect(nativeFabricUIManager.sendAccessibilityEvent).not.toBeCalled(); }); it('getNodeFromInternalInstanceHandle should return the correct shadow node', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); await act(() => { ReactFabric.render(<View foo="test" />, 1); }); const internalInstanceHandle = nativeFabricUIManager.createNode.mock.calls[0][4]; expect(internalInstanceHandle).toEqual(expect.any(Object)); const expectedShadowNode = nativeFabricUIManager.createNode.mock.results[0].value; expect(expectedShadowNode).toEqual(expect.any(Object)); const node = ReactFabric.getNodeFromInternalInstanceHandle( internalInstanceHandle, ); expect(node).toBe(expectedShadowNode); }); it('getPublicInstanceFromInternalInstanceHandle should provide public instances for HostComponent', async () => { const View = createReactNativeComponentClass('RCTView', () => ({ validAttributes: {foo: true}, uiViewClassName: 'RCTView', })); let viewRef; await act(() => { ReactFabric.render( <View foo="test" ref={ref => { viewRef = ref; }} />, 1, ); }); const internalInstanceHandle = nativeFabricUIManager.createNode.mock.calls[0][4]; expect(internalInstanceHandle).toEqual(expect.any(Object)); const publicInstance = ReactFabric.getPublicInstanceFromInternalInstanceHandle( internalInstanceHandle, ); expect(publicInstance).toBe(viewRef); await act(() => { ReactFabric.render(null, 1); }); const publicInstanceAfterUnmount = ReactFabric.getPublicInstanceFromInternalInstanceHandle( internalInstanceHandle, ); expect(publicInstanceAfterUnmount).toBe(null); }); it('getPublicInstanceFromInternalInstanceHandle should provide public instances for HostText', async () => { jest.spyOn(ReactNativePrivateInterface, 'createPublicTextInstance'); const RCTText = createReactNativeComponentClass('RCTText', () => ({ validAttributes: {}, uiViewClassName: 'RCTText', })); await act(() => { ReactFabric.render(<RCTText>Text content</RCTText>, 1); }); // Access the internal instance handle used to create the text node. const internalInstanceHandle = nativeFabricUIManager.createNode.mock.calls[0][4]; expect(internalInstanceHandle).toEqual(expect.any(Object)); // Text public instances should be created lazily. expect( ReactNativePrivateInterface.createPublicTextInstance, ).not.toHaveBeenCalled(); const publicInstance = ReactFabric.getPublicInstanceFromInternalInstanceHandle( internalInstanceHandle, ); // We just requested the text public instance, so it should have been created at this point. expect( ReactNativePrivateInterface.createPublicTextInstance, ).toHaveBeenCalledTimes(1); expect( ReactNativePrivateInterface.createPublicTextInstance, ).toHaveBeenCalledWith(internalInstanceHandle); const expectedPublicInstance = ReactNativePrivateInterface.createPublicTextInstance.mock.results[0] .value; expect(publicInstance).toBe(expectedPublicInstance); await act(() => { ReactFabric.render(null, 1); }); const publicInstanceAfterUnmount = ReactFabric.getPublicInstanceFromInternalInstanceHandle( internalInstanceHandle, ); expect(publicInstanceAfterUnmount).toBe(null); }); });
28.798134
125
0.619994
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 { pointEqualToPoint, sizeEqualToSize, rectEqualToRect, sizeIsValid, sizeIsEmpty, rectIntersectsRect, intersectionOfRects, rectContainsPoint, unionOfRects, } from '../geometry'; describe(pointEqualToPoint, () => { it('should return true when 2 points have the same values', () => { expect(pointEqualToPoint({x: 1, y: 1}, {x: 1, y: 1})).toBe(true); expect(pointEqualToPoint({x: -1, y: 2}, {x: -1, y: 2})).toBe(true); expect( pointEqualToPoint({x: 3.14159, y: 0.26535}, {x: 3.14159, y: 0.26535}), ).toBe(true); }); it('should return false when 2 points have different values', () => { expect(pointEqualToPoint({x: 1, y: 1}, {x: 1, y: 0})).toBe(false); expect(pointEqualToPoint({x: -1, y: 2}, {x: 0, y: 1})).toBe(false); expect( pointEqualToPoint({x: 3.1416, y: 0.26534}, {x: 3.14159, y: 0.26535}), ).toBe(false); }); }); describe(sizeEqualToSize, () => { it('should return true when 2 sizes have the same values', () => { expect(sizeEqualToSize({width: 1, height: 1}, {width: 1, height: 1})).toBe( true, ); expect( sizeEqualToSize({width: -1, height: 2}, {width: -1, height: 2}), ).toBe(true); expect( sizeEqualToSize( {width: 3.14159, height: 0.26535}, {width: 3.14159, height: 0.26535}, ), ).toBe(true); }); it('should return false when 2 sizes have different values', () => { expect(sizeEqualToSize({width: 1, height: 1}, {width: 1, height: 0})).toBe( false, ); expect(sizeEqualToSize({width: -1, height: 2}, {width: 0, height: 1})).toBe( false, ); expect( sizeEqualToSize( {width: 3.1416, height: 0.26534}, {width: 3.14159, height: 0.26535}, ), ).toBe(false); }); }); describe(rectEqualToRect, () => { it('should return true when 2 rects have the same values', () => { expect( rectEqualToRect( {origin: {x: 1, y: 1}, size: {width: 1, height: 1}}, {origin: {x: 1, y: 1}, size: {width: 1, height: 1}}, ), ).toBe(true); expect( rectEqualToRect( {origin: {x: 1, y: 2}, size: {width: 3.14, height: 4}}, {origin: {x: 1, y: 2}, size: {width: 3.14, height: 4}}, ), ).toBe(true); }); it('should return false when 2 rects have different values', () => { expect( rectEqualToRect( {origin: {x: 1, y: 1}, size: {width: 1, height: 1}}, {origin: {x: 0, y: 1}, size: {width: 1, height: 1}}, ), ).toBe(false); expect( rectEqualToRect( {origin: {x: 1, y: 2}, size: {width: 3.14, height: 4}}, {origin: {x: 1, y: 2}, size: {width: 3.15, height: 4}}, ), ).toBe(false); }); }); describe(sizeIsValid, () => { it('should return true when the size has non-negative width and height', () => { expect(sizeIsValid({width: 1, height: 1})).toBe(true); expect(sizeIsValid({width: 0, height: 0})).toBe(true); }); it('should return false when the size has negative width or height', () => { expect(sizeIsValid({width: 0, height: -1})).toBe(false); expect(sizeIsValid({width: -1, height: 0})).toBe(false); expect(sizeIsValid({width: -1, height: -1})).toBe(false); }); }); describe(sizeIsEmpty, () => { it('should return true when the size has negative area', () => { expect(sizeIsEmpty({width: 1, height: -1})).toBe(true); expect(sizeIsEmpty({width: -1, height: -1})).toBe(true); }); it('should return true when the size has zero area', () => { expect(sizeIsEmpty({width: 0, height: 0})).toBe(true); expect(sizeIsEmpty({width: 0, height: 1})).toBe(true); expect(sizeIsEmpty({width: 1, height: 0})).toBe(true); }); it('should return false when the size has positive area', () => { expect(sizeIsEmpty({width: 1, height: 1})).toBe(false); expect(sizeIsEmpty({width: 2, height: 1})).toBe(false); }); }); describe(rectIntersectsRect, () => { it('should return true when 2 rects intersect', () => { // Rects touch expect( rectIntersectsRect( {origin: {x: 0, y: 0}, size: {width: 1, height: 1}}, {origin: {x: 1, y: 1}, size: {width: 1, height: 1}}, ), ).toEqual(true); // Rects overlap expect( rectIntersectsRect( {origin: {x: 0, y: 0}, size: {width: 2, height: 1}}, {origin: {x: 1, y: -2}, size: {width: 0.5, height: 5}}, ), ).toEqual(true); // Rects are equal expect( rectIntersectsRect( {origin: {x: 1, y: 2}, size: {width: 3.14, height: 4}}, {origin: {x: 1, y: 2}, size: {width: 3.14, height: 4}}, ), ).toEqual(true); }); it('should return false when 2 rects do not intersect', () => { expect( rectIntersectsRect( {origin: {x: 0, y: 1}, size: {width: 1, height: 1}}, {origin: {x: 0, y: 10}, size: {width: 1, height: 1}}, ), ).toBe(false); expect( rectIntersectsRect( {origin: {x: 1, y: 2}, size: {width: 3.14, height: 4}}, {origin: {x: -4, y: 2}, size: {width: 3.15, height: 4}}, ), ).toBe(false); }); }); describe(intersectionOfRects, () => { // NOTE: Undefined behavior if rects do not intersect it('should return intersection when 2 rects intersect', () => { // Rects touch expect( intersectionOfRects( {origin: {x: 0, y: 0}, size: {width: 1, height: 1}}, {origin: {x: 1, y: 1}, size: {width: 1, height: 1}}, ), ).toEqual({origin: {x: 1, y: 1}, size: {width: 0, height: 0}}); // Rects overlap expect( intersectionOfRects( {origin: {x: 0, y: 0}, size: {width: 2, height: 1}}, {origin: {x: 1, y: -2}, size: {width: 0.5, height: 5}}, ), ).toEqual({origin: {x: 1, y: 0}, size: {width: 0.5, height: 1}}); // Rects are equal expect( intersectionOfRects( {origin: {x: 1, y: 2}, size: {width: 9.24, height: 4}}, {origin: {x: 1, y: 2}, size: {width: 9.24, height: 4}}, ), ).toEqual({origin: {x: 1, y: 2}, size: {width: 9.24, height: 4}}); }); }); describe(rectContainsPoint, () => { it("should return true if point is on the rect's edge", () => { expect( rectContainsPoint( {x: 0, y: 0}, {origin: {x: 0, y: 0}, size: {width: 1, height: 1}}, ), ).toBe(true); expect( rectContainsPoint( {x: 5, y: 0}, {origin: {x: 0, y: 0}, size: {width: 10, height: 1}}, ), ).toBe(true); expect( rectContainsPoint( {x: 1, y: 1}, {origin: {x: 0, y: 0}, size: {width: 1, height: 1}}, ), ).toBe(true); }); it('should return true if point is in rect', () => { expect( rectContainsPoint( {x: 5, y: 50}, {origin: {x: 0, y: 0}, size: {width: 10, height: 100}}, ), ).toBe(true); }); it('should return false if point is not in rect', () => { expect( rectContainsPoint( {x: -1, y: 0}, {origin: {x: 0, y: 0}, size: {width: 1, height: 1}}, ), ).toBe(false); }); }); describe(unionOfRects, () => { it('should return zero rect if no rects are provided', () => { expect(unionOfRects()).toEqual({ origin: {x: 0, y: 0}, size: {width: 0, height: 0}, }); }); it('should return rect if 1 rect is provided', () => { expect( unionOfRects({origin: {x: 1, y: 2}, size: {width: 3, height: 4}}), ).toEqual({origin: {x: 1, y: 2}, size: {width: 3, height: 4}}); }); it('should return union of rects if more than one rect is provided', () => { expect( unionOfRects( {origin: {x: 1, y: 2}, size: {width: 3, height: 4}}, {origin: {x: 100, y: 200}, size: {width: 3, height: 4}}, {origin: {x: -10, y: -20}, size: {width: 50, height: 60}}, ), ).toEqual({origin: {x: -10, y: -20}, size: {width: 113, height: 224}}); }); });
28.67033
82
0.536116
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'; const rule = require('../no-to-warn-dev-within-to-throw'); const {RuleTester} = require('eslint'); const ruleTester = new RuleTester(); ruleTester.run('eslint-rules/no-to-warn-dev-within-to-throw', rule, { valid: [ 'expect(callback).toWarnDev("warning");', 'expect(function() { expect(callback).toThrow("error") }).toWarnDev("warning");', ], invalid: [ { code: 'expect(function() { expect(callback).toWarnDev("warning") }).toThrow("error");', errors: [ { message: 'toWarnDev() matcher should not be nested', }, ], }, ], });
24.8125
93
0.620606
null
'use strict'; module.exports = require('react-shallow-renderer');
16
51
0.731343
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireDefault(require("react")); var _useTheme = _interopRequireDefault(require("./useTheme")); var _jsxFileName = ""; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Component() { const theme = (0, _useTheme.default)(); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 10 } }, "theme: ", theme); } //# sourceMappingURL=ComponentWithExternalCustomHooks.js.map?foo=bar&param=some_value
25.423077
95
0.670554
null
/** * @license React * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable max-len */ 'use strict'; (function (global, factory) { // eslint-disable-next-line ft-flow/no-unused-expressions typeof exports === 'object' && typeof module !== 'undefined' ? (module.exports = factory(require('react'))) : typeof define === 'function' && define.amd // eslint-disable-line no-undef ? define(['react'], factory) // eslint-disable-line no-undef : (global.Scheduler = factory(global)); })(this, function (global) { function unstable_now() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_now.apply( this, arguments ); } function unstable_scheduleCallback() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_scheduleCallback.apply( this, arguments ); } function unstable_cancelCallback() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_cancelCallback.apply( this, arguments ); } function unstable_shouldYield() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_shouldYield.apply( this, arguments ); } function unstable_requestPaint() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_requestPaint.apply( this, arguments ); } function unstable_runWithPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_runWithPriority.apply( this, arguments ); } function unstable_next() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_next.apply( this, arguments ); } function unstable_wrapCallback() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_wrapCallback.apply( this, arguments ); } function unstable_getCurrentPriorityLevel() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getCurrentPriorityLevel.apply( this, arguments ); } function unstable_getFirstCallbackNode() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_getFirstCallbackNode.apply( this, arguments ); } function unstable_pauseExecution() { return undefined; } function unstable_continueExecution() { return undefined; } function unstable_forceFrameRate() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler.unstable_forceFrameRate.apply( this, arguments ); } return Object.freeze({ unstable_now: unstable_now, unstable_scheduleCallback: unstable_scheduleCallback, unstable_cancelCallback: unstable_cancelCallback, unstable_shouldYield: unstable_shouldYield, unstable_requestPaint: unstable_requestPaint, unstable_runWithPriority: unstable_runWithPriority, unstable_next: unstable_next, unstable_wrapCallback: unstable_wrapCallback, unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel, unstable_continueExecution: unstable_continueExecution, unstable_pauseExecution: unstable_pauseExecution, unstable_getFirstCallbackNode: unstable_getFirstCallbackNode, unstable_forceFrameRate: unstable_forceFrameRate, get unstable_IdlePriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_IdlePriority; }, get unstable_ImmediatePriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_ImmediatePriority; }, get unstable_LowPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_LowPriority; }, get unstable_NormalPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_NormalPriority; }, get unstable_UserBlockingPriority() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_UserBlockingPriority; }, get unstable_Profiling() { return global.React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED .Scheduler.unstable_Profiling; }, }); });
30.612245
124
0.701679
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './index.classic.fb.js'; export { createComponentSelector, createHasPseudoClassSelector, createRoleSelector, createTestNameSelector, createTextSelector, getFindAllNodesFailureDescription, findAllNodes, findBoundingRects, focusWithin, observeVisibleRects, } from 'react-reconciler/src/ReactFiberReconciler';
22.73913
66
0.761468
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/ReactFlightTurbopackNodeLoader.js';
22.909091
66
0.706107
owtf
/** @license React v17.0.0-rc.3 * 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 _assign = require('object-assign'); // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; exports.Fragment = 0xeacb; var REACT_STRICT_MODE_TYPE = 0xeacc; var REACT_PROFILER_TYPE = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; var REACT_SUSPENSE_TYPE = 0xead1; var REACT_SUSPENSE_LIST_TYPE = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_BLOCK_TYPE = 0xead9; var REACT_SERVER_BLOCK_TYPE = 0xeada; var REACT_FUNDAMENTAL_TYPE = 0xead5; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); exports.Fragment = symbolFor('react.fragment'); REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); REACT_PROFILER_TYPE = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_BLOCK_TYPE = symbolFor('react.block'); REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'); REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); } var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function error(format) { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableScopeAPI = false; // Experimental Create Event Handle API. function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { return true; } } return false; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } function getContextName(type) { return type.displayName || 'Context'; } 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: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._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 lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentName(init(payload)); } catch (x) { return null; } } } } return null; } // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: _assign({}, props, { value: prevLog }), info: _assign({}, props, { value: prevInfo }), warn: _assign({}, props, { value: prevWarn }), error: _assign({}, props, { value: prevError }), group: _assign({}, props, { value: prevGroup }), groupCollapsed: _assign({}, props, { value: prevGroupCollapsed }), groupEnd: _assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if (!fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_BLOCK_TYPE: return describeFunctionComponentFrame(type._render); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(Object.prototype.hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown; var specialPropRefWarningShown; var didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function warnIfStringRefCannotBeAutoConverted(config, self) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) { var componentName = getComponentName(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref); didWarnAboutStringRefs[componentName] = true; } } } } function defineKeyPropWarningGetter(props, displayName) { { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } } function defineRefPropWarningGetter(props, displayName) { { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * https://github.com/reactjs/rfcs/pull/107 * @param {*} type * @param {object} props * @param {string} key */ function jsxDEV(type, config, maybeKey, source, self) { { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; // Currently, key can be spread in as a prop. This causes a potential // issue if key is also explicitly declared (ie. <div {...props} key="Hi" /> // or <div key="Hi" {...props} /> ). We want to deprecate key spread, // but as an intermediary step, we will use jsxDEV for everything except // <div {...props} key="Hi" />, because we aren't currently able to tell if // key is explicitly declared to be undefined or not. if (maybeKey !== undefined) { key = '' + maybeKey; } if (hasValidKey(config)) { key = '' + config.key; } if (hasValidRef(config)) { ref = config.ref; warnIfStringRefCannotBeAutoConverted(config, self); } // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } } var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } } function getDeclarationErrorAddendum() { { if (ReactCurrentOwner$1.current) { var name = getComponentName(ReactCurrentOwner$1.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } } function getSourceInfoErrorAddendum(source) { { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; } setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentName(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentName(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function jsxWithValidation(type, props, key, isStaticChildren, source, self) { { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(source); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { var children = props.children; if (children !== undefined) { if (isStaticChildren) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { validateChildKeys(children[i], type); } if (Object.freeze) { Object.freeze(children); } } else { error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.'); } } else { validateChildKeys(children, type); } } } if (type === exports.Fragment) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } } // These two functions exist to still get child warnings in dev var jsxDEV$1 = jsxWithValidation ; exports.jsxDEV = jsxDEV$1; })(); }
30.362957
450
0.639301
Hands-On-Penetration-Testing-with-Python
"use strict"; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const { useMemo, useState } = require('react'); function Component(props) { const InnerComponent = useMemo(() => () => { const [state] = useState(0); return state; }); props.callback(InnerComponent); return null; } module.exports = { Component }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhOZXN0ZWRIb29rcy5qcyJdLCJuYW1lcyI6WyJ1c2VNZW1vIiwidXNlU3RhdGUiLCJyZXF1aXJlIiwiQ29tcG9uZW50IiwicHJvcHMiLCJJbm5lckNvbXBvbmVudCIsInN0YXRlIiwiY2FsbGJhY2siLCJtb2R1bGUiLCJleHBvcnRzIl0sIm1hcHBpbmdzIjoiOztBQUFBOzs7Ozs7OztBQVFBLE1BQU07QUFBQ0EsRUFBQUEsT0FBRDtBQUFVQyxFQUFBQTtBQUFWLElBQXNCQyxPQUFPLENBQUMsT0FBRCxDQUFuQzs7QUFFQSxTQUFTQyxTQUFULENBQW1CQyxLQUFuQixFQUEwQjtBQUN4QixRQUFNQyxjQUFjLEdBQUdMLE9BQU8sQ0FBQyxNQUFNLE1BQU07QUFDekMsVUFBTSxDQUFDTSxLQUFELElBQVVMLFFBQVEsQ0FBQyxDQUFELENBQXhCO0FBRUEsV0FBT0ssS0FBUDtBQUNELEdBSjZCLENBQTlCO0FBS0FGLEVBQUFBLEtBQUssQ0FBQ0csUUFBTixDQUFlRixjQUFmO0FBRUEsU0FBTyxJQUFQO0FBQ0Q7O0FBRURHLE1BQU0sQ0FBQ0MsT0FBUCxHQUFpQjtBQUFDTixFQUFBQTtBQUFELENBQWpCIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5jb25zdCB7dXNlTWVtbywgdXNlU3RhdGV9ID0gcmVxdWlyZSgncmVhY3QnKTtcblxuZnVuY3Rpb24gQ29tcG9uZW50KHByb3BzKSB7XG4gIGNvbnN0IElubmVyQ29tcG9uZW50ID0gdXNlTWVtbygoKSA9PiAoKSA9PiB7XG4gICAgY29uc3QgW3N0YXRlXSA9IHVzZVN0YXRlKDApO1xuXG4gICAgcmV0dXJuIHN0YXRlO1xuICB9KTtcbiAgcHJvcHMuY2FsbGJhY2soSW5uZXJDb21wb25lbnQpO1xuXG4gIHJldHVybiBudWxsO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHtDb21wb25lbnR9O1xuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiIsIklubmVyQ29tcG9uZW50Iiwic3RhdGUiXSwibWFwcGluZ3MiOiJDQUFEO1l5QkNBO2FMQ0EsQVdEQTtnQjNCREEifV1dXX19XX0=
77.607143
1,716
0.916818
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from '../ReactServerStreamConfigNode';
22
66
0.702381
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Request} from 'react-server/src/ReactFlightServer'; export * from '../ReactFlightServerConfigBundlerCustom'; export * from '../ReactFlightServerConfigDebugNoop'; export type Hints = any; export type HintCode = any; // eslint-disable-next-line no-unused-vars export type HintModel<T: any> = any; export const isPrimaryRenderer = false; export const prepareHostDispatcher = () => {}; export const supportsRequestStorage = false; export const requestStorage: AsyncLocalStorage<Request> = (null: any); export function createHints(): any { return null; }
24.064516
70
0.740979
owtf
/** * Copyright (c) Facebook, Inc. and its affiliates. */ // Do not delete or move this file. // Many fiddles reference it so we have to keep it here. (function() { var tag = document.querySelector( 'script[type="application/javascript;version=1.7"]' ); if (!tag || tag.textContent.indexOf('window.onload=function(){') !== -1) { alert('Bad JSFiddle configuration, please fork the original React JSFiddle'); } tag.setAttribute('type', 'text/babel'); tag.textContent = tag.textContent.replace(/^\/\/<!\[CDATA\[/, ''); })();
31.117647
81
0.655046
Hands-On-Bug-Hunting-for-Penetration-Testers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-webpack-server.browser.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-webpack-server.browser.development.js'); }
31.375
94
0.713178
owtf
import React from 'react'; import {StrictMode} from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import App from './App'; import {store} from '../store'; ReactDOM.render( <StrictMode> <Provider store={store}> <App /> </Provider> </StrictMode>, document.getElementById('root') );
20.0625
37
0.666667
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 type { Request, ReactClientValue, } from 'react-server/src/ReactFlightServer'; import type {Destination} from 'react-server/src/ReactServerStreamConfigNode'; import type {ClientManifest} from './ReactFlightServerConfigTurbopackBundler'; import type {ServerManifest} from 'react-client/src/ReactFlightClientConfig'; import type {Busboy} from 'busboy'; import type {Writable} from 'stream'; import type {ServerContextJSONValue, Thenable} from 'shared/ReactTypes'; import { createRequest, startWork, startFlowing, abort, } from 'react-server/src/ReactFlightServer'; import { createResponse, reportGlobalError, close, resolveField, resolveFileInfo, resolveFileChunk, resolveFileComplete, getRoot, } from 'react-server/src/ReactFlightReplyServer'; import {decodeAction} from 'react-server/src/ReactFlightActionServer'; export { registerServerReference, registerClientReference, createClientModuleProxy, } from './ReactFlightTurbopackReferences'; function createDrainHandler(destination: Destination, request: Request) { return () => startFlowing(request, destination); } type Options = { onError?: (error: mixed) => void, onPostpone?: (reason: string) => void, context?: Array<[string, ServerContextJSONValue]>, identifierPrefix?: string, }; type PipeableStream = { abort(reason: mixed): void, pipe<T: Writable>(destination: T): T, }; function renderToPipeableStream( model: ReactClientValue, turbopackMap: ClientManifest, options?: Options, ): PipeableStream { const request = createRequest( model, turbopackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined, ); let hasStartedFlowing = false; startWork(request); return { pipe<T: Writable>(destination: T): T { if (hasStartedFlowing) { throw new Error( 'React currently only supports piping to one writable stream.', ); } hasStartedFlowing = true; startFlowing(request, destination); destination.on('drain', createDrainHandler(destination, request)); return destination; }, abort(reason: mixed) { abort(request, reason); }, }; } function decodeReplyFromBusboy<T>( busboyStream: Busboy, turbopackMap: ServerManifest, ): Thenable<T> { const response = createResponse(turbopackMap, ''); let pendingFiles = 0; const queuedFields: Array<string> = []; busboyStream.on('field', (name, value) => { if (pendingFiles > 0) { // Because the 'end' event fires two microtasks after the next 'field' // we would resolve files and fields out of order. To handle this properly // we queue any fields we receive until the previous file is done. queuedFields.push(name, value); } else { resolveField(response, name, value); } }); busboyStream.on('file', (name, value, {filename, encoding, mimeType}) => { if (encoding.toLowerCase() === 'base64') { throw new Error( "React doesn't accept base64 encoded file uploads because we don't expect " + "form data passed from a browser to ever encode data that way. If that's " + 'the wrong assumption, we can easily fix it.', ); } pendingFiles++; const file = resolveFileInfo(response, name, filename, mimeType); value.on('data', chunk => { resolveFileChunk(response, file, chunk); }); value.on('end', () => { resolveFileComplete(response, name, file); pendingFiles--; if (pendingFiles === 0) { // Release any queued fields for (let i = 0; i < queuedFields.length; i += 2) { resolveField(response, queuedFields[i], queuedFields[i + 1]); } queuedFields.length = 0; } }); }); busboyStream.on('finish', () => { close(response); }); busboyStream.on('error', err => { reportGlobalError( response, // $FlowFixMe[incompatible-call] types Error and mixed are incompatible err, ); }); return getRoot(response); } function decodeReply<T>( body: string | FormData, turbopackMap: ServerManifest, ): Thenable<T> { if (typeof body === 'string') { const form = new FormData(); form.append('0', body); body = form; } const response = createResponse(turbopackMap, '', body); const root = getRoot<T>(response); close(response); return root; } export { renderToPipeableStream, decodeReplyFromBusboy, decodeReply, decodeAction, };
26.77907
86
0.674691
null
'use strict'; const {readdirSync, statSync} = require('fs'); const {join} = require('path'); const baseConfig = require('./config.base'); process.env.IS_BUILD = true; const NODE_MODULES_DIR = process.env.RELEASE_CHANNEL === 'stable' ? 'oss-stable' : 'oss-experimental'; // Find all folders in packages/* with package.json const packagesRoot = join(__dirname, '..', '..', 'packages'); const packages = readdirSync(packagesRoot).filter(dir => { if (dir === 'internal-test-utils') { // This is an internal package used only for testing. It's OK to read // from source. // TODO: Maybe let's have some convention for this? return false; } if (dir.charAt(0) === '.') { return false; } const packagePath = join(packagesRoot, dir, 'package.json'); let stat; try { stat = statSync(packagePath); } catch (err) { return false; } return stat.isFile(); }); // Create a module map to point React packages to the build output const moduleNameMapper = {}; // Allow bundle tests to read (but not write!) default feature flags. // This lets us determine whether we're running in different modes // without making relevant tests internal-only. moduleNameMapper[ '^shared/ReactFeatureFlags' ] = `<rootDir>/packages/shared/forks/ReactFeatureFlags.readonly`; // Map packages to bundles packages.forEach(name => { // Root entry point moduleNameMapper[`^${name}$`] = `<rootDir>/build/${NODE_MODULES_DIR}/${name}`; // Named entry points moduleNameMapper[ `^${name}\/([^\/]+)$` ] = `<rootDir>/build/${NODE_MODULES_DIR}/${name}/$1`; }); moduleNameMapper[ 'use-sync-external-store/shim/with-selector' ] = `<rootDir>/build/${NODE_MODULES_DIR}/use-sync-external-store/shim/with-selector`; moduleNameMapper[ 'use-sync-external-store/shim/index.native' ] = `<rootDir>/build/${NODE_MODULES_DIR}/use-sync-external-store/shim/index.native`; module.exports = Object.assign({}, baseConfig, { // Redirect imports to the compiled bundles moduleNameMapper, modulePathIgnorePatterns: [ ...baseConfig.modulePathIgnorePatterns, 'packages/react-devtools-extensions', 'packages/react-devtools-shared', ], // Don't run bundle tests on -test.internal.* files testPathIgnorePatterns: ['/node_modules/', '-test.internal.js$'], // Exclude the build output from transforms transformIgnorePatterns: ['/node_modules/', '<rootDir>/build/'], setupFiles: [ ...baseConfig.setupFiles, require.resolve('./setupTests.build.js'), ], });
31
85
0.684569
owtf
import * as React from 'react'; import Button from './Button.js'; import Form from './Form.js'; import {like, greet} from './actions.js'; import {getServerState} from './ServerState.js'; const h = React.createElement; export default async function App() { const res = await fetch('http://localhost:3001/todos'); const todos = await res.json(); return h( 'html', { lang: 'en', }, h( 'head', null, h('meta', { charSet: 'utf-8', }), h('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1', }), h('title', null, 'Flight'), h('link', { rel: 'stylesheet', href: '/src/style.css', precedence: 'default', }) ), h( 'body', null, h( 'div', null, h('h1', null, getServerState()), h( 'ul', null, todos.map(todo => h( 'li', { key: todo.id, }, todo.text ) ) ), h(Form, { action: greet, }), h( 'div', null, h( Button, { action: like, }, 'Like' ) ) ) ) ); }
17.093333
57
0.390118
PenetrationTestingScripts
'use strict'; const {resolve} = require('path'); const Webpack = require('webpack'); const DevToolsIgnorePlugin = require('devtools-ignore-webpack-plugin'); const {resolveFeatureFlags} = require('react-devtools-shared/buildUtils'); const { DARK_MODE_DIMMED_WARNING_COLOR, DARK_MODE_DIMMED_ERROR_COLOR, DARK_MODE_DIMMED_LOG_COLOR, LIGHT_MODE_DIMMED_WARNING_COLOR, LIGHT_MODE_DIMMED_ERROR_COLOR, LIGHT_MODE_DIMMED_LOG_COLOR, GITHUB_URL, getVersionString, } = require('./utils'); const NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV) { console.error('NODE_ENV not set'); process.exit(1); } const builtModulesDir = resolve( __dirname, '..', '..', 'build', 'oss-experimental', ); const __DEV__ = NODE_ENV === 'development'; const DEVTOOLS_VERSION = getVersionString(process.env.DEVTOOLS_VERSION); const IS_CHROME = process.env.IS_CHROME === 'true'; const IS_FIREFOX = process.env.IS_FIREFOX === 'true'; const IS_EDGE = process.env.IS_EDGE === 'true'; const featureFlagTarget = process.env.FEATURE_FLAG_TARGET || 'extension-oss'; module.exports = { mode: __DEV__ ? 'development' : 'production', devtool: __DEV__ ? 'cheap-module-source-map' : 'nosources-cheap-source-map', entry: { backend: './src/backend.js', }, output: { path: __dirname + '/build', filename: 'react_devtools_backend_compact.js', }, node: { global: false, }, resolve: { alias: { react: resolve(builtModulesDir, 'react'), 'react-debug-tools': resolve(builtModulesDir, 'react-debug-tools'), 'react-devtools-feature-flags': resolveFeatureFlags(featureFlagTarget), 'react-dom': resolve(builtModulesDir, 'react-dom'), 'react-is': resolve(builtModulesDir, 'react-is'), scheduler: resolve(builtModulesDir, 'scheduler'), }, }, optimization: { minimize: false, }, plugins: [ new Webpack.ProvidePlugin({ process: 'process/browser', }), new Webpack.DefinePlugin({ __DEV__: true, __PROFILE__: false, __DEV____DEV__: true, 'process.env.DEVTOOLS_PACKAGE': `"react-devtools-extensions"`, 'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`, 'process.env.GITHUB_URL': `"${GITHUB_URL}"`, 'process.env.DARK_MODE_DIMMED_WARNING_COLOR': `"${DARK_MODE_DIMMED_WARNING_COLOR}"`, 'process.env.DARK_MODE_DIMMED_ERROR_COLOR': `"${DARK_MODE_DIMMED_ERROR_COLOR}"`, 'process.env.DARK_MODE_DIMMED_LOG_COLOR': `"${DARK_MODE_DIMMED_LOG_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_WARNING_COLOR': `"${LIGHT_MODE_DIMMED_WARNING_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_ERROR_COLOR': `"${LIGHT_MODE_DIMMED_ERROR_COLOR}"`, 'process.env.LIGHT_MODE_DIMMED_LOG_COLOR': `"${LIGHT_MODE_DIMMED_LOG_COLOR}"`, 'process.env.IS_CHROME': IS_CHROME, 'process.env.IS_FIREFOX': IS_FIREFOX, 'process.env.IS_EDGE': IS_EDGE, }), new DevToolsIgnorePlugin({ shouldIgnorePath: function (path) { if (!__DEV__) { return true; } return path.includes('/node_modules/') || path.includes('/webpack/'); }, }), ], module: { rules: [ { test: /\.js$/, loader: 'babel-loader', options: { configFile: resolve( __dirname, '..', 'react-devtools-shared', 'babel.config.js', ), }, }, ], }, };
28.119658
92
0.614504
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-interactions-events/tap.production.min.js'); } else { module.exports = require('./cjs/react-interactions-events/tap.development.js'); }
28.875
84
0.705882
Tricks-Web-Penetration-Tester
// @flow import type {ComponentType} from "react"; import createGridComponent from './createGridComponent'; import type { Props, ScrollToAlign } from './createGridComponent'; const DEFAULT_ESTIMATED_ITEM_SIZE = 50; type VariableSizeProps = {| estimatedColumnWidth: number, estimatedRowHeight: number, ...Props<any>, |}; type itemSizeGetter = (index: number) => number; type ItemType = 'column' | 'row'; type ItemMetadata = {| offset: number, size: number, |}; type ItemMetadataMap = { [index: number]: ItemMetadata, ... }; type InstanceProps = {| columnMetadataMap: ItemMetadataMap, estimatedColumnWidth: number, estimatedRowHeight: number, lastMeasuredColumnIndex: number, lastMeasuredRowIndex: number, rowMetadataMap: ItemMetadataMap, |}; const getEstimatedTotalHeight = ( { rowCount }: Props<any>, { rowMetadataMap, estimatedRowHeight, lastMeasuredRowIndex }: InstanceProps ) => { let totalSizeOfMeasuredRows = 0; // Edge case check for when the number of items decreases while a scroll is in progress. // https://github.com/bvaughn/react-window/pull/138 if (lastMeasuredRowIndex >= rowCount) { lastMeasuredRowIndex = rowCount - 1; } if (lastMeasuredRowIndex >= 0) { const itemMetadata = rowMetadataMap[lastMeasuredRowIndex]; totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size; } const numUnmeasuredItems = rowCount - lastMeasuredRowIndex - 1; const totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedRowHeight; return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems; }; const getEstimatedTotalWidth = ( { columnCount }: Props<any>, { columnMetadataMap, estimatedColumnWidth, lastMeasuredColumnIndex, }: InstanceProps ) => { let totalSizeOfMeasuredRows = 0; // Edge case check for when the number of items decreases while a scroll is in progress. // https://github.com/bvaughn/react-window/pull/138 if (lastMeasuredColumnIndex >= columnCount) { lastMeasuredColumnIndex = columnCount - 1; } if (lastMeasuredColumnIndex >= 0) { const itemMetadata = columnMetadataMap[lastMeasuredColumnIndex]; totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size; } const numUnmeasuredItems = columnCount - lastMeasuredColumnIndex - 1; const totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedColumnWidth; return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems; }; const getItemMetadata = ( itemType: ItemType, props: Props<any>, index: number, instanceProps: InstanceProps ): ItemMetadata => { let itemMetadataMap, itemSize, lastMeasuredIndex; if (itemType === 'column') { itemMetadataMap = instanceProps.columnMetadataMap; itemSize = ((props.columnWidth: any): itemSizeGetter); lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex; } else { itemMetadataMap = instanceProps.rowMetadataMap; itemSize = ((props.rowHeight: any): itemSizeGetter); lastMeasuredIndex = instanceProps.lastMeasuredRowIndex; } if (index > lastMeasuredIndex) { let offset = 0; if (lastMeasuredIndex >= 0) { const itemMetadata = itemMetadataMap[lastMeasuredIndex]; offset = itemMetadata.offset + itemMetadata.size; } for (let i = lastMeasuredIndex + 1; i <= index; i++) { let size = itemSize(i); itemMetadataMap[i] = { offset, size, }; offset += size; } if (itemType === 'column') { instanceProps.lastMeasuredColumnIndex = index; } else { instanceProps.lastMeasuredRowIndex = index; } } return itemMetadataMap[index]; }; const findNearestItem = ( itemType: ItemType, props: Props<any>, instanceProps: InstanceProps, offset: number ) => { let itemMetadataMap, lastMeasuredIndex; if (itemType === 'column') { itemMetadataMap = instanceProps.columnMetadataMap; lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex; } else { itemMetadataMap = instanceProps.rowMetadataMap; lastMeasuredIndex = instanceProps.lastMeasuredRowIndex; } const lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0; if (lastMeasuredItemOffset >= offset) { // If we've already measured items within this range just use a binary search as it's faster. return findNearestItemBinarySearch( itemType, props, instanceProps, lastMeasuredIndex, 0, offset ); } else { // If we haven't yet measured this high, fallback to an exponential search with an inner binary search. // The exponential search avoids pre-computing sizes for the full set of items as a binary search would. // The overall complexity for this approach is O(log n). return findNearestItemExponentialSearch( itemType, props, instanceProps, Math.max(0, lastMeasuredIndex), offset ); } }; const findNearestItemBinarySearch = ( itemType: ItemType, props: Props<any>, instanceProps: InstanceProps, high: number, low: number, offset: number ): number => { while (low <= high) { const middle = low + Math.floor((high - low) / 2); const currentOffset = getItemMetadata( itemType, props, middle, instanceProps ).offset; if (currentOffset === offset) { return middle; } else if (currentOffset < offset) { low = middle + 1; } else if (currentOffset > offset) { high = middle - 1; } } if (low > 0) { return low - 1; } else { return 0; } }; const findNearestItemExponentialSearch = ( itemType: ItemType, props: Props<any>, instanceProps: InstanceProps, index: number, offset: number ): number => { const itemCount = itemType === 'column' ? props.columnCount : props.rowCount; let interval = 1; while ( index < itemCount && getItemMetadata(itemType, props, index, instanceProps).offset < offset ) { index += interval; interval *= 2; } return findNearestItemBinarySearch( itemType, props, instanceProps, Math.min(index, itemCount - 1), Math.floor(index / 2), offset ); }; const getOffsetForIndexAndAlignment = ( itemType: ItemType, props: Props<any>, index: number, align: ScrollToAlign, scrollOffset: number, instanceProps: InstanceProps, scrollbarSize: number ): number => { const size = itemType === 'column' ? props.width : props.height; const itemMetadata = getItemMetadata(itemType, props, index, instanceProps); // Get estimated total size after ItemMetadata is computed, // To ensure it reflects actual measurements instead of just estimates. const estimatedTotalSize = itemType === 'column' ? getEstimatedTotalWidth(props, instanceProps) : getEstimatedTotalHeight(props, instanceProps); const maxOffset = Math.max( 0, Math.min(estimatedTotalSize - size, itemMetadata.offset) ); const minOffset = Math.max( 0, itemMetadata.offset - size + scrollbarSize + itemMetadata.size ); if (align === 'smart') { if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) { align = 'auto'; } else { align = 'center'; } } switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': return Math.round(minOffset + (maxOffset - minOffset) / 2); case 'auto': default: if (scrollOffset >= minOffset && scrollOffset <= maxOffset) { return scrollOffset; } else if (minOffset > maxOffset) { // Because we only take into account the scrollbar size when calculating minOffset // this value can be larger than maxOffset when at the end of the list return minOffset; } else if (scrollOffset < minOffset) { return minOffset; } else { return maxOffset; } } }; const VariableSizeGrid: ComponentType<Props<$FlowFixMe>> = createGridComponent({ getColumnOffset: ( props: Props<any>, index: number, instanceProps: InstanceProps ): number => getItemMetadata('column', props, index, instanceProps).offset, getColumnStartIndexForOffset: ( props: Props<any>, scrollLeft: number, instanceProps: InstanceProps ): number => findNearestItem('column', props, instanceProps, scrollLeft), getColumnStopIndexForStartIndex: ( props: Props<any>, startIndex: number, scrollLeft: number, instanceProps: InstanceProps ): number => { const { columnCount, width } = props; const itemMetadata = getItemMetadata( 'column', props, startIndex, instanceProps ); const maxOffset = scrollLeft + width; let offset = itemMetadata.offset + itemMetadata.size; let stopIndex = startIndex; while (stopIndex < columnCount - 1 && offset < maxOffset) { stopIndex++; offset += getItemMetadata('column', props, stopIndex, instanceProps).size; } return stopIndex; }, getColumnWidth: ( props: Props<any>, index: number, instanceProps: InstanceProps ): number => instanceProps.columnMetadataMap[index].size, getEstimatedTotalHeight, getEstimatedTotalWidth, getOffsetForColumnAndAlignment: ( props: Props<any>, index: number, align: ScrollToAlign, scrollOffset: number, instanceProps: InstanceProps, scrollbarSize: number ): number => getOffsetForIndexAndAlignment( 'column', props, index, align, scrollOffset, instanceProps, scrollbarSize ), getOffsetForRowAndAlignment: ( props: Props<any>, index: number, align: ScrollToAlign, scrollOffset: number, instanceProps: InstanceProps, scrollbarSize: number ): number => getOffsetForIndexAndAlignment( 'row', props, index, align, scrollOffset, instanceProps, scrollbarSize ), getRowOffset: ( props: Props<any>, index: number, instanceProps: InstanceProps ): number => getItemMetadata('row', props, index, instanceProps).offset, getRowHeight: ( props: Props<any>, index: number, instanceProps: InstanceProps ): number => instanceProps.rowMetadataMap[index].size, getRowStartIndexForOffset: ( props: Props<any>, scrollTop: number, instanceProps: InstanceProps ): number => findNearestItem('row', props, instanceProps, scrollTop), getRowStopIndexForStartIndex: ( props: Props<any>, startIndex: number, scrollTop: number, instanceProps: InstanceProps ): number => { const { rowCount, height } = props; const itemMetadata = getItemMetadata( 'row', props, startIndex, instanceProps ); const maxOffset = scrollTop + height; let offset = itemMetadata.offset + itemMetadata.size; let stopIndex = startIndex; while (stopIndex < rowCount - 1 && offset < maxOffset) { stopIndex++; offset += getItemMetadata('row', props, stopIndex, instanceProps).size; } return stopIndex; }, initInstanceProps(props: Props<any>, instance: any): InstanceProps { const { estimatedColumnWidth, estimatedRowHeight, } = ((props: any): VariableSizeProps); const instanceProps = { columnMetadataMap: {}, estimatedColumnWidth: estimatedColumnWidth || DEFAULT_ESTIMATED_ITEM_SIZE, estimatedRowHeight: estimatedRowHeight || DEFAULT_ESTIMATED_ITEM_SIZE, lastMeasuredColumnIndex: -1, lastMeasuredRowIndex: -1, rowMetadataMap: {}, }; instance.resetAfterColumnIndex = ( columnIndex: number, shouldForceUpdate?: boolean = true ) => { instance.resetAfterIndices({ columnIndex, shouldForceUpdate }); }; instance.resetAfterRowIndex = ( rowIndex: number, shouldForceUpdate?: boolean = true ) => { instance.resetAfterIndices({ rowIndex, shouldForceUpdate }); }; instance.resetAfterIndices = ({ columnIndex, rowIndex, shouldForceUpdate = true, }: { columnIndex?: number, rowIndex?: number, shouldForceUpdate: boolean, }) => { if (typeof columnIndex === 'number') { instanceProps.lastMeasuredColumnIndex = Math.min( instanceProps.lastMeasuredColumnIndex, columnIndex - 1 ); } if (typeof rowIndex === 'number') { instanceProps.lastMeasuredRowIndex = Math.min( instanceProps.lastMeasuredRowIndex, rowIndex - 1 ); } // We could potentially optimize further by only evicting styles after this index, // But since styles are only cached while scrolling is in progress- // It seems an unnecessary optimization. // It's unlikely that resetAfterIndex() will be called while a user is scrolling. instance._getItemStyleCache(-1); if (shouldForceUpdate) { instance.forceUpdate(); } }; return instanceProps; }, shouldResetStyleCacheOnItemSizeChange: false, validateProps: ({ columnWidth, rowHeight }: Props<any>): void => { if (process.env.NODE_ENV !== 'production') { if (typeof columnWidth !== 'function') { throw Error( 'An invalid "columnWidth" prop has been specified. ' + 'Value should be a function. ' + `"${ columnWidth === null ? 'null' : typeof columnWidth }" was specified.` ); } else if (typeof rowHeight !== 'function') { throw Error( 'An invalid "rowHeight" prop has been specified. ' + 'Value should be a function. ' + `"${rowHeight === null ? 'null' : typeof rowHeight}" was specified.` ); } } }, }); export default VariableSizeGrid;
25.990196
108
0.665286
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={[]} routeTree={sidebarLearn} meta={{title: 'Something Went Wrong'}}> <MaxWidth> <Intro> <P>Something went very wrong.</P> <P>Sorry about that.</P> <P> If you’d like, please{' '} <A href="https://github.com/reactjs/react.dev/issues/new"> report a bug. </A> </P> </Intro> </MaxWidth> </Page> ); }
23.0625
70
0.552666
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 { PreconnectOptions, PreloadOptions, PreloadModuleOptions, PreinitOptions, PreinitModuleOptions, } from './ReactDOMTypes'; import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals'; const Dispatcher = ReactDOMSharedInternals.Dispatcher; import { getCrossOriginString, getCrossOriginStringAs, } from 'react-dom-bindings/src/shared/crossOriginStrings'; export function prefetchDNS(href: string) { if (__DEV__) { if (typeof href !== 'string' || !href) { console.error( 'ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.', getValueDescriptorExpectingObjectForWarning(href), ); } else if (arguments.length > 1) { const options = arguments[1]; if ( typeof options === 'object' && options.hasOwnProperty('crossOrigin') ) { console.error( 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', getValueDescriptorExpectingEnumForWarning(options), ); } else { console.error( 'ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.', getValueDescriptorExpectingEnumForWarning(options), ); } } } const dispatcher = Dispatcher.current; if (dispatcher && typeof href === 'string') { dispatcher.prefetchDNS(href); } // We don't error because preconnect needs to be resilient to being called in a variety of scopes // and the runtime may not be capable of responding. The function is optimistic and not critical // so we favor silent bailout over warning or erroring. } export function preconnect(href: string, options?: ?PreconnectOptions) { if (__DEV__) { if (typeof href !== 'string' || !href) { console.error( 'ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.', getValueDescriptorExpectingObjectForWarning(href), ); } else if (options != null && typeof options !== 'object') { console.error( 'ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.', getValueDescriptorExpectingEnumForWarning(options), ); } else if (options != null && typeof options.crossOrigin !== 'string') { console.error( 'ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.', getValueDescriptorExpectingObjectForWarning(options.crossOrigin), ); } } const dispatcher = Dispatcher.current; if (dispatcher && typeof href === 'string') { const crossOrigin = options ? getCrossOriginString(options.crossOrigin) : null; dispatcher.preconnect(href, crossOrigin); } // We don't error because preconnect needs to be resilient to being called in a variety of scopes // and the runtime may not be capable of responding. The function is optimistic and not critical // so we favor silent bailout over warning or erroring. } export function preload(href: string, options: PreloadOptions) { if (__DEV__) { let encountered = ''; if (typeof href !== 'string' || !href) { encountered += ` The \`href\` argument encountered was ${getValueDescriptorExpectingObjectForWarning( href, )}.`; } if (options == null || typeof options !== 'object') { encountered += ` The \`options\` argument encountered was ${getValueDescriptorExpectingObjectForWarning( options, )}.`; } else if (typeof options.as !== 'string' || !options.as) { encountered += ` The \`as\` option encountered was ${getValueDescriptorExpectingObjectForWarning( options.as, )}.`; } if (encountered) { console.error( 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag.%s', encountered, ); } } const dispatcher = Dispatcher.current; if ( dispatcher && typeof href === 'string' && // We check existence because we cannot enforce this function is actually called with the stated type typeof options === 'object' && options !== null && typeof options.as === 'string' ) { const as = options.as; const crossOrigin = getCrossOriginStringAs(as, options.crossOrigin); dispatcher.preload(href, as, { crossOrigin, integrity: typeof options.integrity === 'string' ? options.integrity : undefined, nonce: typeof options.nonce === 'string' ? options.nonce : undefined, type: typeof options.type === 'string' ? options.type : undefined, fetchPriority: typeof options.fetchPriority === 'string' ? options.fetchPriority : undefined, referrerPolicy: typeof options.referrerPolicy === 'string' ? options.referrerPolicy : undefined, imageSrcSet: typeof options.imageSrcSet === 'string' ? options.imageSrcSet : undefined, imageSizes: typeof options.imageSizes === 'string' ? options.imageSizes : undefined, }); } // We don't error because preload needs to be resilient to being called in a variety of scopes // and the runtime may not be capable of responding. The function is optimistic and not critical // so we favor silent bailout over warning or erroring. } export function preloadModule(href: string, options?: ?PreloadModuleOptions) { if (__DEV__) { let encountered = ''; if (typeof href !== 'string' || !href) { encountered += ` The \`href\` argument encountered was ${getValueDescriptorExpectingObjectForWarning( href, )}.`; } if (options !== undefined && typeof options !== 'object') { encountered += ` The \`options\` argument encountered was ${getValueDescriptorExpectingObjectForWarning( options, )}.`; } else if (options && 'as' in options && typeof options.as !== 'string') { encountered += ` The \`as\` option encountered was ${getValueDescriptorExpectingObjectForWarning( options.as, )}.`; } if (encountered) { console.error( 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag.%s', encountered, ); } } const dispatcher = Dispatcher.current; if (dispatcher && typeof href === 'string') { if (options) { const crossOrigin = getCrossOriginStringAs( options.as, options.crossOrigin, ); dispatcher.preloadModule(href, { as: typeof options.as === 'string' && options.as !== 'script' ? options.as : undefined, crossOrigin, integrity: typeof options.integrity === 'string' ? options.integrity : undefined, }); } else { dispatcher.preloadModule(href); } } // We don't error because preload needs to be resilient to being called in a variety of scopes // and the runtime may not be capable of responding. The function is optimistic and not critical // so we favor silent bailout over warning or erroring. } export function preinit(href: string, options: PreinitOptions) { if (__DEV__) { if (typeof href !== 'string' || !href) { console.error( 'ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.', getValueDescriptorExpectingObjectForWarning(href), ); } else if (options == null || typeof options !== 'object') { console.error( 'ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.', getValueDescriptorExpectingEnumForWarning(options), ); } else if (options.as !== 'style' && options.as !== 'script') { console.error( 'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".', getValueDescriptorExpectingEnumForWarning(options.as), ); } } const dispatcher = Dispatcher.current; if ( dispatcher && typeof href === 'string' && options && typeof options.as === 'string' ) { const as = options.as; const crossOrigin = getCrossOriginStringAs(as, options.crossOrigin); const integrity = typeof options.integrity === 'string' ? options.integrity : undefined; const fetchPriority = typeof options.fetchPriority === 'string' ? options.fetchPriority : undefined; if (as === 'style') { dispatcher.preinitStyle( href, typeof options.precedence === 'string' ? options.precedence : undefined, { crossOrigin, integrity, fetchPriority, }, ); } else if (as === 'script') { dispatcher.preinitScript(href, { crossOrigin, integrity, fetchPriority, nonce: typeof options.nonce === 'string' ? options.nonce : undefined, }); } } // We don't error because preinit needs to be resilient to being called in a variety of scopes // and the runtime may not be capable of responding. The function is optimistic and not critical // so we favor silent bailout over warning or erroring. } export function preinitModule(href: string, options?: ?PreinitModuleOptions) { if (__DEV__) { let encountered = ''; if (typeof href !== 'string' || !href) { encountered += ` The \`href\` argument encountered was ${getValueDescriptorExpectingObjectForWarning( href, )}.`; } if (options !== undefined && typeof options !== 'object') { encountered += ` The \`options\` argument encountered was ${getValueDescriptorExpectingObjectForWarning( options, )}.`; } else if (options && 'as' in options && options.as !== 'script') { encountered += ` The \`as\` option encountered was ${getValueDescriptorExpectingEnumForWarning( options.as, )}.`; } if (encountered) { console.error( 'ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s', encountered, ); } else { const as = options && typeof options.as === 'string' ? options.as : 'script'; switch (as) { case 'script': { break; } // We have an invalid as type and need to warn default: { const typeOfAs = getValueDescriptorExpectingEnumForWarning(as); console.error( 'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script"' + ' but received "%s" instead. This warning was generated for `href` "%s". In the future other' + ' module types will be supported, aligning with the import-attributes proposal. Learn more here:' + ' (https://github.com/tc39/proposal-import-attributes)', typeOfAs, href, ); } } } } const dispatcher = Dispatcher.current; if (dispatcher && typeof href === 'string') { if (typeof options === 'object' && options !== null) { if (options.as == null || options.as === 'script') { const crossOrigin = getCrossOriginStringAs( options.as, options.crossOrigin, ); dispatcher.preinitModuleScript(href, { crossOrigin, integrity: typeof options.integrity === 'string' ? options.integrity : undefined, nonce: typeof options.nonce === 'string' ? options.nonce : undefined, }); } } else if (options == null) { dispatcher.preinitModuleScript(href); } } // We don't error because preinit needs to be resilient to being called in a variety of scopes // and the runtime may not be capable of responding. The function is optimistic and not critical // so we favor silent bailout over warning or erroring. } function getValueDescriptorExpectingObjectForWarning(thing: any): string { return thing === null ? '`null`' : thing === undefined ? '`undefined`' : thing === '' ? 'an empty string' : `something with type "${typeof thing}"`; } function getValueDescriptorExpectingEnumForWarning(thing: any): string { return thing === null ? '`null`' : thing === undefined ? '`undefined`' : thing === '' ? 'an empty string' : typeof thing === 'string' ? JSON.stringify(thing) : typeof thing === 'number' ? '`' + thing + '`' : `something with type "${typeof thing}"`; }
38.696884
477
0.642521
null
'use strict'; const baseConfig = require('./config.base'); module.exports = Object.assign({}, baseConfig, { modulePathIgnorePatterns: [ ...baseConfig.modulePathIgnorePatterns, 'packages/react-devtools-extensions', 'packages/react-devtools-shared', ], setupFiles: [ ...baseConfig.setupFiles, require.resolve('./setupHostConfigs.js'), ], });
22.1875
48
0.686486
owtf
const React = window.React; const CIRCLE_SIZE = 80; class DragBox extends React.Component { state = { hasCapture: false, circleLeft: 80, circleTop: 80, }; isDragging = false; previousLeft = 0; previousTop = 0; onDown = event => { this.isDragging = true; event.target.setPointerCapture(event.pointerId); // We store the initial coordinates to be able to calculate the changes // later on. this.extractPositionDelta(event); }; onMove = event => { if (!this.isDragging) { return; } const {left, top} = this.extractPositionDelta(event); this.setState(({circleLeft, circleTop}) => ({ circleLeft: circleLeft + left, circleTop: circleTop + top, })); }; onUp = event => (this.isDragging = false); onGotCapture = event => this.setState({hasCapture: true}); onLostCapture = event => this.setState({hasCapture: false}); extractPositionDelta = event => { const left = event.pageX; const top = event.pageY; const delta = { left: left - this.previousLeft, top: top - this.previousTop, }; this.previousLeft = left; this.previousTop = top; return delta; }; render() { const {hasCapture, circleLeft, circleTop} = this.state; const boxStyle = { border: '1px solid #d9d9d9', margin: '10px 0 20px', minHeight: 400, width: '100%', position: 'relative', }; const circleStyle = { width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, position: 'absolute', left: circleLeft, top: circleTop, backgroundColor: hasCapture ? 'blue' : 'green', touchAction: 'none', }; return ( <div style={boxStyle}> <div style={circleStyle} onPointerDown={this.onDown} onPointerMove={this.onMove} onPointerUp={this.onUp} onPointerCancel={this.onUp} onGotPointerCapture={this.onGotCapture} onLostPointerCapture={this.onLostCapture} /> </div> ); } } export default DragBox;
22.131868
75
0.602662
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 { ReactServerContext, ServerContextJSONValue, } from 'shared/ReactTypes'; import {REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED} from 'shared/ReactSymbols'; import {isPrimaryRenderer} from './ReactFlightServerConfig'; let rendererSigil; if (__DEV__) { // Use this to detect multiple renderers using the same context rendererSigil = {}; } // Used to store the parent path of all context overrides in a shared linked list. // Forming a reverse tree. type ContextNode<T: ServerContextJSONValue> = { parent: null | ContextNode<any>, depth: number, // Short hand to compute the depth of the tree at this node. context: ReactServerContext<T>, parentValue: T, value: T, }; // The structure of a context snapshot is an implementation of this file. // Currently, it's implemented as tracking the current active node. export opaque type ContextSnapshot = null | ContextNode<any>; export const rootContextSnapshot: ContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. // This global (actually thread local) state represents what state all those "current", // fields are currently in. let currentActiveSnapshot: ContextSnapshot = null; function popNode(prev: ContextNode<any>): void { if (isPrimaryRenderer) { prev.context._currentValue = prev.parentValue; } else { prev.context._currentValue2 = prev.parentValue; } } function pushNode(next: ContextNode<any>): void { if (isPrimaryRenderer) { next.context._currentValue = next.value; } else { next.context._currentValue2 = next.value; } } function popToNearestCommonAncestor( prev: ContextNode<any>, next: ContextNode<any>, ): void { if (prev === next) { // We've found a shared ancestor. We don't need to pop nor reapply this one or anything above. } else { popNode(prev); const parentPrev = prev.parent; const parentNext = next.parent; if (parentPrev === null) { if (parentNext !== null) { throw new Error( 'The stacks must reach the root at the same time. This is a bug in React.', ); } } else { if (parentNext === null) { throw new Error( 'The stacks must reach the root at the same time. This is a bug in React.', ); } popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. pushNode(next); } } } function popAllPrevious(prev: ContextNode<any>): void { popNode(prev); const parentPrev = prev.parent; if (parentPrev !== null) { popAllPrevious(parentPrev); } } function pushAllNext(next: ContextNode<any>): void { const parentNext = next.parent; if (parentNext !== null) { pushAllNext(parentNext); } pushNode(next); } function popPreviousToCommonLevel( prev: ContextNode<any>, next: ContextNode<any>, ): void { popNode(prev); const parentPrev = prev.parent; if (parentPrev === null) { throw new Error( 'The depth must equal at least at zero before reaching the root. This is a bug in React.', ); } if (parentPrev.depth === next.depth) { // We found the same level. Now we just need to find a shared ancestor. popToNearestCommonAncestor(parentPrev, next); } else { // We must still be deeper. popPreviousToCommonLevel(parentPrev, next); } } function popNextToCommonLevel( prev: ContextNode<any>, next: ContextNode<any>, ): void { const parentNext = next.parent; if (parentNext === null) { throw new Error( 'The depth must equal at least at zero before reaching the root. This is a bug in React.', ); } if (prev.depth === parentNext.depth) { // We found the same level. Now we just need to find a shared ancestor. popToNearestCommonAncestor(prev, parentNext); } else { // We must still be deeper. popNextToCommonLevel(prev, parentNext); } pushNode(next); } // Perform context switching to the new snapshot. // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by // updating all the context's current values. That way reads, always just read the current value. // At the cost of updating contexts even if they're never read by this subtree. export function switchContext(newSnapshot: ContextSnapshot): void { // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. // We also need to update any new contexts that are now on the stack with the deepest value. // The easiest way to update new contexts is to just reapply them in reverse order from the // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack // for that. Therefore this algorithm is recursive. // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. // 3) Then we reapply new contexts on the way back up the stack. const prev = currentActiveSnapshot; const next = newSnapshot; if (prev !== next) { if (prev === null) { // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. pushAllNext(next); } else if (next === null) { popAllPrevious(prev); } else if (prev.depth === next.depth) { popToNearestCommonAncestor(prev, next); } else if (prev.depth > next.depth) { popPreviousToCommonLevel(prev, next); } else { popNextToCommonLevel(prev, next); } currentActiveSnapshot = next; } } export function pushProvider<T: ServerContextJSONValue>( context: ReactServerContext<T>, nextValue: T, ): ContextSnapshot { let prevValue; if (isPrimaryRenderer) { prevValue = context._currentValue; context._currentValue = nextValue; if (__DEV__) { if ( context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer = rendererSigil; } } else { prevValue = context._currentValue2; context._currentValue2 = nextValue; if (__DEV__) { if ( context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil ) { console.error( 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.', ); } context._currentRenderer2 = rendererSigil; } } const prevNode = currentActiveSnapshot; const newNode: ContextNode<T> = { parent: prevNode, depth: prevNode === null ? 0 : prevNode.depth + 1, context: context, parentValue: prevValue, value: nextValue, }; currentActiveSnapshot = newNode; return newNode; } export function popProvider(): ContextSnapshot { const prevSnapshot = currentActiveSnapshot; if (prevSnapshot === null) { throw new Error( 'Tried to pop a Context at the root of the app. This is a bug in React.', ); } if (isPrimaryRenderer) { const value = prevSnapshot.parentValue; if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; } else { prevSnapshot.context._currentValue = value; } } else { const value = prevSnapshot.parentValue; if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue; } else { prevSnapshot.context._currentValue2 = value; } } return (currentActiveSnapshot = prevSnapshot.parent); } export function getActiveContext(): ContextSnapshot { return currentActiveSnapshot; } export function readContext<T>(context: ReactServerContext<T>): T { const value = isPrimaryRenderer ? context._currentValue : context._currentValue2; return value; }
30.118519
99
0.681943
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const stream = require('stream'); const shouldIgnoreConsoleError = require('../../../../../scripts/jest/shouldIgnoreConsoleError'); module.exports = function (initModules) { let ReactDOM; let ReactDOMServer; let act; function resetModules() { ({ReactDOM, ReactDOMServer} = initModules()); act = require('internal-test-utils').act; } function shouldUseDocument(reactElement) { // Used for whole document tests. return reactElement && reactElement.type === 'html'; } function getContainerFromMarkup(reactElement, markup) { if (shouldUseDocument(reactElement)) { const doc = document.implementation.createHTMLDocument(''); doc.open(); doc.write( markup || '<!doctype html><html><meta charset=utf-8><title>test doc</title>', ); doc.close(); return doc; } else { const container = document.createElement('div'); container.innerHTML = markup; return container; } } // Helper functions for rendering tests // ==================================== // promisified version of ReactDOM.render() async function asyncReactDOMRender(reactElement, domElement, forceHydrate) { if (forceHydrate) { await act(() => { ReactDOM.hydrate(reactElement, domElement); }); } else { await act(() => { ReactDOM.render(reactElement, domElement); }); } } // performs fn asynchronously and expects count errors logged to console.error. // will fail the test if the count of errors logged is not equal to count. async function expectErrors(fn, count) { if (console.error.mockClear) { console.error.mockClear(); } else { // TODO: Rewrite tests that use this helper to enumerate expected errors. // This will enable the helper to use the .toErrorDev() matcher instead of spying. spyOnDev(console, 'error').mockImplementation(() => {}); } const result = await fn(); if ( console.error.mock && console.error.mock.calls && console.error.mock.calls.length !== 0 ) { const filteredWarnings = []; for (let i = 0; i < console.error.mock.calls.length; i++) { const args = console.error.mock.calls[i]; const [format, ...rest] = args; if (!shouldIgnoreConsoleError(format, rest)) { filteredWarnings.push(args); } } if (filteredWarnings.length !== count) { console.log( `We expected ${count} warning(s), but saw ${filteredWarnings.length} warning(s).`, ); if (filteredWarnings.length > 0) { console.log(`We saw these warnings:`); for (let i = 0; i < filteredWarnings.length; i++) { console.log(...filteredWarnings[i]); } } if (__DEV__) { expect(console.error).toHaveBeenCalledTimes(count); } } } return result; } // renders the reactElement into domElement, and expects a certain number of errors. // returns a Promise that resolves when the render is complete. function renderIntoDom( reactElement, domElement, forceHydrate, errorCount = 0, ) { return expectErrors(async () => { await asyncReactDOMRender(reactElement, domElement, forceHydrate); return domElement.firstChild; }, errorCount); } async function renderIntoString(reactElement, errorCount = 0) { return await expectErrors( () => new Promise(resolve => resolve(ReactDOMServer.renderToString(reactElement)), ), errorCount, ); } // Renders text using SSR and then stuffs it into a DOM node; returns the DOM // element that corresponds with the reactElement. // Does not render on client or perform client-side revival. async function serverRender(reactElement, errorCount = 0) { const markup = await renderIntoString(reactElement, errorCount); return getContainerFromMarkup(reactElement, markup).firstChild; } // this just drains a readable piped into it to a string, which can be accessed // via .buffer. class DrainWritable extends stream.Writable { constructor(options) { super(options); this.buffer = ''; } _write(chunk, encoding, cb) { this.buffer += chunk; cb(); } } async function renderIntoStream(reactElement, errorCount = 0) { return await expectErrors( () => new Promise((resolve, reject) => { const writable = new DrainWritable(); const s = ReactDOMServer.renderToPipeableStream(reactElement, { onShellError(e) { reject(e); }, }); s.pipe(writable); writable.on('finish', () => resolve(writable.buffer)); }), errorCount, ); } // Renders text using node stream SSR and then stuffs it into a DOM node; // returns the DOM element that corresponds with the reactElement. // Does not render on client or perform client-side revival. async function streamRender(reactElement, errorCount = 0) { const markup = await renderIntoStream(reactElement, errorCount); let firstNode = getContainerFromMarkup(reactElement, markup).firstChild; if (firstNode && firstNode.nodeType === Node.DOCUMENT_TYPE_NODE) { // Skip document type nodes. firstNode = firstNode.nextSibling; } return firstNode; } const clientCleanRender = (element, errorCount = 0) => { if (shouldUseDocument(element)) { // Documents can't be rendered from scratch. return clientRenderOnServerString(element, errorCount); } const container = document.createElement('div'); return renderIntoDom(element, container, false, errorCount); }; const clientRenderOnServerString = async (element, errorCount = 0) => { const markup = await renderIntoString(element, errorCount); resetModules(); const container = getContainerFromMarkup(element, markup); let serverNode = container.firstChild; const firstClientNode = await renderIntoDom( element, container, true, errorCount, ); let clientNode = firstClientNode; // Make sure all top level nodes match up while (serverNode || clientNode) { expect(serverNode != null).toBe(true); expect(clientNode != null).toBe(true); expect(clientNode.nodeType).toBe(serverNode.nodeType); // Assert that the DOM element hasn't been replaced. // Note that we cannot use expect(serverNode).toBe(clientNode) because // of jest bug #1772. expect(serverNode === clientNode).toBe(true); serverNode = serverNode.nextSibling; clientNode = clientNode.nextSibling; } return firstClientNode; }; function BadMarkupExpected() {} const clientRenderOnBadMarkup = async (element, errorCount = 0) => { // First we render the top of bad mark up. const container = getContainerFromMarkup( element, shouldUseDocument(element) ? '<html><body><div id="badIdWhichWillCauseMismatch" /></body></html>' : '<div id="badIdWhichWillCauseMismatch"></div>', ); await renderIntoDom(element, container, true, errorCount + 1); // This gives us the resulting text content. const hydratedTextContent = container.lastChild && container.lastChild.textContent; // Next we render the element into a clean DOM node client side. let cleanContainer; if (shouldUseDocument(element)) { // We can't render into a document during a clean render, // so instead, we'll render the children into the document element. cleanContainer = getContainerFromMarkup( element, '<html></html>', ).documentElement; element = element.props.children; } else { cleanContainer = document.createElement('div'); } await asyncReactDOMRender(element, cleanContainer, true); // This gives us the expected text content. const cleanTextContent = (cleanContainer.lastChild && cleanContainer.lastChild.textContent) || ''; // The only guarantee is that text content has been patched up if needed. expect(hydratedTextContent).toBe(cleanTextContent); // Abort any further expects. All bets are off at this point. throw new BadMarkupExpected(); }; // runs a DOM rendering test as four different tests, with four different rendering // scenarios: // -- render to string on server // -- render on client without any server markup "clean client render" // -- render on client on top of good server-generated string markup // -- render on client on top of bad server-generated markup // // testFn is a test that has one arg, which is a render function. the render // function takes in a ReactElement and an optional expected error count and // returns a promise of a DOM Element. // // You should only perform tests that examine the DOM of the results of // render; you should not depend on the interactivity of the returned DOM element, // as that will not work in the server string scenario. function itRenders(desc, testFn) { it(`renders ${desc} with server string render`, () => testFn(serverRender)); it(`renders ${desc} with server stream render`, () => testFn(streamRender)); itClientRenders(desc, testFn); } // run testFn in three different rendering scenarios: // -- render on client without any server markup "clean client render" // -- render on client on top of good server-generated string markup // -- render on client on top of bad server-generated markup // // testFn is a test that has one arg, which is a render function. the render // function takes in a ReactElement and an optional expected error count and // returns a promise of a DOM Element. // // Since all of the renders in this function are on the client, you can test interactivity, // unlike with itRenders. function itClientRenders(desc, testFn) { it(`renders ${desc} with clean client render`, () => testFn(clientCleanRender)); it(`renders ${desc} with client render on top of good server markup`, () => testFn(clientRenderOnServerString)); it(`renders ${desc} with client render on top of bad server markup`, async () => { try { await testFn(clientRenderOnBadMarkup); } catch (x) { // We expect this to trigger the BadMarkupExpected rejection. if (!(x instanceof BadMarkupExpected)) { // If not, rethrow. throw x; } } }); } function itThrows(desc, testFn, partialMessage) { it(`throws ${desc}`, () => { return testFn().then( () => expect(false).toBe('The promise resolved and should not have.'), err => { expect(err).toBeInstanceOf(Error); expect(err.message).toContain(partialMessage); }, ); }); } function itThrowsWhenRendering(desc, testFn, partialMessage) { itThrows( `when rendering ${desc} with server string render`, () => testFn(serverRender), partialMessage, ); itThrows( `when rendering ${desc} with clean client render`, () => testFn(clientCleanRender), partialMessage, ); // we subtract one from the warning count here because the throw means that it won't // get the usual markup mismatch warning. itThrows( `when rendering ${desc} with client render on top of bad server markup`, () => testFn((element, warningCount = 0) => clientRenderOnBadMarkup(element, warningCount - 1), ), partialMessage, ); } // renders serverElement to a string, sticks it into a DOM element, and then // tries to render clientElement on top of it. shouldMatch is a boolean // telling whether we should expect the markup to match or not. async function testMarkupMatch(serverElement, clientElement, shouldMatch) { const domElement = await serverRender(serverElement); resetModules(); return renderIntoDom( clientElement, domElement.parentNode, true, shouldMatch ? 0 : 1, ); } // expects that rendering clientElement on top of a server-rendered // serverElement does NOT raise a markup mismatch warning. function expectMarkupMatch(serverElement, clientElement) { return testMarkupMatch(serverElement, clientElement, true); } // expects that rendering clientElement on top of a server-rendered // serverElement DOES raise a markup mismatch warning. function expectMarkupMismatch(serverElement, clientElement) { return testMarkupMatch(serverElement, clientElement, false); } return { resetModules, expectMarkupMismatch, expectMarkupMatch, itRenders, itClientRenders, itThrowsWhenRendering, asyncReactDOMRender, serverRender, clientCleanRender, clientRenderOnBadMarkup, clientRenderOnServerString, renderIntoDom, streamRender, }; };
32.771795
97
0.659301