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
'use strict'; const Git = require('nodegit'); const rimraf = require('rimraf'); const ncp = require('ncp').ncp; const {existsSync} = require('fs'); const exec = require('child_process').exec; const {join} = require('path'); const reactUrl = 'https://github.com/facebook/react.git'; function cleanDir() { return new Promise(_resolve => rimraf('remote-repo', _resolve)); } function executeCommand(command) { return new Promise(_resolve => exec(command, error => { if (!error) { _resolve(); } else { console.error(error); process.exit(1); } }) ); } function asyncCopyTo(from, to) { return new Promise(_resolve => { ncp(from, to, error => { if (error) { console.error(error); process.exit(1); } _resolve(); }); }); } function getDefaultReactPath() { return join(__dirname, 'remote-repo'); } async function buildBenchmark(reactPath = getDefaultReactPath(), benchmark) { // get the build.js from the benchmark directory and execute it await require(join(__dirname, 'benchmarks', benchmark, 'build.js'))( reactPath, asyncCopyTo ); } async function getMergeBaseFromLocalGitRepo(localRepo) { const repo = await Git.Repository.open(localRepo); return await Git.Merge.base( repo, await repo.getHeadCommit(), await repo.getBranchCommit('main') ); } async function buildBenchmarkBundlesFromGitRepo( commitId, skipBuild, url = reactUrl, clean ) { let repo; const remoteRepoDir = getDefaultReactPath(); if (!skipBuild) { if (clean) { //clear remote-repo folder await cleanDir(remoteRepoDir); } // check if remote-repo directory already exists if (existsSync(remoteRepoDir)) { repo = await Git.Repository.open(remoteRepoDir); // fetch all the latest remote changes await repo.fetchAll(); } else { // if not, clone the repo to remote-repo folder repo = await Git.Clone(url, remoteRepoDir); } let commit = await repo.getBranchCommit('main'); // reset hard to this remote head await Git.Reset.reset(repo, commit, Git.Reset.TYPE.HARD); // then we checkout the latest main head await repo.checkoutBranch('main'); // make sure we pull in the latest changes await repo.mergeBranches('main', 'origin/main'); // then we check if we need to move the HEAD to the merge base if (commitId && commitId !== 'main') { // as the commitId probably came from our local repo // we use it to lookup the right commit in our remote repo commit = await Git.Commit.lookup(repo, commitId); // then we checkout the merge base await Git.Checkout.tree(repo, commit); } await buildReactBundles(); } } async function buildReactBundles(reactPath = getDefaultReactPath(), skipBuild) { if (!skipBuild) { await executeCommand( `cd ${reactPath} && yarn && yarn build react/index,react-dom/index --type=UMD_PROD` ); } } // if run directly via CLI if (require.main === module) { buildBenchmarkBundlesFromGitRepo(); } module.exports = { buildReactBundles, buildBenchmark, buildBenchmarkBundlesFromGitRepo, getMergeBaseFromLocalGitRepo, };
25.162602
89
0.658999
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/ReactTestRenderer';
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. * * @flow */ import type {ReactContext, ReactProviderType} from 'shared/ReactTypes'; import type { Fiber, ContextDependency, Dependencies, } from './ReactInternalTypes'; import type {StackCursor} from './ReactFiberStack'; import type {Lanes} from './ReactFiberLane'; import type {SharedQueue} from './ReactFiberClassUpdateQueue'; import type {TransitionStatus} from './ReactFiberConfig'; import type {Hook} from './ReactFiberHooks'; import {isPrimaryRenderer} from './ReactFiberConfig'; import {createCursor, push, pop} from './ReactFiberStack'; import { ContextProvider, ClassComponent, DehydratedFragment, } from './ReactWorkTags'; import { NoLanes, isSubsetOfLanes, includesSomeLane, mergeLanes, pickArbitraryLane, } from './ReactFiberLane'; import { NoFlags, DidPropagateContext, NeedsPropagation, } from './ReactFiberFlags'; import is from 'shared/objectIs'; import {createUpdate, ForceUpdate} from './ReactFiberClassUpdateQueue'; import {markWorkInProgressReceivedUpdate} from './ReactFiberBeginWork'; import { enableLazyContextPropagation, enableServerContext, enableFormActions, enableAsyncActions, } from 'shared/ReactFeatureFlags'; import {REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED} from 'shared/ReactSymbols'; import { getHostTransitionProvider, HostTransitionContext, } from './ReactFiberHostContext'; const valueCursor: StackCursor<mixed> = createCursor(null); let rendererCursorDEV: StackCursor<Object | null>; if (__DEV__) { rendererCursorDEV = createCursor(null); } let renderer2CursorDEV: StackCursor<Object | null>; if (__DEV__) { renderer2CursorDEV = createCursor(null); } let rendererSigil; if (__DEV__) { // Use this to detect multiple renderers using the same context rendererSigil = {}; } let currentlyRenderingFiber: Fiber | null = null; let lastContextDependency: ContextDependency<mixed> | null = null; let lastFullyObservedContext: ReactContext<any> | null = null; let isDisallowedContextReadInDEV: boolean = false; export function resetContextDependencies(): void { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastFullyObservedContext = null; if (__DEV__) { isDisallowedContextReadInDEV = false; } } export function enterDisallowedContextReadInDEV(): void { if (__DEV__) { isDisallowedContextReadInDEV = true; } } export function exitDisallowedContextReadInDEV(): void { if (__DEV__) { isDisallowedContextReadInDEV = false; } } export function pushProvider<T>( providerFiber: Fiber, context: ReactContext<T>, nextValue: T, ): void { if (isPrimaryRenderer) { push(valueCursor, context._currentValue, providerFiber); context._currentValue = nextValue; if (__DEV__) { push(rendererCursorDEV, context._currentRenderer, providerFiber); 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 { push(valueCursor, context._currentValue2, providerFiber); context._currentValue2 = nextValue; if (__DEV__) { push(renderer2CursorDEV, context._currentRenderer2, providerFiber); 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; } } } export function popProvider( context: ReactContext<any>, providerFiber: Fiber, ): void { const currentValue = valueCursor.current; if (isPrimaryRenderer) { if ( enableServerContext && currentValue === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED ) { context._currentValue = context._defaultValue; } else { context._currentValue = currentValue; } if (__DEV__) { const currentRenderer = rendererCursorDEV.current; pop(rendererCursorDEV, providerFiber); context._currentRenderer = currentRenderer; } } else { if ( enableServerContext && currentValue === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED ) { context._currentValue2 = context._defaultValue; } else { context._currentValue2 = currentValue; } if (__DEV__) { const currentRenderer2 = renderer2CursorDEV.current; pop(renderer2CursorDEV, providerFiber); context._currentRenderer2 = currentRenderer2; } } pop(valueCursor, providerFiber); } export function scheduleContextWorkOnParentPath( parent: Fiber | null, renderLanes: Lanes, propagationRoot: Fiber, ) { // Update the child lanes of all the ancestors, including the alternates. let node = parent; while (node !== null) { const alternate = node.alternate; if (!isSubsetOfLanes(node.childLanes, renderLanes)) { node.childLanes = mergeLanes(node.childLanes, renderLanes); if (alternate !== null) { alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); } } else if ( alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes) ) { alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); } else { // Neither alternate was updated. // Normally, this would mean that the rest of the // ancestor path already has sufficient priority. // However, this is not necessarily true inside offscreen // or fallback trees because childLanes may be inconsistent // with the surroundings. This is why we continue the loop. } if (node === propagationRoot) { break; } node = node.return; } if (__DEV__) { if (node !== propagationRoot) { console.error( 'Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); } } } export function propagateContextChange<T>( workInProgress: Fiber, context: ReactContext<T>, renderLanes: Lanes, ): void { if (enableLazyContextPropagation) { // TODO: This path is only used by Cache components. Update // lazilyPropagateParentContextChanges to look for Cache components so they // can take advantage of lazy propagation. const forcePropagateEntireTree = true; propagateContextChanges( workInProgress, [context], renderLanes, forcePropagateEntireTree, ); } else { propagateContextChange_eager(workInProgress, context, renderLanes); } } function propagateContextChange_eager<T>( workInProgress: Fiber, context: ReactContext<T>, renderLanes: Lanes, ): void { // Only used by eager implementation if (enableLazyContextPropagation) { return; } let fiber = workInProgress.child; if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } while (fiber !== null) { let nextFiber; // Visit this fiber. const list = fiber.dependencies; if (list !== null) { nextFiber = fiber.child; let dependency = list.firstContext; while (dependency !== null) { // Check if the context matches. if (dependency.context === context) { // Match! Schedule an update on this fiber. if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. const lane = pickArbitraryLane(renderLanes); const update = createUpdate(lane); update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. // Inlined `enqueueUpdate` to remove interleaved update check const updateQueue = fiber.updateQueue; if (updateQueue === null) { // Only occurs if the fiber has been unmounted. } else { const sharedQueue: SharedQueue<any> = (updateQueue: any).shared; const pending = sharedQueue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } sharedQueue.pending = update; } } fiber.lanes = mergeLanes(fiber.lanes, renderLanes); const alternate = fiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } scheduleContextWorkOnParentPath( fiber.return, renderLanes, workInProgress, ); // Mark the updated lanes on the list, too. list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the // dependency list. break; } dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { // Don't scan deeper if this is a matching provider nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if (fiber.tag === DehydratedFragment) { // If a dehydrated suspense boundary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is // mark it as having updates. const parentSuspense = fiber.return; if (parentSuspense === null) { throw new Error( 'We just came from a parent so we must have had a parent. This is a bug in React.', ); } parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); const alternate = parentSuspense.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childLanes on // this fiber to indicate that a context has changed. scheduleContextWorkOnParentPath( parentSuspense, renderLanes, workInProgress, ); nextFiber = fiber.sibling; } else { // Traverse down. nextFiber = fiber.child; } if (nextFiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. nextFiber.return = fiber; } else { // No child. Traverse to next sibling. nextFiber = fiber; while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } const sibling = nextFiber.sibling; if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; } // No more siblings. Traverse up. nextFiber = nextFiber.return; } } fiber = nextFiber; } } function propagateContextChanges<T>( workInProgress: Fiber, contexts: Array<any>, renderLanes: Lanes, forcePropagateEntireTree: boolean, ): void { // Only used by lazy implementation if (!enableLazyContextPropagation) { return; } let fiber = workInProgress.child; if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } while (fiber !== null) { let nextFiber; // Visit this fiber. const list = fiber.dependencies; if (list !== null) { nextFiber = fiber.child; let dep = list.firstContext; findChangedDep: while (dep !== null) { // Assigning these to constants to help Flow const dependency = dep; const consumer = fiber; findContext: for (let i = 0; i < contexts.length; i++) { const context: ReactContext<T> = contexts[i]; // Check if the context matches. // TODO: Compare selected values to bail out early. if (dependency.context === context) { // Match! Schedule an update on this fiber. // In the lazy implementation, don't mark a dirty flag on the // dependency itself. Not all changes are propagated, so we can't // rely on the propagation function alone to determine whether // something has changed; the consumer will check. In the future, we // could add back a dirty flag as an optimization to avoid double // checking, but until we have selectors it's not really worth // the trouble. consumer.lanes = mergeLanes(consumer.lanes, renderLanes); const alternate = consumer.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } scheduleContextWorkOnParentPath( consumer.return, renderLanes, workInProgress, ); if (!forcePropagateEntireTree) { // During lazy propagation, when we find a match, we can defer // propagating changes to the children, because we're going to // visit them during render. We should continue propagating the // siblings, though nextFiber = null; } // Since we already found a match, we can stop traversing the // dependency list. break findChangedDep; } } dep = dependency.next; } } else if (fiber.tag === DehydratedFragment) { // If a dehydrated suspense boundary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is // mark it as having updates. const parentSuspense = fiber.return; if (parentSuspense === null) { throw new Error( 'We just came from a parent so we must have had a parent. This is a bug in React.', ); } parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); const alternate = parentSuspense.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childLanes on // this fiber to indicate that a context has changed. scheduleContextWorkOnParentPath( parentSuspense, renderLanes, workInProgress, ); nextFiber = null; } else { // Traverse down. nextFiber = fiber.child; } if (nextFiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. nextFiber.return = fiber; } else { // No child. Traverse to next sibling. nextFiber = fiber; while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } const sibling = nextFiber.sibling; if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; } // No more siblings. Traverse up. nextFiber = nextFiber.return; } } fiber = nextFiber; } } export function lazilyPropagateParentContextChanges( current: Fiber, workInProgress: Fiber, renderLanes: Lanes, ) { const forcePropagateEntireTree = false; propagateParentContextChanges( current, workInProgress, renderLanes, forcePropagateEntireTree, ); } // Used for propagating a deferred tree (Suspense, Offscreen). We must propagate // to the entire subtree, because we won't revisit it until after the current // render has completed, at which point we'll have lost track of which providers // have changed. export function propagateParentContextChangesToDeferredTree( current: Fiber, workInProgress: Fiber, renderLanes: Lanes, ) { const forcePropagateEntireTree = true; propagateParentContextChanges( current, workInProgress, renderLanes, forcePropagateEntireTree, ); } function propagateParentContextChanges( current: Fiber, workInProgress: Fiber, renderLanes: Lanes, forcePropagateEntireTree: boolean, ) { if (!enableLazyContextPropagation) { return; } // Collect all the parent providers that changed. Since this is usually small // number, we use an Array instead of Set. let contexts = null; let parent: null | Fiber = workInProgress; let isInsidePropagationBailout = false; while (parent !== null) { if (!isInsidePropagationBailout) { if ((parent.flags & NeedsPropagation) !== NoFlags) { isInsidePropagationBailout = true; } else if ((parent.flags & DidPropagateContext) !== NoFlags) { break; } } if (parent.tag === ContextProvider) { const currentParent = parent.alternate; if (currentParent === null) { throw new Error('Should have a current fiber. This is a bug in React.'); } const oldProps = currentParent.memoizedProps; if (oldProps !== null) { const providerType: ReactProviderType<any> = parent.type; const context: ReactContext<any> = providerType._context; const newProps = parent.pendingProps; const newValue = newProps.value; const oldValue = oldProps.value; if (!is(newValue, oldValue)) { if (contexts !== null) { contexts.push(context); } else { contexts = [context]; } } } } else if ( enableFormActions && enableAsyncActions && parent === getHostTransitionProvider() ) { // During a host transition, a host component can act like a context // provider. E.g. in React DOM, this would be a <form />. const currentParent = parent.alternate; if (currentParent === null) { throw new Error('Should have a current fiber. This is a bug in React.'); } const oldStateHook: Hook = currentParent.memoizedState; const oldState: TransitionStatus = oldStateHook.memoizedState; const newStateHook: Hook = parent.memoizedState; const newState: TransitionStatus = newStateHook.memoizedState; // This uses regular equality instead of Object.is because we assume that // host transition state doesn't include NaN as a valid type. if (oldState !== newState) { if (contexts !== null) { contexts.push(HostTransitionContext); } else { contexts = [HostTransitionContext]; } } } parent = parent.return; } if (contexts !== null) { // If there were any changed providers, search through the children and // propagate their changes. propagateContextChanges( workInProgress, contexts, renderLanes, forcePropagateEntireTree, ); } // This is an optimization so that we only propagate once per subtree. If a // deeply nested child bails out, and it calls this propagation function, it // uses this flag to know that the remaining ancestor providers have already // been propagated. // // NOTE: This optimization is only necessary because we sometimes enter the // begin phase of nodes that don't have any work scheduled on them — // specifically, the siblings of a node that _does_ have scheduled work. The // siblings will bail out and call this function again, even though we already // propagated content changes to it and its subtree. So we use this flag to // mark that the parent providers already propagated. // // Unfortunately, though, we need to ignore this flag when we're inside a // tree whose context propagation was deferred — that's what the // `NeedsPropagation` flag is for. // // If we could instead bail out before entering the siblings' begin phase, // then we could remove both `DidPropagateContext` and `NeedsPropagation`. // Consider this as part of the next refactor to the fiber tree structure. workInProgress.flags |= DidPropagateContext; } export function checkIfContextChanged( currentDependencies: Dependencies, ): boolean { if (!enableLazyContextPropagation) { return false; } // Iterate over the current dependencies to see if something changed. This // only gets called if props and state has already bailed out, so it's a // relatively uncommon path, except at the root of a changed subtree. // Alternatively, we could move these comparisons into `readContext`, but // that's a much hotter path, so I think this is an appropriate trade off. let dependency = currentDependencies.firstContext; while (dependency !== null) { const context = dependency.context; const newValue = isPrimaryRenderer ? context._currentValue : context._currentValue2; const oldValue = dependency.memoizedValue; if (!is(newValue, oldValue)) { return true; } dependency = dependency.next; } return false; } export function prepareToReadContext( workInProgress: Fiber, renderLanes: Lanes, ): void { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastFullyObservedContext = null; const dependencies = workInProgress.dependencies; if (dependencies !== null) { if (enableLazyContextPropagation) { // Reset the work-in-progress list dependencies.firstContext = null; } else { const firstContext = dependencies.firstContext; if (firstContext !== null) { if (includesSomeLane(dependencies.lanes, renderLanes)) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); } // Reset the work-in-progress list dependencies.firstContext = null; } } } } export function readContext<T>(context: ReactContext<T>): T { if (__DEV__) { // This warning would fire if you read context inside a Hook like useMemo. // Unlike the class check below, it's not enforced in production for perf. if (isDisallowedContextReadInDEV) { console.error( 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().', ); } } return readContextForConsumer(currentlyRenderingFiber, context); } export function readContextDuringReconcilation<T>( consumer: Fiber, context: ReactContext<T>, renderLanes: Lanes, ): T { if (currentlyRenderingFiber === null) { prepareToReadContext(consumer, renderLanes); } return readContextForConsumer(consumer, context); } function readContextForConsumer<T>( consumer: Fiber | null, context: ReactContext<T>, ): T { const value = isPrimaryRenderer ? context._currentValue : context._currentValue2; if (lastFullyObservedContext === context) { // Nothing to do. We already observe everything in this context. } else { const contextItem = { context: ((context: any): ReactContext<mixed>), memoizedValue: value, next: null, }; if (lastContextDependency === null) { if (consumer === null) { throw new Error( 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().', ); } // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; consumer.dependencies = { lanes: NoLanes, firstContext: contextItem, }; if (enableLazyContextPropagation) { consumer.flags |= NeedsPropagation; } } else { // Append a new context item. lastContextDependency = lastContextDependency.next = contextItem; } } return value; }
31.469987
95
0.649805
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 {Thenable, Wakeable} from 'shared/ReactTypes'; 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; type Module = any; type ModuleLoaderFunction = () => Thenable<Module>; // This is intentionally a module-level Map, rather than a React-managed one. // Otherwise, refreshing the inspected element cache would also clear this cache. // Modules are static anyway. const moduleLoaderFunctionToModuleMap: Map<ModuleLoaderFunction, Module> = 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; } } // TODO Flow type export function loadModule(moduleLoaderFunction: ModuleLoaderFunction): Module { let record = moduleLoaderFunctionToModuleMap.get(moduleLoaderFunction); if (__DEBUG__) { console.log( `[dynamicImportCache] loadModule("${moduleLoaderFunction.name}")`, ); } if (!record) { const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { then(callback: () => mixed) { callbacks.add(callback); }, // Optional property used by Timeline: displayName: `Loading module "${moduleLoaderFunction.name}"`, }; const wake = () => { if (timeoutID) { clearTimeout(timeoutID); timeoutID = null; } // This assumes they won't throw. callbacks.forEach(callback => callback()); callbacks.clear(); }; const newRecord: Record<Module> = (record = { status: Pending, value: wakeable, }); let didTimeout = false; moduleLoaderFunction().then( module => { if (__DEBUG__) { console.log( `[dynamicImportCache] loadModule("${moduleLoaderFunction.name}") then()`, ); } if (didTimeout) { return; } const resolvedRecord = ((newRecord: any): ResolvedRecord<Module>); resolvedRecord.status = Resolved; resolvedRecord.value = module; wake(); }, error => { if (__DEBUG__) { console.log( `[dynamicImportCache] loadModule("${moduleLoaderFunction.name}") catch()`, ); } if (didTimeout) { return; } console.log(error); const thrownRecord = ((newRecord: any): RejectedRecord); thrownRecord.status = Rejected; thrownRecord.value = null; wake(); }, ); // Eventually timeout and stop trying to load the module. let timeoutID: null | TimeoutID = setTimeout(function onTimeout() { if (__DEBUG__) { console.log( `[dynamicImportCache] loadModule("${moduleLoaderFunction.name}") onTimeout()`, ); } timeoutID = null; didTimeout = true; const timedoutRecord = ((newRecord: any): RejectedRecord); timedoutRecord.status = Rejected; timedoutRecord.value = null; wake(); }, TIMEOUT); moduleLoaderFunctionToModuleMap.set(moduleLoaderFunction, record); } // $FlowFixMe[underconstrained-implicit-instantiation] const response = readRecord(record).value; return response; }
22.919753
88
0.619515
Effective-Python-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /************************************************************************ * This file is forked between different DevTools implementations. * It should never be imported directly! * It should always be imported from "react-devtools-feature-flags". ************************************************************************/ export const consoleManagedByDevToolsDuringStrictMode = true; export const enableLogger = false; export const enableStyleXFeatures = false; export const isInternalFacebookBuild = false;
34.9
74
0.609484
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 {Thenable} from 'shared/ReactTypes'; // The server acts as a Client of itself when resolving Server References. // That's why we import the Client configuration from the Server. // Everything is aliased as their Server equivalence for clarity. import type { ServerReferenceId, ServerManifest, ClientReference as ServerReference, } from 'react-client/src/ReactFlightClientConfig'; import { resolveServerReference, preloadModule, requireModule, } from 'react-client/src/ReactFlightClientConfig'; export type JSONValue = | number | null | boolean | string | {+[key: string]: JSONValue} | $ReadOnlyArray<JSONValue>; const PENDING = 'pending'; const BLOCKED = 'blocked'; const RESOLVED_MODEL = 'resolved_model'; const INITIALIZED = 'fulfilled'; const ERRORED = 'rejected'; type PendingChunk<T> = { status: 'pending', value: null | Array<(T) => mixed>, reason: null | Array<(mixed) => mixed>, _response: Response, then(resolve: (T) => mixed, reject: (mixed) => mixed): void, }; type BlockedChunk<T> = { status: 'blocked', value: null | Array<(T) => mixed>, reason: null | Array<(mixed) => mixed>, _response: Response, then(resolve: (T) => mixed, reject: (mixed) => mixed): void, }; type ResolvedModelChunk<T> = { status: 'resolved_model', value: string, reason: null, _response: Response, then(resolve: (T) => mixed, reject: (mixed) => mixed): void, }; type InitializedChunk<T> = { status: 'fulfilled', value: T, reason: null, _response: Response, then(resolve: (T) => mixed, reject: (mixed) => mixed): void, }; type ErroredChunk<T> = { status: 'rejected', value: null, reason: mixed, _response: Response, then(resolve: (T) => mixed, reject: (mixed) => mixed): void, }; type SomeChunk<T> = | PendingChunk<T> | BlockedChunk<T> | ResolvedModelChunk<T> | InitializedChunk<T> | ErroredChunk<T>; // $FlowFixMe[missing-this-annot] function Chunk(status: any, value: any, reason: any, response: Response) { this.status = status; this.value = value; this.reason = reason; this._response = response; } // We subclass Promise.prototype so that we get other methods like .catch Chunk.prototype = (Object.create(Promise.prototype): any); // TODO: This doesn't return a new Promise chain unlike the real .then Chunk.prototype.then = function <T>( this: SomeChunk<T>, resolve: (value: T) => mixed, reject: (reason: mixed) => mixed, ) { const chunk: SomeChunk<T> = this; // If we have resolved content, we try to initialize it first which // might put us back into one of the other states. switch (chunk.status) { case RESOLVED_MODEL: initializeModelChunk(chunk); break; } // The status might have changed after initialization. switch (chunk.status) { case INITIALIZED: resolve(chunk.value); break; case PENDING: case BLOCKED: if (resolve) { if (chunk.value === null) { chunk.value = ([]: Array<(T) => mixed>); } chunk.value.push(resolve); } if (reject) { if (chunk.reason === null) { chunk.reason = ([]: Array<(mixed) => mixed>); } chunk.reason.push(reject); } break; default: reject(chunk.reason); break; } }; export type Response = { _bundlerConfig: ServerManifest, _prefix: string, _formData: FormData, _chunks: Map<number, SomeChunk<any>>, _fromJSON: (key: string, value: JSONValue) => any, }; export function getRoot<T>(response: Response): Thenable<T> { const chunk = getChunk(response, 0); return (chunk: any); } function createPendingChunk<T>(response: Response): PendingChunk<T> { // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors return new Chunk(PENDING, null, null, response); } function wakeChunk<T>(listeners: Array<(T) => mixed>, value: T): void { for (let i = 0; i < listeners.length; i++) { const listener = listeners[i]; listener(value); } } function wakeChunkIfInitialized<T>( chunk: SomeChunk<T>, resolveListeners: Array<(T) => mixed>, rejectListeners: null | Array<(mixed) => mixed>, ): void { switch (chunk.status) { case INITIALIZED: wakeChunk(resolveListeners, chunk.value); break; case PENDING: case BLOCKED: chunk.value = resolveListeners; chunk.reason = rejectListeners; break; case ERRORED: if (rejectListeners) { wakeChunk(rejectListeners, chunk.reason); } break; } } function triggerErrorOnChunk<T>(chunk: SomeChunk<T>, error: mixed): void { if (chunk.status !== PENDING && chunk.status !== BLOCKED) { // We already resolved. We didn't expect to see this. return; } const listeners = chunk.reason; const erroredChunk: ErroredChunk<T> = (chunk: any); erroredChunk.status = ERRORED; erroredChunk.reason = error; if (listeners !== null) { wakeChunk(listeners, error); } } function createResolvedModelChunk<T>( response: Response, value: string, ): ResolvedModelChunk<T> { // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors return new Chunk(RESOLVED_MODEL, value, null, response); } function resolveModelChunk<T>(chunk: SomeChunk<T>, value: string): void { if (chunk.status !== PENDING) { // We already resolved. We didn't expect to see this. return; } const resolveListeners = chunk.value; const rejectListeners = chunk.reason; const resolvedChunk: ResolvedModelChunk<T> = (chunk: any); resolvedChunk.status = RESOLVED_MODEL; resolvedChunk.value = value; if (resolveListeners !== null) { // This is unfortunate that we're reading this eagerly if // we already have listeners attached since they might no // longer be rendered or might not be the highest pri. initializeModelChunk(resolvedChunk); // The status might have changed after initialization. wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); } } function bindArgs(fn: any, args: any) { return fn.bind.apply(fn, [null].concat(args)); } function loadServerReference<T>( response: Response, id: ServerReferenceId, bound: null | Thenable<Array<any>>, parentChunk: SomeChunk<T>, parentObject: Object, key: string, ): T { const serverReference: ServerReference<T> = resolveServerReference<$FlowFixMe>(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all // the relevant modules already loaded but it allows for lazy loading of code // if needed. const preloadPromise = preloadModule(serverReference); let promise: Promise<T>; if (bound) { promise = Promise.all([(bound: any), preloadPromise]).then( ([args]: Array<any>) => bindArgs(requireModule(serverReference), args), ); } else { if (preloadPromise) { promise = Promise.resolve(preloadPromise).then(() => requireModule(serverReference), ); } else { // Synchronously available return requireModule(serverReference); } } promise.then( createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk), ); // We need a placeholder value that will be replaced later. return (null: any); } let initializingChunk: ResolvedModelChunk<any> = (null: any); let initializingChunkBlockedModel: null | {deps: number, value: any} = null; function initializeModelChunk<T>(chunk: ResolvedModelChunk<T>): void { const prevChunk = initializingChunk; const prevBlocked = initializingChunkBlockedModel; initializingChunk = chunk; initializingChunkBlockedModel = null; try { const value: T = JSON.parse(chunk.value, chunk._response._fromJSON); if ( initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0 ) { initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. // We have to go the BLOCKED state until they're resolved. const blockedChunk: BlockedChunk<T> = (chunk: any); blockedChunk.status = BLOCKED; blockedChunk.value = null; blockedChunk.reason = null; } else { const initializedChunk: InitializedChunk<T> = (chunk: any); initializedChunk.status = INITIALIZED; initializedChunk.value = value; } } catch (error) { const erroredChunk: ErroredChunk<T> = (chunk: any); erroredChunk.status = ERRORED; erroredChunk.reason = error; } finally { initializingChunk = prevChunk; initializingChunkBlockedModel = prevBlocked; } } // Report that any missing chunks in the model is now going to throw this // error upon read. Also notify any pending promises. export function reportGlobalError(response: Response, error: Error): void { response._chunks.forEach(chunk => { // If this chunk was already resolved or errored, it won't // trigger an error but if it wasn't then we need to // because we won't be getting any new data to resolve it. if (chunk.status === PENDING) { triggerErrorOnChunk(chunk, error); } }); } function getChunk(response: Response, id: number): SomeChunk<any> { const chunks = response._chunks; let chunk = chunks.get(id); if (!chunk) { const prefix = response._prefix; const key = prefix + id; // Check if we have this field in the backing store already. const backingEntry = response._formData.get(key); if (backingEntry != null) { // We assume that this is a string entry for now. chunk = createResolvedModelChunk(response, (backingEntry: any)); } else { // We're still waiting on this entry to stream in. chunk = createPendingChunk(response); } chunks.set(id, chunk); } return chunk; } function createModelResolver<T>( chunk: SomeChunk<T>, parentObject: Object, key: string, ): (value: any) => void { let blocked; if (initializingChunkBlockedModel) { blocked = initializingChunkBlockedModel; blocked.deps++; } else { blocked = initializingChunkBlockedModel = { deps: 1, value: null, }; } return value => { parentObject[key] = value; blocked.deps--; if (blocked.deps === 0) { if (chunk.status !== BLOCKED) { return; } const resolveListeners = chunk.value; const initializedChunk: InitializedChunk<T> = (chunk: any); initializedChunk.status = INITIALIZED; initializedChunk.value = blocked.value; if (resolveListeners !== null) { wakeChunk(resolveListeners, blocked.value); } } }; } function createModelReject<T>(chunk: SomeChunk<T>): (error: mixed) => void { return (error: mixed) => triggerErrorOnChunk(chunk, error); } function getOutlinedModel(response: Response, id: number): any { const chunk = getChunk(response, id); if (chunk.status === RESOLVED_MODEL) { initializeModelChunk(chunk); } if (chunk.status !== INITIALIZED) { // We know that this is emitted earlier so otherwise it's an error. throw chunk.reason; } return chunk.value; } function parseModelString( response: Response, parentObject: Object, key: string, value: string, ): any { if (value[0] === '$') { switch (value[1]) { case '$': { // This was an escaped string value. return value.slice(1); } case '@': { // Promise const id = parseInt(value.slice(2), 16); const chunk = getChunk(response, id); return chunk; } case 'S': { // Symbol return Symbol.for(value.slice(2)); } case 'F': { // Server Reference const id = parseInt(value.slice(2), 16); // TODO: Just encode this in the reference inline instead of as a model. const metaData: {id: ServerReferenceId, bound: Thenable<Array<any>>} = getOutlinedModel(response, id); return loadServerReference( response, metaData.id, metaData.bound, initializingChunk, parentObject, key, ); } case 'Q': { // Map const id = parseInt(value.slice(2), 16); const data = getOutlinedModel(response, id); return new Map(data); } case 'W': { // Set const id = parseInt(value.slice(2), 16); const data = getOutlinedModel(response, id); return new Set(data); } case 'K': { // FormData const stringId = value.slice(2); const formPrefix = response._prefix + stringId + '_'; const data = new FormData(); const backingFormData = response._formData; // We assume that the reference to FormData always comes after each // entry that it references so we can assume they all exist in the // backing store already. // $FlowFixMe[prop-missing] FormData has forEach on it. backingFormData.forEach((entry: File | string, entryKey: string) => { if (entryKey.startsWith(formPrefix)) { data.append(entryKey.slice(formPrefix.length), entry); } }); return data; } case 'I': { // $Infinity return Infinity; } case '-': { // $-0 or $-Infinity if (value === '$-0') { return -0; } else { return -Infinity; } } case 'N': { // $NaN return NaN; } case 'u': { // matches "$undefined" // Special encoding for `undefined` which can't be serialized as JSON otherwise. return undefined; } case 'D': { // Date return new Date(Date.parse(value.slice(2))); } case 'n': { // BigInt return BigInt(value.slice(2)); } default: { // We assume that anything else is a reference ID. const id = parseInt(value.slice(1), 16); const chunk = getChunk(response, id); switch (chunk.status) { case RESOLVED_MODEL: initializeModelChunk(chunk); break; } // The status might have changed after initialization. switch (chunk.status) { case INITIALIZED: return chunk.value; case PENDING: case BLOCKED: const parentChunk = initializingChunk; chunk.then( createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk), ); return null; default: throw chunk.reason; } } } } return value; } export function createResponse( bundlerConfig: ServerManifest, formFieldPrefix: string, backingFormData?: FormData = new FormData(), ): Response { const chunks: Map<number, SomeChunk<any>> = new Map(); const response: Response = { _bundlerConfig: bundlerConfig, _prefix: formFieldPrefix, _formData: backingFormData, _chunks: chunks, _fromJSON: function (this: any, key: string, value: JSONValue) { if (typeof value === 'string') { // We can't use .bind here because we need the "this" value. return parseModelString(response, this, key, value); } return value; }, }; return response; } export function resolveField( response: Response, key: string, value: string, ): void { // Add this field to the backing store. response._formData.append(key, value); const prefix = response._prefix; if (key.startsWith(prefix)) { const chunks = response._chunks; const id = +key.slice(prefix.length); const chunk = chunks.get(id); if (chunk) { // We were waiting on this key so now we can resolve it. resolveModelChunk(chunk, value); } } } export function resolveFile(response: Response, key: string, file: File): void { // Add this field to the backing store. response._formData.append(key, file); } export opaque type FileHandle = { chunks: Array<Uint8Array>, filename: string, mime: string, }; export function resolveFileInfo( response: Response, key: string, filename: string, mime: string, ): FileHandle { return { chunks: [], filename, mime, }; } export function resolveFileChunk( response: Response, handle: FileHandle, chunk: Uint8Array, ): void { handle.chunks.push(chunk); } export function resolveFileComplete( response: Response, key: string, handle: FileHandle, ): void { // Add this file to the backing store. // Node.js doesn't expose a global File constructor so we need to use // the append() form that takes the file name as the third argument, // to create a File object. const blob = new Blob(handle.chunks, {type: handle.mime}); response._formData.append(key, blob, handle.filename); } export function close(response: Response): void { // In case there are any remaining unresolved chunks, they won't // be resolved now. So we need to issue an error to those. // Ideally we should be able to early bail out if we kept a // ref count of pending chunks. reportGlobalError(response, new Error('Connection closed.')); }
28.078727
88
0.642721
Mastering-Machine-Learning-for-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {copy} from 'clipboard-js'; import * as React from 'react'; import {OptionsContext} from '../context'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import KeyValue from './KeyValue'; import NewKeyValue from './NewKeyValue'; import {alphaSortEntries, serializeDataForCopy} from '../utils'; import Store from '../../store'; import styles from './InspectedElementSharedStyles.css'; import {ElementTypeClass} from 'react-devtools-shared/src/frontend/types'; import type {InspectedElement} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {Element} from 'react-devtools-shared/src/frontend/types'; type Props = { bridge: FrontendBridge, element: Element, inspectedElement: InspectedElement, store: Store, }; export default function InspectedElementPropsTree({ bridge, element, inspectedElement, store, }: Props): React.Node { const {readOnly} = React.useContext(OptionsContext); const { canEditFunctionProps, canEditFunctionPropsDeletePaths, canEditFunctionPropsRenamePaths, props, type, } = inspectedElement; const canDeletePaths = type === ElementTypeClass || canEditFunctionPropsDeletePaths; const canEditValues = !readOnly && (type === ElementTypeClass || canEditFunctionProps); const canRenamePaths = type === ElementTypeClass || canEditFunctionPropsRenamePaths; const entries = props != null ? Object.entries(props) : null; if (entries !== null) { entries.sort(alphaSortEntries); } const isEmpty = entries === null || entries.length === 0; const handleCopy = () => copy(serializeDataForCopy(((props: any): Object))); return ( <div className={styles.InspectedElementTree} data-testname="InspectedElementPropsTree"> <div className={styles.HeaderRow}> <div className={styles.Header}>props</div> {!isEmpty && ( <Button onClick={handleCopy} title="Copy to clipboard"> <ButtonIcon type="copy" /> </Button> )} </div> {!isEmpty && (entries: any).map(([name, value]) => ( <KeyValue key={name} alphaSort={true} bridge={bridge} canDeletePaths={canDeletePaths} canEditValues={canEditValues} canRenamePaths={canRenamePaths} depth={1} element={element} hidden={false} inspectedElement={inspectedElement} name={name} path={[name]} pathRoot="props" store={store} value={value} /> ))} {canEditValues && ( <NewKeyValue bridge={bridge} depth={0} hidden={false} inspectedElement={inspectedElement} path={[]} store={store} type="props" /> )} </div> ); }
27.378378
79
0.630994
owtf
module.exports = { baseUrl: '.', name: 'input', out: 'output.js', optimize: 'none', paths: { react: '../../../../build/oss-experimental/react/umd/react.production.min', 'react-dom': '../../../../build/oss-experimental/react-dom/umd/react-dom.production.min', schedule: '../../../../build/oss-experimental/scheduler/umd/schedule.development', }, };
26.5
82
0.591146
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function Component() { const [count] = require('react').useState(0); return count; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJyZXF1aXJlIiwidXNlU3RhdGUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFBQTs7Ozs7Ozs7QUFTTyxTQUFTQSxTQUFULEdBQXFCO0FBQzFCLFFBQU0sQ0FBQ0MsS0FBRCxJQUFVQyxPQUFPLENBQUMsT0FBRCxDQUFQLENBQWlCQyxRQUFqQixDQUEwQixDQUExQixDQUFoQjs7QUFFQSxTQUFPRixLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50XSA9IHJlcXVpcmUoJ3JlYWN0JykudXNlU3RhdGUoMCk7XG5cbiAgcmV0dXJuIGNvdW50O1xufVxuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiJdLCJtYXBwaW5ncyI6IkNBQUQifV1dXX19XX0=
67.238095
1,032
0.902235
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); const isDarkMode = useIsDarkMode(); const { foo } = useFoo(); (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 27, columnNumber: 7 } }, "Foo: ", foo), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const [isDarkMode] = (0, _react.useState)(false); (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return isDarkMode; } function useFoo() { (0, _react.useDebugValue)('foo'); return { foo: true }; } //# sourceMappingURL=ComponentWithCustomHook.js.map?foo=bar&param=some_value
36.617647
743
0.636293
owtf
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; const React = window.React; export default class MediaEvents extends React.Component { state = { playbackRate: 2, events: { onCanPlay: false, onCanPlayThrough: false, onDurationChange: false, onEmptied: false, onEnded: false, onError: false, onLoadedData: false, onLoadedMetadata: false, onLoadStart: false, onPause: false, onPlay: false, onPlaying: false, onProgress: false, onRateChange: false, onResize: false, onSeeked: false, onSeeking: false, onSuspend: false, onTimeUpdate: false, onVolumeChange: false, onWaiting: false, }, }; updatePlaybackRate = () => { this.video.playbackRate = 2; }; setVideo = el => { this.video = el; }; eventDidFire(event) { this.setState({ events: Object.assign({}, this.state.events, {[event]: true}), }); } getProgress() { const events = Object.keys(this.state.events); const total = events.length; const fired = events.filter(type => this.state.events[type]).length; return fired / total; } render() { const events = Object.keys(this.state.events); const handlers = events.reduce((events, event) => { events[event] = this.eventDidFire.bind(this, event); return events; }, {}); return ( <FixtureSet title="Media Events"> <TestCase title="Event bubbling" description="Media events should synthetically bubble"> <TestCase.Steps> <li>Play the loaded video</li> <li>Pause the loaded video</li> <li>Play the failing video</li> <li>Drag the track bar</li> <li>Toggle the volume button</li> <li> <button onClick={this.updatePlaybackRate}> Click this button to increase playback rate </button> </li> </TestCase.Steps> <p className="footnote"> Note: This test does not confirm <code>onStalled</code>,{' '} <code>onAbort</code>, or <code>onEncrypted</code> </p> <TestCase.ExpectedResult> All events in the table below should be marked as "true". </TestCase.ExpectedResult> <section {...handlers}> <video src="/test.mp4" width="300" controls ref={this.setVideo} /> <video src="/missing.mp4" width="300" controls /> <p className="footnote"> Note: The second video will not load. This is intentional. </p> </section> <hr /> <section> <h3>Events</h3> <p>The following events should bubble:</p> <table> <tbody>{events.map(this.renderOutcome, this)}</tbody> </table> </section> </TestCase> </FixtureSet> ); } renderOutcome(event) { let fired = this.state.events[event]; return ( <tr key={event}> <td> <b>{event}</b> </td> <td style={{color: fired ? null : 'red'}}>{`${fired}`}</td> </tr> ); } }
25.430894
78
0.547692
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 {Interaction} from './useCanvasInteraction'; import type {Size} from './geometry'; import memoize from 'memoize-one'; import {View} from './View'; import {zeroPoint} from './geometry'; import {DPR} from '../content-views/constants'; export type ViewRefs = { activeView: View | null, hoveredView: View | null, }; // hidpi canvas: https://www.html5rocks.com/en/tutorials/canvas/hidpi/ function configureRetinaCanvas( canvas: HTMLCanvasElement, height: number, width: number, ) { canvas.width = width * DPR; canvas.height = height * DPR; canvas.style.width = `${width}px`; canvas.style.height = `${height}px`; } const getCanvasContext = memoize( ( canvas: HTMLCanvasElement, height: number, width: number, scaleCanvas: boolean = true, ): CanvasRenderingContext2D => { const context = canvas.getContext('2d', {alpha: false}); if (scaleCanvas) { configureRetinaCanvas(canvas, height, width); // Scale all drawing operations by the dpr, so you don't have to worry about the difference. context.scale(DPR, DPR); } return context; }, ); type ResetHoveredEventFn = () => void; /** * Represents the canvas surface and a view heirarchy. A surface is also the * place where all interactions enter the view heirarchy. */ export class Surface { rootView: ?View; _context: ?CanvasRenderingContext2D; _canvasSize: ?Size; _resetHoveredEvent: ResetHoveredEventFn; _viewRefs: ViewRefs = { activeView: null, hoveredView: null, }; constructor(resetHoveredEvent: ResetHoveredEventFn) { this._resetHoveredEvent = resetHoveredEvent; } hasActiveView(): boolean { return this._viewRefs.activeView !== null; } setCanvas(canvas: HTMLCanvasElement, canvasSize: Size) { this._context = getCanvasContext( canvas, canvasSize.height, canvasSize.width, ); this._canvasSize = canvasSize; if (this.rootView) { this.rootView.setNeedsDisplay(); } } displayIfNeeded() { const {rootView, _canvasSize, _context} = this; if (!rootView || !_context || !_canvasSize) { return; } rootView.setFrame({ origin: zeroPoint, size: _canvasSize, }); rootView.setVisibleArea({ origin: zeroPoint, size: _canvasSize, }); rootView.displayIfNeeded(_context, this._viewRefs); } getCurrentCursor(): string | null { const {activeView, hoveredView} = this._viewRefs; if (activeView !== null) { return activeView.currentCursor; } else if (hoveredView !== null) { return hoveredView.currentCursor; } else { return null; } } handleInteraction(interaction: Interaction) { const rootView = this.rootView; if (rootView != null) { const viewRefs = this._viewRefs; switch (interaction.type) { case 'mousemove': case 'wheel-control': case 'wheel-meta': case 'wheel-plain': case 'wheel-shift': // Clean out the hovered view before processing this type of interaction. const hoveredView = viewRefs.hoveredView; viewRefs.hoveredView = null; rootView.handleInteractionAndPropagateToSubviews( interaction, viewRefs, ); // If a previously hovered view is no longer hovered, update the outer state. if (hoveredView !== null && viewRefs.hoveredView === null) { this._resetHoveredEvent(); } break; default: rootView.handleInteractionAndPropagateToSubviews( interaction, viewRefs, ); break; } } } }
24.070968
98
0.637838
Effective-Python-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import Badge from './Badge'; import IndexableDisplayName from './IndexableDisplayName'; import styles from './ForgetBadge.css'; type CommonProps = { className?: string, }; type PropsForIndexable = CommonProps & { indexable: true, elementID: number, }; type PropsForNonIndexable = CommonProps & { indexable: false | void, elementID?: number, }; type Props = PropsForIndexable | PropsForNonIndexable; export default function ForgetBadge(props: Props): React.Node { const {className = ''} = props; const innerView = props.indexable ? ( <IndexableDisplayName displayName="Forget" id={props.elementID} /> ) : ( 'Forget' ); return <Badge className={`${styles.Root} ${className}`}>{innerView}</Badge>; }
21.068182
78
0.696907
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 */ // Turns a TypedArray or ArrayBuffer into a string that can be used for comparison // in a Map to see if the bytes are the same. export default function binaryToComparableString( view: $ArrayBufferView, ): string { return String.fromCharCode.apply( String, new Uint8Array(view.buffer, view.byteOffset, view.byteLength), ); }
26.2
82
0.723757
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 { prerenderToNodeStream, version, } from './src/server/react-dom-server.node';
20.071429
66
0.697279
Python-Penetration-Testing-for-Developers
'use strict'; module.exports = require('./client.browser');
14.5
45
0.688525
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {formatDuration} from './utils'; import ProfilerStore from 'react-devtools-shared/src/devtools/ProfilerStore'; import type {CommitTree} from './types'; export type ChartNode = { actualDuration: number, didRender: boolean, id: number, label: string, name: string, offset: number, selfDuration: number, treeBaseDuration: number, }; export type ChartData = { baseDuration: number, depth: number, idToDepthMap: Map<number, number>, maxSelfDuration: number, renderPathNodes: Set<number>, rows: Array<Array<ChartNode>>, }; const cachedChartData: Map<string, ChartData> = new Map(); export function getChartData({ commitIndex, commitTree, profilerStore, rootID, }: { commitIndex: number, commitTree: CommitTree, profilerStore: ProfilerStore, rootID: number, }): ChartData { const commitDatum = profilerStore.getCommitData(rootID, commitIndex); const {fiberActualDurations, fiberSelfDurations} = commitDatum; const {nodes} = commitTree; const chartDataKey = `${rootID}-${commitIndex}`; if (cachedChartData.has(chartDataKey)) { return ((cachedChartData.get(chartDataKey): any): ChartData); } const idToDepthMap: Map<number, number> = new Map(); const renderPathNodes: Set<number> = new Set(); const rows: Array<Array<ChartNode>> = []; let maxDepth = 0; let maxSelfDuration = 0; // Generate flame graph structure using tree base durations. const walkTree = ( id: number, rightOffset: number, currentDepth: number, ): ChartNode => { idToDepthMap.set(id, currentDepth); const node = nodes.get(id); if (node == null) { throw Error(`Could not find node with id "${id}" in commit tree`); } const {children, displayName, hocDisplayNames, key, treeBaseDuration} = node; const actualDuration = fiberActualDurations.get(id) || 0; const selfDuration = fiberSelfDurations.get(id) || 0; const didRender = fiberActualDurations.has(id); const name = displayName || 'Anonymous'; const maybeKey = key !== null ? ` key="${key}"` : ''; let maybeBadge = ''; if (hocDisplayNames !== null && hocDisplayNames.length > 0) { maybeBadge = ` (${hocDisplayNames[0]})`; } let label = `${name}${maybeBadge}${maybeKey}`; if (didRender) { label += ` (${formatDuration(selfDuration)}ms of ${formatDuration( actualDuration, )}ms)`; } maxDepth = Math.max(maxDepth, currentDepth); maxSelfDuration = Math.max(maxSelfDuration, selfDuration); const chartNode: ChartNode = { actualDuration, didRender, id, label, name, offset: rightOffset - treeBaseDuration, selfDuration, treeBaseDuration, }; if (currentDepth > rows.length) { rows.push([chartNode]); } else { rows[currentDepth - 1].push(chartNode); } for (let i = children.length - 1; i >= 0; i--) { const childID = children[i]; const childChartNode: $FlowFixMe = walkTree( childID, rightOffset, currentDepth + 1, ); rightOffset -= childChartNode.treeBaseDuration; } return chartNode; }; let baseDuration = 0; // Special case to handle unmounted roots. if (nodes.size > 0) { // Skip over the root; we don't want to show it in the flamegraph. const root = nodes.get(rootID); if (root == null) { throw Error( `Could not find root node with id "${rootID}" in commit tree`, ); } // Don't assume a single root. // Component filters or Fragments might lead to multiple "roots" in a flame graph. for (let i = root.children.length - 1; i >= 0; i--) { const id = root.children[i]; const node = nodes.get(id); if (node == null) { throw Error(`Could not find node with id "${id}" in commit tree`); } baseDuration += node.treeBaseDuration; walkTree(id, baseDuration, 1); } fiberActualDurations.forEach((duration, id) => { let node = nodes.get(id); if (node != null) { let currentID = node.parentID; while (currentID !== 0) { if (renderPathNodes.has(currentID)) { // We've already walked this path; we can skip it. break; } else { renderPathNodes.add(currentID); } node = nodes.get(currentID); currentID = node != null ? node.parentID : 0; } } }); } const chartData = { baseDuration, depth: maxDepth, idToDepthMap, maxSelfDuration, renderPathNodes, rows, }; cachedChartData.set(chartDataKey, chartData); return chartData; } export function invalidateChartData(): void { cachedChartData.clear(); }
24.611399
86
0.631526
Effective-Python-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {createRegExp} from '../utils'; import {TreeStateContext} from './TreeContext'; import styles from './Element.css'; const {useMemo, useContext} = React; type Props = { displayName: string | null, id: number, }; function IndexableDisplayName({displayName, id}: Props): React.Node { const {searchIndex, searchResults, searchText} = useContext(TreeStateContext); const isSearchResult = useMemo(() => { return searchResults.includes(id); }, [id, searchResults]); const isCurrentResult = searchIndex !== null && id === searchResults[searchIndex]; if (!isSearchResult || displayName === null) { return displayName; } const match = createRegExp(searchText).exec(displayName); if (match === null) { return displayName; } const startIndex = match.index; const stopIndex = startIndex + match[0].length; const children = []; if (startIndex > 0) { children.push(<span key="begin">{displayName.slice(0, startIndex)}</span>); } children.push( <mark key="middle" className={isCurrentResult ? styles.CurrentHighlight : styles.Highlight}> {displayName.slice(startIndex, stopIndex)} </mark>, ); if (stopIndex < displayName.length) { children.push(<span key="end">{displayName.slice(stopIndex)}</span>); } return children; } export default IndexableDisplayName;
23.859375
80
0.681761
owtf
var path = require('path'); module.exports = { entry: './input', output: { filename: 'output.js', }, resolve: { root: path.resolve('../../../../build/oss-experimental/'), }, };
15.416667
62
0.535714
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 {canUseDOM} from 'shared/ExecutionEnvironment'; export let passiveBrowserEventsSupported: boolean = false; // Check if browser support events with passive listeners // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support if (canUseDOM) { try { const options: { passive?: void, } = {}; Object.defineProperty(options, 'passive', { get: function () { passiveBrowserEventsSupported = true; }, }); window.addEventListener('test', options, options); window.removeEventListener('test', options, options); } catch (e) { passiveBrowserEventsSupported = false; } }
26.6875
112
0.692655
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 {isInternalModule} from '../moduleFilters'; describe('isInternalModule', () => { let map; function createFlamechartStackFrame(scriptUrl, locationLine, locationColumn) { return { name: 'test', timestamp: 0, duration: 1, scriptUrl, locationLine, locationColumn, }; } function createStackFrame(fileName, lineNumber, columnNumber) { return { columnNumber: columnNumber, lineNumber: lineNumber, fileName: fileName, functionName: 'test', source: ` at test (${fileName}:${lineNumber}:${columnNumber})`, }; } beforeEach(() => { map = new Map(); map.set('foo', [ [createStackFrame('foo', 10, 0), createStackFrame('foo', 15, 100)], ]); map.set('bar', [ [createStackFrame('bar', 10, 0), createStackFrame('bar', 15, 100)], [createStackFrame('bar', 20, 0), createStackFrame('bar', 25, 100)], ]); }); it('should properly identify stack frames within the provided module ranges', () => { expect( isInternalModule(map, createFlamechartStackFrame('foo', 10, 0)), ).toBe(true); expect( isInternalModule(map, createFlamechartStackFrame('foo', 12, 35)), ).toBe(true); expect( isInternalModule(map, createFlamechartStackFrame('foo', 15, 100)), ).toBe(true); expect( isInternalModule(map, createFlamechartStackFrame('bar', 12, 0)), ).toBe(true); expect( isInternalModule(map, createFlamechartStackFrame('bar', 22, 125)), ).toBe(true); }); it('should properly identify stack frames outside of the provided module ranges', () => { expect(isInternalModule(map, createFlamechartStackFrame('foo', 9, 0))).toBe( false, ); expect( isInternalModule(map, createFlamechartStackFrame('foo', 15, 101)), ).toBe(false); expect( isInternalModule(map, createFlamechartStackFrame('bar', 17, 0)), ).toBe(false); expect( isInternalModule(map, createFlamechartStackFrame('baz', 12, 0)), ).toBe(false); }); });
27.2125
91
0.631649
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 */ let React; let ReactNoop; let act; let useState; let useMemoCache; let MemoCacheSentinel; let ErrorBoundary; describe('useMemoCache()', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); act = require('internal-test-utils').act; useState = React.useState; useMemoCache = React.unstable_useMemoCache; MemoCacheSentinel = Symbol.for('react.memo_cache_sentinel'); class _ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = {hasError: false}; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return {hasError: true}; } componentDidCatch(error, errorInfo) {} render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } ErrorBoundary = _ErrorBoundary; }); // @gate enableUseMemoCacheHook test('render component using cache', async () => { function Component(props) { const cache = useMemoCache(1); expect(Array.isArray(cache)).toBe(true); expect(cache.length).toBe(1); expect(cache[0]).toBe(MemoCacheSentinel); return 'Ok'; } const root = ReactNoop.createRoot(); await act(() => { root.render(<Component />); }); expect(root).toMatchRenderedOutput('Ok'); }); // @gate enableUseMemoCacheHook test('update component using cache', async () => { let setX; let forceUpdate; function Component(props) { const cache = useMemoCache(5); // x is used to produce a `data` object passed to the child const [x, _setX] = useState(0); setX = _setX; // n is passed as-is to the child as a cache breaker const [n, setN] = useState(0); forceUpdate = () => setN(a => a + 1); const c_0 = x !== cache[0]; let data; if (c_0) { data = {text: `Count ${x}`}; cache[0] = x; cache[1] = data; } else { data = cache[1]; } const c_2 = x !== cache[2]; const c_3 = n !== cache[3]; let t0; if (c_2 || c_3) { t0 = <Text data={data} n={n} />; cache[2] = x; cache[3] = n; cache[4] = t0; } else { t0 = cache[4]; } return t0; } let data; const Text = jest.fn(function Text(props) { data = props.data; return data.text; }); const root = ReactNoop.createRoot(); await act(() => { root.render(<Component />); }); expect(root).toMatchRenderedOutput('Count 0'); expect(Text).toBeCalledTimes(1); const data0 = data; // Changing x should reset the data object await act(() => { setX(1); }); expect(root).toMatchRenderedOutput('Count 1'); expect(Text).toBeCalledTimes(2); expect(data).not.toBe(data0); const data1 = data; // Forcing an unrelated update shouldn't recreate the // data object. await act(() => { forceUpdate(); }); expect(root).toMatchRenderedOutput('Count 1'); expect(Text).toBeCalledTimes(3); expect(data).toBe(data1); // confirm that the cache persisted across renders }); // @gate enableUseMemoCacheHook test('update component using cache with setstate during render', async () => { let setN; function Component(props) { const cache = useMemoCache(5); // x is used to produce a `data` object passed to the child const [x] = useState(0); const c_0 = x !== cache[0]; let data; if (c_0) { data = {text: `Count ${x}`}; cache[0] = x; cache[1] = data; } else { data = cache[1]; } // n is passed as-is to the child as a cache breaker const [n, _setN] = useState(0); setN = _setN; if (n === 1) { setN(2); return; } const c_2 = x !== cache[2]; const c_3 = n !== cache[3]; let t0; if (c_2 || c_3) { t0 = <Text data={data} n={n} />; cache[2] = x; cache[3] = n; cache[4] = t0; } else { t0 = cache[4]; } return t0; } let data; const Text = jest.fn(function Text(props) { data = props.data; return `${data.text} (n=${props.n})`; }); const root = ReactNoop.createRoot(); await act(() => { root.render(<Component />); }); expect(root).toMatchRenderedOutput('Count 0 (n=0)'); expect(Text).toBeCalledTimes(1); const data0 = data; // Trigger an update that will cause a setState during render. The `data` prop // does not depend on `n`, and should remain cached. await act(() => { setN(1); }); expect(root).toMatchRenderedOutput('Count 0 (n=2)'); expect(Text).toBeCalledTimes(2); expect(data).toBe(data0); }); // @gate enableUseMemoCacheHook test('update component using cache with throw during render', async () => { let setN; let shouldFail = true; function Component(props) { const cache = useMemoCache(5); // x is used to produce a `data` object passed to the child const [x] = useState(0); const c_0 = x !== cache[0]; let data; if (c_0) { data = {text: `Count ${x}`}; cache[0] = x; cache[1] = data; } else { data = cache[1]; } // n is passed as-is to the child as a cache breaker const [n, _setN] = useState(0); setN = _setN; if (n === 1) { if (shouldFail) { shouldFail = false; throw new Error('failed'); } } const c_2 = x !== cache[2]; const c_3 = n !== cache[3]; let t0; if (c_2 || c_3) { t0 = <Text data={data} n={n} />; cache[2] = x; cache[3] = n; cache[4] = t0; } else { t0 = cache[4]; } return t0; } let data; const Text = jest.fn(function Text(props) { data = props.data; return `${data.text} (n=${props.n})`; }); spyOnDev(console, 'error'); const root = ReactNoop.createRoot(); await act(() => { root.render( <ErrorBoundary> <Component /> </ErrorBoundary>, ); }); expect(root).toMatchRenderedOutput('Count 0 (n=0)'); expect(Text).toBeCalledTimes(1); const data0 = data; await act(() => { // this triggers a throw. setN(1); }); expect(root).toMatchRenderedOutput('Count 0 (n=1)'); expect(Text).toBeCalledTimes(2); expect(data).toBe(data0); const data1 = data; // Forcing an unrelated update shouldn't recreate the // data object. await act(() => { setN(2); }); expect(root).toMatchRenderedOutput('Count 0 (n=2)'); expect(Text).toBeCalledTimes(3); expect(data).toBe(data1); // confirm that the cache persisted across renders }); // @gate enableUseMemoCacheHook test('update component and custom hook with caches', async () => { let setX; let forceUpdate; function Component(props) { const cache = useMemoCache(4); // x is used to produce a `data` object passed to the child const [x, _setX] = useState(0); setX = _setX; const c_x = x !== cache[0]; cache[0] = x; // n is passed as-is to the child as a cache breaker const [n, setN] = useState(0); forceUpdate = () => setN(a => a + 1); const c_n = n !== cache[1]; cache[1] = n; let _data; if (c_x) { _data = cache[2] = {text: `Count ${x}`}; } else { _data = cache[2]; } const data = useData(_data); if (c_x || c_n) { return (cache[3] = <Text data={data} n={n} />); } else { return cache[3]; } } function useData(data) { const cache = useMemoCache(2); const c_data = data !== cache[0]; cache[0] = data; let nextData; if (c_data) { nextData = cache[1] = {text: data.text.toLowerCase()}; } else { nextData = cache[1]; } return nextData; } let data; const Text = jest.fn(function Text(props) { data = props.data; return data.text; }); const root = ReactNoop.createRoot(); await act(() => { root.render(<Component />); }); expect(root).toMatchRenderedOutput('count 0'); expect(Text).toBeCalledTimes(1); const data0 = data; // Changing x should reset the data object await act(() => { setX(1); }); expect(root).toMatchRenderedOutput('count 1'); expect(Text).toBeCalledTimes(2); expect(data).not.toBe(data0); const data1 = data; // Forcing an unrelated update shouldn't recreate the // data object. await act(() => { forceUpdate(); }); expect(root).toMatchRenderedOutput('count 1'); expect(Text).toBeCalledTimes(3); expect(data).toBe(data1); // confirm that the cache persisted across renders }); });
24.561308
82
0.548507
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 {BatchConfigTransition} from 'react-reconciler/src/ReactFiberTracingMarkerComponent'; import type {StartTransitionOptions} from 'shared/ReactTypes'; import ReactCurrentBatchConfig from './ReactCurrentBatchConfig'; import {enableTransitionTracing} from 'shared/ReactFeatureFlags'; export function startTransition( scope: () => void, options?: StartTransitionOptions, ) { const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = ({}: BatchConfigTransition); const currentTransition = ReactCurrentBatchConfig.transition; if (__DEV__) { ReactCurrentBatchConfig.transition._updatedFibers = new Set(); } if (enableTransitionTracing) { if (options !== undefined && options.name !== undefined) { // $FlowFixMe[incompatible-use] found when upgrading Flow ReactCurrentBatchConfig.transition.name = options.name; // $FlowFixMe[incompatible-use] found when upgrading Flow ReactCurrentBatchConfig.transition.startTime = -1; } } try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; if (__DEV__) { if (prevTransition === null && currentTransition._updatedFibers) { const updatedFibersCount = currentTransition._updatedFibers.size; currentTransition._updatedFibers.clear(); if (updatedFibersCount > 10) { console.warn( 'Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.', ); } } } } }
32.803571
99
0.69926
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 {clamp} from './clamp'; /** * Single-axis offset and length state. * * ``` * contentStart containerStart containerEnd contentEnd * |<----------offset| | | * |<-------------------length------------------->| * ``` */ export type ScrollState = { offset: number, length: number, }; function clampOffset(state: ScrollState, containerLength: number): ScrollState { return { offset: clamp(-(state.length - containerLength), 0, state.offset), length: state.length, }; } function clampLength({ state, minContentLength, maxContentLength, containerLength, }: { state: ScrollState, minContentLength: number, maxContentLength: number, containerLength: number, }): ScrollState { return { offset: state.offset, length: clamp( Math.max(minContentLength, containerLength), Math.max(containerLength, maxContentLength), state.length, ), }; } /** * Returns `state` clamped such that: * - `length`: you won't be able to zoom in/out such that the content is * shorter than the `containerLength`. * - `offset`: content remains in `containerLength`. */ export function clampState({ state, minContentLength, maxContentLength, containerLength, }: { state: ScrollState, minContentLength: number, maxContentLength: number, containerLength: number, }): ScrollState { return clampOffset( clampLength({ state, minContentLength, maxContentLength, containerLength, }), containerLength, ); } export function translateState({ state, delta, containerLength, }: { state: ScrollState, delta: number, containerLength: number, }): ScrollState { return clampOffset( { offset: state.offset + delta, length: state.length, }, containerLength, ); } /** * Returns a new clamped `state` zoomed by `multiplier`. * * The provided fixed point will also remain stationary relative to * `containerStart`. * * ``` * contentStart containerStart fixedPoint containerEnd * |<---------offset-| x | * |-fixedPoint-------------------------------->x | * |-fixedPointFromContainer->x | * |<----------containerLength----------->| * ``` */ export function zoomState({ state, multiplier, fixedPoint, minContentLength, maxContentLength, containerLength, }: { state: ScrollState, multiplier: number, fixedPoint: number, minContentLength: number, maxContentLength: number, containerLength: number, }): ScrollState { // Length and offset must be computed separately, so that if the length is // clamped the offset will still be correct (unless it gets clamped too). const zoomedState = clampLength({ state: { offset: state.offset, length: state.length * multiplier, }, minContentLength, maxContentLength, containerLength, }); // Adjust offset so that distance between containerStart<->fixedPoint is fixed const fixedPointFromContainer = fixedPoint + state.offset; const scaledFixedPoint = fixedPoint * (zoomedState.length / state.length); const offsetAdjustedState = clampOffset( { offset: fixedPointFromContainer - scaledFixedPoint, length: zoomedState.length, }, containerLength, ); return offsetAdjustedState; } export function moveStateToRange({ state, rangeStart, rangeEnd, contentLength, minContentLength, maxContentLength, containerLength, }: { state: ScrollState, rangeStart: number, rangeEnd: number, contentLength: number, minContentLength: number, maxContentLength: number, containerLength: number, }): ScrollState { // Length and offset must be computed separately, so that if the length is // clamped the offset will still be correct (unless it gets clamped too). const lengthClampedState = clampLength({ state: { offset: state.offset, length: contentLength * (containerLength / (rangeEnd - rangeStart)), }, minContentLength, maxContentLength, containerLength, }); const offsetAdjustedState = clampOffset( { offset: -rangeStart * (lengthClampedState.length / contentLength), length: lengthClampedState.length, }, containerLength, ); return offsetAdjustedState; } export function areScrollStatesEqual( state1: ScrollState, state2: ScrollState, ): boolean { return state1.offset === state2.offset && state1.length === state2.length; }
22.014493
80
0.65148
PenTesting
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from '../src/ReactFlightWebpackNodeLoader.js';
22.727273
66
0.703846
owtf
import React, {Component, Suspense, startTransition} from 'react'; import Theme, {ThemeToggleButton} from './Theme'; import './Chrome.css'; export default class Chrome extends Component { state = {theme: 'light'}; render() { const assets = this.props.assets; return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="shortcut icon" href="favicon.ico" /> <link rel="stylesheet" href={assets['main.css']} /> <title>{this.props.title}</title> </head> <body className={this.state.theme}> <noscript dangerouslySetInnerHTML={{ __html: `<b>Enable JavaScript to run this app.</b>`, }} /> <Suspense fallback="Loading..."> <Theme.Provider value={this.state.theme}> {this.props.children} <div> <ThemeToggleButton onChange={theme => { startTransition(() => { this.setState({theme}); }); }} /> </div> </Theme.Provider> </Suspense> <script dangerouslySetInnerHTML={{ __html: `assetManifest = ${JSON.stringify(assets)};`, }} /> </body> </html> ); } }
28.32
80
0.477133
null
'use strict'; module.exports = require('bindings')('perfcounters');
16.5
53
0.710145
owtf
const validateHeaderIds = require('./headingIDHelpers/validateHeadingIDs'); const generateHeadingIds = require('./headingIDHelpers/generateHeadingIDs'); /** * yarn lint-heading-ids --> Checks all files and causes an error if heading ID is missing * yarn lint-heading-ids --fix --> Fixes all markdown file's heading IDs * yarn lint-heading-ids path/to/markdown.md --> Checks that particular file for missing heading ID (path can denote a directory or particular file) * yarn lint-heading-ids --fix path/to/markdown.md --> Fixes that particular file's markdown IDs (path can denote a directory or particular file) */ const markdownPaths = process.argv.slice(2); if (markdownPaths.includes('--fix')) { generateHeadingIds(markdownPaths.filter((path) => path !== '--fix')); } else { validateHeaderIds(markdownPaths); }
47.588235
148
0.747879
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 */ // NOTE: We're explicitly not using JSX here. This is intended to test // the current stack addendum without having source location added by babel. 'use strict'; let React; let ReactTestUtils; describe('ReactChildReconciler', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactTestUtils = require('react-dom/test-utils'); }); function createIterable(array) { return { '@@iterator': function () { let i = 0; return { next() { const next = { value: i < array.length ? array[i] : undefined, done: i === array.length, }; i++; return next; }, }; }, }; } function makeIterableFunction(value) { const fn = () => {}; fn['@@iterator'] = function iterator() { let timesCalled = 0; return { next() { const done = timesCalled++ > 0; return {done, value: done ? undefined : value}; }, }; }; return fn; } it('does not treat functions as iterables', () => { let node; const iterableFunction = makeIterableFunction('foo'); expect(() => { node = ReactTestUtils.renderIntoDocument( <div> <h1>{iterableFunction}</h1> </div>, ); }).toErrorDev('Functions are not valid as a React child'); expect(node.innerHTML).toContain(''); // h1 }); it('warns for duplicated array keys', () => { class Component extends React.Component { render() { return <div>{[<div key="1" />, <div key="1" />]}</div>; } } expect(() => ReactTestUtils.renderIntoDocument(<Component />)).toErrorDev( 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', ); }); it('warns for duplicated array keys with component stack info', () => { class Component extends React.Component { render() { return <div>{[<div key="1" />, <div key="1" />]}</div>; } } class Parent extends React.Component { render() { return React.cloneElement(this.props.child); } } class GrandParent extends React.Component { render() { return <Parent child={<Component />} />; } } expect(() => ReactTestUtils.renderIntoDocument(<GrandParent />)).toErrorDev( 'Encountered two children with the same key, `1`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.\n' + ' in div (at **)\n' + ' in Component (at **)\n' + ' in Parent (at **)\n' + ' in GrandParent (at **)', ); }); it('warns for duplicated iterable keys', () => { class Component extends React.Component { render() { return <div>{createIterable([<div key="1" />, <div key="1" />])}</div>; } } expect(() => ReactTestUtils.renderIntoDocument(<Component />)).toErrorDev( 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', ); }); it('warns for duplicated iterable keys with component stack info', () => { class Component extends React.Component { render() { return <div>{createIterable([<div key="1" />, <div key="1" />])}</div>; } } class Parent extends React.Component { render() { return React.cloneElement(this.props.child); } } class GrandParent extends React.Component { render() { return <Parent child={<Component />} />; } } expect(() => ReactTestUtils.renderIntoDocument(<GrandParent />)).toErrorDev( 'Encountered two children with the same key, `1`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.\n' + ' in div (at **)\n' + ' in Component (at **)\n' + ' in Parent (at **)\n' + ' in GrandParent (at **)', ); }); });
28.275449
80
0.569149
Effective-Python-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import Badge from './Badge'; import ForgetBadge from './ForgetBadge'; import styles from './ElementBadges.css'; type Props = { hocDisplayNames: Array<string> | null, compiledWithForget: boolean, className?: string, }; export default function ElementBadges({ compiledWithForget, hocDisplayNames, className = '', }: Props): React.Node { if ( !compiledWithForget && (hocDisplayNames == null || hocDisplayNames.length === 0) ) { return null; } return ( <div className={`${styles.Root} ${className}`}> {compiledWithForget && <ForgetBadge indexable={false} />} {hocDisplayNames != null && hocDisplayNames.length > 0 && ( <Badge>{hocDisplayNames[0]}</Badge> )} {hocDisplayNames != null && hocDisplayNames.length > 1 && ( <div className={styles.ExtraLabel}>+{hocDisplayNames.length - 1}</div> )} </div> ); }
22.102041
78
0.645447
Mastering-Machine-Learning-for-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactContext} from 'shared/ReactTypes'; import * as React from 'react'; import { createContext, useCallback, useContext, useEffect, useMemo, useState, } from 'react'; import {unstable_batchedUpdates as batchedUpdates} from 'react-dom'; import {createResource} from 'react-devtools-shared/src/devtools/cache'; import { BridgeContext, StoreContext, } from 'react-devtools-shared/src/devtools/views/context'; import {TreeStateContext} from '../TreeContext'; import type {StateContext} from '../TreeContext'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type Store from 'react-devtools-shared/src/devtools/store'; import type {StyleAndLayout as StyleAndLayoutBackend} from 'react-devtools-shared/src/backend/NativeStyleEditor/types'; import type {StyleAndLayout as StyleAndLayoutFrontend} from './types'; import type {Element} from 'react-devtools-shared/src/frontend/types'; import type { Resource, Thenable, } from 'react-devtools-shared/src/devtools/cache'; export type GetStyleAndLayout = (id: number) => StyleAndLayoutFrontend | null; type Context = { getStyleAndLayout: GetStyleAndLayout, }; const NativeStyleContext: ReactContext<Context> = createContext<Context>( ((null: any): Context), ); NativeStyleContext.displayName = 'NativeStyleContext'; type ResolveFn = (styleAndLayout: StyleAndLayoutFrontend) => void; type InProgressRequest = { promise: Thenable<StyleAndLayoutFrontend>, resolveFn: ResolveFn, }; const inProgressRequests: WeakMap<Element, InProgressRequest> = new WeakMap(); const resource: Resource<Element, Element, StyleAndLayoutFrontend> = createResource( (element: Element) => { const request = inProgressRequests.get(element); if (request != null) { return request.promise; } let resolveFn: | ResolveFn | (( result: Promise<StyleAndLayoutFrontend> | StyleAndLayoutFrontend, ) => void) = ((null: any): ResolveFn); const promise = new Promise(resolve => { resolveFn = resolve; }); inProgressRequests.set(element, ({promise, resolveFn}: $FlowFixMe)); return (promise: $FlowFixMe); }, (element: Element) => element, {useWeakMap: true}, ); type Props = { children: React$Node, }; function NativeStyleContextController({children}: Props): React.Node { const bridge = useContext<FrontendBridge>(BridgeContext); const store = useContext<Store>(StoreContext); const getStyleAndLayout = useCallback<GetStyleAndLayout>( (id: number) => { const element = store.getElementByID(id); if (element !== null) { return resource.read(element); } else { return null; } }, [store], ); // It's very important that this context consumes selectedElementID and not NativeStyleID. // Otherwise the effect that sends the "inspect" message across the bridge- // would itself be blocked by the same render that suspends (waiting for the data). const {selectedElementID} = useContext<StateContext>(TreeStateContext); const [currentStyleAndLayout, setCurrentStyleAndLayout] = useState<StyleAndLayoutFrontend | null>(null); // This effect handler invalidates the suspense cache and schedules rendering updates with React. useEffect(() => { const onStyleAndLayout = ({id, layout, style}: StyleAndLayoutBackend) => { const element = store.getElementByID(id); if (element !== null) { const styleAndLayout: StyleAndLayoutFrontend = { layout, style, }; const request = inProgressRequests.get(element); if (request != null) { inProgressRequests.delete(element); batchedUpdates(() => { request.resolveFn(styleAndLayout); setCurrentStyleAndLayout(styleAndLayout); }); } else { resource.write(element, styleAndLayout); // Schedule update with React if the currently-selected element has been invalidated. if (id === selectedElementID) { setCurrentStyleAndLayout(styleAndLayout); } } } }; bridge.addListener('NativeStyleEditor_styleAndLayout', onStyleAndLayout); return () => bridge.removeListener( 'NativeStyleEditor_styleAndLayout', onStyleAndLayout, ); }, [bridge, currentStyleAndLayout, selectedElementID, store]); // This effect handler polls for updates on the currently selected element. useEffect(() => { if (selectedElementID === null) { return () => {}; } const rendererID = store.getRendererIDForElement(selectedElementID); let timeoutID: TimeoutID | null = null; const sendRequest = () => { timeoutID = null; if (rendererID !== null) { bridge.send('NativeStyleEditor_measure', { id: selectedElementID, rendererID, }); } }; // Send the initial measurement request. // We'll poll for an update in the response handler below. sendRequest(); const onStyleAndLayout = ({id}: StyleAndLayoutBackend) => { // If this is the element we requested, wait a little bit and then ask for another update. if (id === selectedElementID) { if (timeoutID !== null) { clearTimeout(timeoutID); } timeoutID = setTimeout(sendRequest, 1000); } }; bridge.addListener('NativeStyleEditor_styleAndLayout', onStyleAndLayout); return () => { bridge.removeListener( 'NativeStyleEditor_styleAndLayout', onStyleAndLayout, ); if (timeoutID !== null) { clearTimeout(timeoutID); } }; }, [bridge, selectedElementID, store]); const value = useMemo( () => ({getStyleAndLayout}), // NativeStyle is used to invalidate the cache and schedule an update with React. [currentStyleAndLayout, getStyleAndLayout], ); return ( <NativeStyleContext.Provider value={value}> {children} </NativeStyleContext.Provider> ); } export {NativeStyleContext, NativeStyleContextController};
29.253589
119
0.671307
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/ReactSuspenseTestUtils';
21.818182
66
0.7
Python-Penetration-Testing-Cookbook
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "ComponentUsingHooksIndirectly", { enumerable: true, get: function () { return _ComponentUsingHooksIndirectly.Component; } }); Object.defineProperty(exports, "ComponentWithCustomHook", { enumerable: true, get: function () { return _ComponentWithCustomHook.Component; } }); Object.defineProperty(exports, "ComponentWithExternalCustomHooks", { enumerable: true, get: function () { return _ComponentWithExternalCustomHooks.Component; } }); Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", { enumerable: true, get: function () { return _ComponentWithMultipleHooksPerLine.Component; } }); Object.defineProperty(exports, "ComponentWithNestedHooks", { enumerable: true, get: function () { return _ComponentWithNestedHooks.Component; } }); Object.defineProperty(exports, "ContainingStringSourceMappingURL", { enumerable: true, get: function () { return _ContainingStringSourceMappingURL.Component; } }); Object.defineProperty(exports, "Example", { enumerable: true, get: function () { return _Example.Component; } }); Object.defineProperty(exports, "InlineRequire", { enumerable: true, get: function () { return _InlineRequire.Component; } }); Object.defineProperty(exports, "useTheme", { enumerable: true, get: function () { return _useTheme.default; } }); exports.ToDoList = void 0; var _ComponentUsingHooksIndirectly = require("./ComponentUsingHooksIndirectly"); var _ComponentWithCustomHook = require("./ComponentWithCustomHook"); var _ComponentWithExternalCustomHooks = require("./ComponentWithExternalCustomHooks"); var _ComponentWithMultipleHooksPerLine = require("./ComponentWithMultipleHooksPerLine"); var _ComponentWithNestedHooks = require("./ComponentWithNestedHooks"); var _ContainingStringSourceMappingURL = require("./ContainingStringSourceMappingURL"); var _Example = require("./Example"); var _InlineRequire = require("./InlineRequire"); var ToDoList = _interopRequireWildcard(require("./ToDoList")); exports.ToDoList = ToDoList; var _useTheme = _interopRequireDefault(require("./useTheme")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFTQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7OztBQUVBIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5fSBmcm9tICcuL0NvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5JztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhDdXN0b21Ib29rfSBmcm9tICcuL0NvbXBvbmVudFdpdGhDdXN0b21Ib29rJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZX0gZnJvbSAnLi9Db21wb25lbnRXaXRoTXVsdGlwbGVIb29rc1BlckxpbmUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgQ29tcG9uZW50V2l0aE5lc3RlZEhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhOZXN0ZWRIb29rcyc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBDb250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTH0gZnJvbSAnLi9Db250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTCc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBFeGFtcGxlfSBmcm9tICcuL0V4YW1wbGUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgSW5saW5lUmVxdWlyZX0gZnJvbSAnLi9JbmxpbmVSZXF1aXJlJztcbmltcG9ydCAqIGFzIFRvRG9MaXN0IGZyb20gJy4vVG9Eb0xpc3QnO1xuZXhwb3J0IHtUb0RvTGlzdH07XG5leHBvcnQge2RlZmF1bHQgYXMgdXNlVGhlbWV9IGZyb20gJy4vdXNlVGhlbWUnO1xuIl19
54.235955
1,652
0.816073
null
#!/usr/bin/env node 'use strict'; const {exec} = require('child-process-promise'); const {existsSync} = require('fs'); const {join} = require('path'); const {execRead, logPromise} = require('../utils'); const theme = require('../theme'); const run = async ({cwd, local, packages, version}) => { if (local) { // Sanity test if (!existsSync(join(cwd, 'build', 'node_modules', 'react'))) { console.error(theme.error`No local build exists.`); process.exit(1); } return; } if (!existsSync(join(cwd, 'build'))) { await exec(`mkdir ./build`, {cwd}); } // Cleanup from previous builds await exec(`rm -rf ./build/node_modules*`, {cwd}); await exec(`mkdir ./build/node_modules`, {cwd}); const nodeModulesPath = join(cwd, 'build/node_modules'); // Checkout "next" release from NPM for all local packages for (let i = 0; i < packages.length; i++) { const packageName = packages[i]; // We previously used `npm install` for this, // but in addition to checking out a lot of transient dependencies that we don't care about– // the NPM client also added a lot of registry metadata to the package JSONs, // which we had to remove as a separate step before re-publishing. // It's easier for us to just download and extract the tarball. const url = await execRead( `npm view ${packageName}@${version} dist.tarball` ); const filePath = join(nodeModulesPath, `${packageName}.tgz`); const packagePath = join(nodeModulesPath, `${packageName}`); const tempPackagePath = join(nodeModulesPath, 'package'); // Download packages from NPM and extract them to the expected build locations. await exec(`curl -L ${url} > ${filePath}`, {cwd}); await exec(`tar -xvzf ${filePath} -C ${nodeModulesPath}`, {cwd}); await exec(`mv ${tempPackagePath} ${packagePath}`, {cwd}); await exec(`rm ${filePath}`, {cwd}); } }; module.exports = async params => { return logPromise( run(params), theme`Checking out "next" from NPM {version ${params.version}}` ); };
32.803279
96
0.647259
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-noop-renderer-flight-server.production.min.js'); } else { module.exports = require('./cjs/react-noop-renderer-flight-server.development.js'); }
29.875
88
0.707317
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 */ // $FlowFixMe[cannot-resolve-module] const dynamicFeatureFlags = require('SchedulerFeatureFlags'); const {enableProfiling: enableProfilingFeatureFlag} = dynamicFeatureFlags; export const { userBlockingPriorityTimeout, normalPriorityTimeout, lowPriorityTimeout, enableIsInputPending, enableIsInputPendingContinuous, frameYieldMs, continuousYieldMs, maxYieldMs, } = dynamicFeatureFlags; export const enableSchedulerDebugging = true; export const enableProfiling: boolean = __PROFILE__ && enableProfilingFeatureFlag;
25.392857
74
0.779133
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 {canUseDOM} from 'shared/ExecutionEnvironment'; /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix: string): boolean { if (!canUseDOM) { return false; } const eventName = 'on' + eventNameSuffix; let isSupported = eventName in document; if (!isSupported) { const element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof (element: any)[eventName] === 'function'; } return isSupported; } export default isEventSupported;
25.116279
78
0.695187
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {Fragment, useContext} from 'react'; import {ProfilerContext} from './ProfilerContext'; import {formatDuration} from './utils'; import WhatChanged from './WhatChanged'; import {StoreContext} from '../context'; import styles from './HoveredFiberInfo.css'; import type {ChartNode} from './FlamegraphChartBuilder'; export type TooltipFiberData = { id: number, name: string, }; export type Props = { fiberData: ChartNode, }; export default function HoveredFiberInfo({fiberData}: Props): React.Node { const {profilerStore} = useContext(StoreContext); const {rootID, selectedCommitIndex} = useContext(ProfilerContext); const {id, name} = fiberData; const {profilingCache} = profilerStore; const commitIndices = profilingCache.getFiberCommits({ fiberID: ((id: any): number), rootID: ((rootID: any): number), }); let renderDurationInfo = null; let i = 0; for (i = 0; i < commitIndices.length; i++) { const commitIndex = commitIndices[i]; if (selectedCommitIndex === commitIndex) { const {fiberActualDurations, fiberSelfDurations} = profilerStore.getCommitData(((rootID: any): number), commitIndex); const actualDuration = fiberActualDurations.get(id) || 0; const selfDuration = fiberSelfDurations.get(id) || 0; renderDurationInfo = ( <div key={commitIndex} className={styles.CurrentCommit}> {formatDuration(selfDuration)}ms of {formatDuration(actualDuration)}ms </div> ); break; } } return ( <Fragment> <div className={styles.Toolbar}> <div className={styles.Component}>{name}</div> </div> <div className={styles.Content}> {renderDurationInfo || <div>Did not render.</div>} <WhatChanged fiberID={((id: any): number)} /> </div> </Fragment> ); }
26.932432
80
0.668925
owtf
// copied from scripts/jest/matchers/toWarnDev.js 'use strict'; const {diff: jestDiff} = require('jest-diff'); const util = require('util'); function shouldIgnoreConsoleError(format, args) { if (__DEV__) { if (typeof format === 'string') { if (format.indexOf('Error: Uncaught [') === 0) { // This looks like an uncaught error from invokeGuardedCallback() wrapper // in development that is reported by jsdom. Ignore because it's noisy. return true; } if (format.indexOf('The above error occurred') === 0) { // This looks like an error addendum from ReactFiberErrorLogger. // Ignore it too. return true; } } } else { if ( format != null && typeof format.message === 'string' && typeof format.stack === 'string' && args.length === 0 ) { // In production, ReactFiberErrorLogger logs error objects directly. // They are noisy too so we'll try to ignore them. return true; } } // Looks legit return false; } function normalizeCodeLocInfo(str) { return str && str.replace(/at .+?:\d+/g, 'at **'); } const createMatcherFor = consoleMethod => function matcher(callback, expectedMessages, options = {}) { if (__DEV__) { // Warn about incorrect usage of matcher. if (typeof expectedMessages === 'string') { expectedMessages = [expectedMessages]; } else if (!Array.isArray(expectedMessages)) { throw Error( `toWarnDev() requires a parameter of type string or an array of strings ` + `but was given ${typeof expectedMessages}.` ); } if ( options != null && (typeof options !== 'object' || Array.isArray(options)) ) { throw new Error( 'toWarnDev() second argument, when present, should be an object. ' + 'Did you forget to wrap the messages into an array?' ); } if (arguments.length > 3) { // `matcher` comes from Jest, so it's more than 2 in practice throw new Error( 'toWarnDev() received more than two arguments. ' + 'Did you forget to wrap the messages into an array?' ); } const withoutStack = options.withoutStack; const warningsWithoutComponentStack = []; const warningsWithComponentStack = []; const unexpectedWarnings = []; let lastWarningWithMismatchingFormat = null; let lastWarningWithExtraComponentStack = null; // Catch errors thrown by the callback, // But only rethrow them if all test expectations have been satisfied. // Otherwise an Error in the callback can mask a failed expectation, // and result in a test that passes when it shouldn't. let caughtError; const isLikelyAComponentStack = message => typeof message === 'string' && message.includes('\n in '); const consoleSpy = (format, ...args) => { // Ignore uncaught errors reported by jsdom // and React addendums because they're too noisy. if ( consoleMethod === 'error' && shouldIgnoreConsoleError(format, args) ) { return; } const message = util.format(format, ...args); const normalizedMessage = normalizeCodeLocInfo(message); // Remember if the number of %s interpolations // doesn't match the number of arguments. // We'll fail the test if it happens. let argIndex = 0; format.replace(/%s/g, () => argIndex++); if (argIndex !== args.length) { lastWarningWithMismatchingFormat = { format, args, expectedArgCount: argIndex, }; } // Protect against accidentally passing a component stack // to warning() which already injects the component stack. if ( args.length >= 2 && isLikelyAComponentStack(args[args.length - 1]) && isLikelyAComponentStack(args[args.length - 2]) ) { lastWarningWithExtraComponentStack = { format, }; } for (let index = 0; index < expectedMessages.length; index++) { const expectedMessage = expectedMessages[index]; if ( normalizedMessage === expectedMessage || normalizedMessage.includes(expectedMessage) ) { if (isLikelyAComponentStack(normalizedMessage)) { warningsWithComponentStack.push(normalizedMessage); } else { warningsWithoutComponentStack.push(normalizedMessage); } expectedMessages.splice(index, 1); return; } } let errorMessage; if (expectedMessages.length === 0) { errorMessage = 'Unexpected warning recorded: ' + this.utils.printReceived(normalizedMessage); } else if (expectedMessages.length === 1) { errorMessage = 'Unexpected warning recorded: ' + jestDiff(expectedMessages[0], normalizedMessage); } else { errorMessage = 'Unexpected warning recorded: ' + jestDiff(expectedMessages, [normalizedMessage]); } // Record the call stack for unexpected warnings. // We don't throw an Error here though, // Because it might be suppressed by ReactFiberScheduler. unexpectedWarnings.push(new Error(errorMessage)); }; // TODO Decide whether we need to support nested toWarn* expectations. // If we don't need it, add a check here to see if this is already our spy, // And throw an error. const originalMethod = console[consoleMethod]; // Avoid using Jest's built-in spy since it can't be removed. console[consoleMethod] = consoleSpy; try { callback(); } catch (error) { caughtError = error; } finally { // Restore the unspied method so that unexpected errors fail tests. console[consoleMethod] = originalMethod; // Any unexpected Errors thrown by the callback should fail the test. // This should take precedence since unexpected errors could block warnings. if (caughtError) { throw caughtError; } // Any unexpected warnings should be treated as a failure. if (unexpectedWarnings.length > 0) { return { message: () => unexpectedWarnings[0].stack, pass: false, }; } // Any remaining messages indicate a failed expectations. if (expectedMessages.length > 0) { return { message: () => `Expected warning was not recorded:\n ${this.utils.printReceived( expectedMessages[0] )}`, pass: false, }; } if (typeof withoutStack === 'number') { // We're expecting a particular number of warnings without stacks. if (withoutStack !== warningsWithoutComponentStack.length) { return { message: () => `Expected ${withoutStack} warnings without a component stack but received ${warningsWithoutComponentStack.length}:\n` + warningsWithoutComponentStack.map(warning => this.utils.printReceived(warning) ), pass: false, }; } } else if (withoutStack === true) { // We're expecting that all warnings won't have the stack. // If some warnings have it, it's an error. if (warningsWithComponentStack.length > 0) { return { message: () => `Received warning unexpectedly includes a component stack:\n ${this.utils.printReceived( warningsWithComponentStack[0] )}\nIf this warning intentionally includes the component stack, remove ` + `{withoutStack: true} from the toWarnDev() call. If you have a mix of ` + `warnings with and without stack in one toWarnDev() call, pass ` + `{withoutStack: N} where N is the number of warnings without stacks.`, pass: false, }; } } else if (withoutStack === false || withoutStack === undefined) { // We're expecting that all warnings *do* have the stack (default). // If some warnings don't have it, it's an error. if (warningsWithoutComponentStack.length > 0) { return { message: () => `Received warning unexpectedly does not include a component stack:\n ${this.utils.printReceived( warningsWithoutComponentStack[0] )}\nIf this warning intentionally omits the component stack, add ` + `{withoutStack: true} to the toWarnDev() call.`, pass: false, }; } } else { throw Error( `The second argument for toWarnDev(), when specified, must be an object. It may have a ` + `property called "withoutStack" whose value may be undefined, boolean, or a number. ` + `Instead received ${typeof withoutStack}.` ); } if (lastWarningWithMismatchingFormat !== null) { return { message: () => `Received ${ lastWarningWithMismatchingFormat.args.length } arguments for a message with ${ lastWarningWithMismatchingFormat.expectedArgCount } placeholders:\n ${this.utils.printReceived( lastWarningWithMismatchingFormat.format )}`, pass: false, }; } if (lastWarningWithExtraComponentStack !== null) { return { message: () => `Received more than one component stack for a warning:\n ${this.utils.printReceived( lastWarningWithExtraComponentStack.format )}\nDid you accidentally pass a stack to warning() as the last argument? ` + `Don't forget warning() already injects the component stack automatically.`, pass: false, }; } return {pass: true}; } } else { // Any uncaught errors or warnings should fail tests in production mode. callback(); return {pass: true}; } }; module.exports = { toLowPriorityWarnDev: createMatcherFor('warn'), toWarnDev: createMatcherFor('error'), };
35.568966
135
0.576198
Penetration-Testing-Study-Notes
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-art.production.min.js'); } else { module.exports = require('./cjs/react-art.development.js'); }
23.875
64
0.666667
null
#!/usr/bin/env node 'use strict'; const chalk = require('chalk'); const {exec} = require('child-process-promise'); const inquirer = require('inquirer'); const {homedir} = require('os'); const {join, relative} = require('path'); const {DRY_RUN, ROOT_PATH} = require('./configuration'); const { clear, confirm, confirmContinue, execRead, logger, saveBuildMetadata, } = require('./utils'); // This is the primary control function for this script. async function main() { clear(); await confirm('Have you stopped all NPM DEV scripts?', () => { const packagesPath = relative(process.cwd(), join(__dirname, 'packages')); console.log('Stop all NPM DEV scripts in the following directories:'); console.log( chalk.bold(' ' + join(packagesPath, 'react-devtools-core')), chalk.gray('(start:backend, start:standalone)') ); console.log( chalk.bold(' ' + join(packagesPath, 'react-devtools-inline')), chalk.gray('(start)') ); const buildAndTestScriptPath = join(__dirname, 'build-and-test.js'); const pathToPrint = relative(process.cwd(), buildAndTestScriptPath); console.log('\nThen restart this release step:'); console.log(chalk.bold.green(' ' + pathToPrint)); }); await confirm('Have you run the prepare-release script?', () => { const prepareReleaseScriptPath = join(__dirname, 'prepare-release.js'); const pathToPrint = relative(process.cwd(), prepareReleaseScriptPath); console.log('Begin by running the prepare-release script:'); console.log(chalk.bold.green(' ' + pathToPrint)); }); const archivePath = await archiveGitRevision(); const buildID = await downloadLatestReactBuild(); await buildAndTestInlinePackage(); await buildAndTestStandalonePackage(); await buildAndTestExtensions(); saveBuildMetadata({archivePath, buildID}); printFinalInstructions(); } async function archiveGitRevision() { const desktopPath = join(homedir(), 'Desktop'); const archivePath = join(desktopPath, 'DevTools.tgz'); console.log(`Creating git archive at ${chalk.dim(archivePath)}`); console.log(''); if (!DRY_RUN) { await exec(`git archive main | gzip > ${archivePath}`, {cwd: ROOT_PATH}); } return archivePath; } async function buildAndTestExtensions() { const extensionsPackagePath = join( ROOT_PATH, 'packages', 'react-devtools-extensions' ); const buildExtensionsPromise = exec('yarn build', { cwd: extensionsPackagePath, }); await logger( buildExtensionsPromise, `Building browser extensions ${chalk.dim('(this may take a minute)')}`, { estimate: 60000, } ); console.log(''); console.log(`Extensions have been build for Chrome, Edge, and Firefox.`); console.log(''); console.log('Smoke test each extension before continuing:'); console.log(` ${chalk.bold.green('cd ' + extensionsPackagePath)}`); console.log(''); console.log(` ${chalk.dim('# Test Chrome extension')}`); console.log(` ${chalk.bold.green('yarn test:chrome')}`); console.log(''); console.log(` ${chalk.dim('# Test Edge extension')}`); console.log(` ${chalk.bold.green('yarn test:edge')}`); console.log(''); console.log(` ${chalk.dim('# Firefox Chrome extension')}`); console.log(` ${chalk.bold.green('yarn test:firefox')}`); await confirmContinue(); } async function buildAndTestStandalonePackage() { const corePackagePath = join(ROOT_PATH, 'packages', 'react-devtools-core'); const corePackageDest = join(corePackagePath, 'dist'); await exec(`rm -rf ${corePackageDest}`); const buildCorePromise = exec('yarn build', {cwd: corePackagePath}); await logger( buildCorePromise, `Building ${chalk.bold('react-devtools-core')} package.`, { estimate: 25000, } ); const standalonePackagePath = join(ROOT_PATH, 'packages', 'react-devtools'); const safariFixturePath = join( ROOT_PATH, 'fixtures', 'devtools', 'standalone', 'index.html' ); console.log(''); console.log( `Test the ${chalk.bold('react-devtools-core')} target before continuing:` ); console.log(` ${chalk.bold.green('cd ' + standalonePackagePath)}`); console.log(` ${chalk.bold.green('yarn start')}`); console.log(''); console.log( 'The following fixture can be useful for testing Safari integration:' ); console.log(` ${chalk.dim(safariFixturePath)}`); await confirmContinue(); } async function buildAndTestInlinePackage() { const inlinePackagePath = join( ROOT_PATH, 'packages', 'react-devtools-inline' ); const inlinePackageDest = join(inlinePackagePath, 'dist'); await exec(`rm -rf ${inlinePackageDest}`); const buildPromise = exec('yarn build', {cwd: inlinePackagePath}); await logger( buildPromise, `Building ${chalk.bold('react-devtools-inline')} package.`, { estimate: 10000, } ); const shellPackagePath = join(ROOT_PATH, 'packages', 'react-devtools-shell'); console.log(''); console.log(`Built ${chalk.bold('react-devtools-inline')} target.`); console.log(''); console.log('Test this build before continuing:'); console.log(` ${chalk.bold.green('cd ' + shellPackagePath)}`); console.log(` ${chalk.bold.green('yarn start')}`); await confirmContinue(); } async function downloadLatestReactBuild() { const releaseScriptPath = join(ROOT_PATH, 'scripts', 'release'); const installPromise = exec('yarn install', {cwd: releaseScriptPath}); await logger( installPromise, `Installing release script dependencies. ${chalk.dim( '(this may take a minute if CI is still running)' )}`, { estimate: 5000, } ); console.log(''); const {commit} = await inquirer.prompt([ { type: 'input', name: 'commit', message: 'Which React version (commit) should be used?', default: 'main', }, ]); console.log(''); const downloadScriptPath = join( releaseScriptPath, 'download-experimental-build.js' ); const downloadPromise = execRead( `"${downloadScriptPath}" --commit=${commit}` ); const output = await logger( downloadPromise, 'Downloading React artifacts from CI.', {estimate: 15000} ); const match = output.match('--build=([0-9]+)'); if (match.length === 0) { console.error(chalk.red(`No build ID found in "${output}"`)); process.exit(1); } const buildID = match[1]; console.log(''); console.log(`Downloaded artifacts for CI build ${chalk.bold(buildID)}.`); return buildID; } function printFinalInstructions() { const publishReleaseScriptPath = join(__dirname, 'publish-release.js'); const pathToPrint = relative(process.cwd(), publishReleaseScriptPath); console.log(''); console.log('Continue by running the publish-release script:'); console.log(chalk.bold.green(' ' + pathToPrint)); } main();
26.653226
79
0.663555
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 {enableCreateEventHandleAPI} from 'shared/ReactFeatureFlags'; export type Flags = number; // Don't change these values. They're used by React Dev Tools. export const NoFlags = /* */ 0b0000000000000000000000000000; export const PerformedWork = /* */ 0b0000000000000000000000000001; export const Placement = /* */ 0b0000000000000000000000000010; export const DidCapture = /* */ 0b0000000000000000000010000000; export const Hydrating = /* */ 0b0000000000000001000000000000; // You can change the rest (and add more). export const Update = /* */ 0b0000000000000000000000000100; /* Skipped value: 0b0000000000000000000000001000; */ export const ChildDeletion = /* */ 0b0000000000000000000000010000; export const ContentReset = /* */ 0b0000000000000000000000100000; export const Callback = /* */ 0b0000000000000000000001000000; /* Used by DidCapture: 0b0000000000000000000010000000; */ export const ForceClientRender = /* */ 0b0000000000000000000100000000; export const Ref = /* */ 0b0000000000000000001000000000; export const Snapshot = /* */ 0b0000000000000000010000000000; export const Passive = /* */ 0b0000000000000000100000000000; /* Used by Hydrating: 0b0000000000000001000000000000; */ export const Visibility = /* */ 0b0000000000000010000000000000; export const StoreConsistency = /* */ 0b0000000000000100000000000000; // It's OK to reuse these bits because these flags are mutually exclusive for // different fiber types. We should really be doing this for as many flags as // possible, because we're about to run out of bits. export const ScheduleRetry = StoreConsistency; export const ShouldSuspendCommit = Visibility; export const DidDefer = ContentReset; export const LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit) export const HostEffectMask = /* */ 0b0000000000000111111111111111; // These are not really side effects, but we still reuse this field. export const Incomplete = /* */ 0b0000000000001000000000000000; export const ShouldCapture = /* */ 0b0000000000010000000000000000; export const ForceUpdateForLegacySuspense = /* */ 0b0000000000100000000000000000; export const DidPropagateContext = /* */ 0b0000000001000000000000000000; export const NeedsPropagation = /* */ 0b0000000010000000000000000000; export const Forked = /* */ 0b0000000100000000000000000000; // Static tags describe aspects of a fiber that are not specific to a render, // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). // This enables us to defer more work in the unmount case, // since we can defer traversing the tree during layout to look for Passive effects, // and instead rely on the static flag as a signal that there may be cleanup work. export const RefStatic = /* */ 0b0000001000000000000000000000; export const LayoutStatic = /* */ 0b0000010000000000000000000000; export const PassiveStatic = /* */ 0b0000100000000000000000000000; export const MaySuspendCommit = /* */ 0b0001000000000000000000000000; // Flag used to identify newly inserted fibers. It isn't reset after commit unlike `Placement`. export const PlacementDEV = /* */ 0b0010000000000000000000000000; export const MountLayoutDev = /* */ 0b0100000000000000000000000000; export const MountPassiveDev = /* */ 0b1000000000000000000000000000; // Groups of flags that are used in the commit phase to skip over trees that // don't contain effects, by checking subtreeFlags. export const BeforeMutationMask: number = // TODO: Remove Update flag from before mutation phase by re-landing Visibility // flag logic (see #20043) Update | Snapshot | (enableCreateEventHandleAPI ? // createEventHandle needs to visit deleted and hidden trees to // fire beforeblur // TODO: Only need to visit Deletions during BeforeMutation phase if an // element is focused. ChildDeletion | Visibility : 0); export const MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; export const LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask export const PassiveMask = Passive | Visibility | ChildDeletion; // Union of tags that don't get reset on clones. // This allows certain concepts to persist without recalculating them, // e.g. whether a subtree contains passive effects or portals. export const StaticMask = LayoutStatic | PassiveStatic | RefStatic | MaySuspendCommit;
47.724771
95
0.690395
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 { Thenable, PendingThenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; import type {Lane} from './ReactFiberLane'; import {requestTransitionLane} from './ReactFiberRootScheduler'; import {NoLane} from './ReactFiberLane'; // If there are multiple, concurrent async actions, they are entangled. All // transition updates that occur while the async action is still in progress // are treated as part of the action. // // The ideal behavior would be to treat each async function as an independent // action. However, without a mechanism like AsyncContext, we can't tell which // action an update corresponds to. So instead, we entangle them all into one. // The listeners to notify once the entangled scope completes. let currentEntangledListeners: Array<() => mixed> | null = null; // The number of pending async actions in the entangled scope. let currentEntangledPendingCount: number = 0; // The transition lane shared by all updates in the entangled scope. let currentEntangledLane: Lane = NoLane; export function requestAsyncActionContext<S>( actionReturnValue: Thenable<any>, // If this is provided, this resulting thenable resolves to this value instead // of the return value of the action. This is a perf trick to avoid composing // an extra async function. overrideReturnValue: S | null, ): Thenable<S> { // This is an async action. // // Return a thenable that resolves once the action scope (i.e. the async // function passed to startTransition) has finished running. const thenable: Thenable<S> = (actionReturnValue: any); let entangledListeners; if (currentEntangledListeners === null) { // There's no outer async action scope. Create a new one. entangledListeners = currentEntangledListeners = []; currentEntangledPendingCount = 0; currentEntangledLane = requestTransitionLane(); } else { entangledListeners = currentEntangledListeners; } currentEntangledPendingCount++; // Create a thenable that represents the result of this action, but doesn't // resolve until the entire entangled scope has finished. // // Expressed using promises: // const [thisResult] = await Promise.all([thisAction, entangledAction]); // return thisResult; const resultThenable = createResultThenable<S>(entangledListeners); let resultStatus = 'pending'; let resultValue; let rejectedReason; thenable.then( (value: S) => { resultStatus = 'fulfilled'; resultValue = overrideReturnValue !== null ? overrideReturnValue : value; pingEngtangledActionScope(); }, error => { resultStatus = 'rejected'; rejectedReason = error; pingEngtangledActionScope(); }, ); // Attach a listener to fill in the result. entangledListeners.push(() => { switch (resultStatus) { case 'fulfilled': { const fulfilledThenable: FulfilledThenable<S> = (resultThenable: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = resultValue; break; } case 'rejected': { const rejectedThenable: RejectedThenable<S> = (resultThenable: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = rejectedReason; break; } case 'pending': default: { // The listener above should have been called first, so `resultStatus` // should already be set to the correct value. throw new Error( 'Thenable should have already resolved. This ' + 'is a bug in React.', ); } } }); return resultThenable; } export function requestSyncActionContext<S>( actionReturnValue: any, // If this is provided, this resulting thenable resolves to this value instead // of the return value of the action. This is a perf trick to avoid composing // an extra async function. overrideReturnValue: S | null, ): Thenable<S> | S { const resultValue: S = overrideReturnValue !== null ? overrideReturnValue : (actionReturnValue: any); // This is not an async action, but it may be part of an outer async action. if (currentEntangledListeners === null) { return resultValue; } else { // Return a thenable that does not resolve until the entangled actions // have finished. const entangledListeners = currentEntangledListeners; const resultThenable = createResultThenable<S>(entangledListeners); entangledListeners.push(() => { const fulfilledThenable: FulfilledThenable<S> = (resultThenable: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = resultValue; }); return resultThenable; } } function pingEngtangledActionScope() { if ( currentEntangledListeners !== null && --currentEntangledPendingCount === 0 ) { // All the actions have finished. Close the entangled async action scope // and notify all the listeners. const listeners = currentEntangledListeners; currentEntangledListeners = null; currentEntangledLane = NoLane; for (let i = 0; i < listeners.length; i++) { const listener = listeners[i]; listener(); } } } function createResultThenable<S>( entangledListeners: Array<() => mixed>, ): Thenable<S> { // Waits for the entangled async action to complete, then resolves to the // result of an individual action. const resultThenable: PendingThenable<S> = { status: 'pending', value: null, reason: null, then(resolve: S => mixed) { // This is a bit of a cheat. `resolve` expects a value of type `S` to be // passed, but because we're instrumenting the `status` field ourselves, // and we know this thenable will only be used by React, we also know // the value isn't actually needed. So we add the resolve function // directly to the entangled listeners. // // This is also why we don't need to check if the thenable is still // pending; the Suspense implementation already performs that check. const ping: () => mixed = (resolve: any); entangledListeners.push(ping); }, }; return resultThenable; } export function peekEntangledActionLane(): Lane { return currentEntangledLane; }
33.417112
80
0.695571
cybersecurity-penetration-testing
/* eslint-disable dot-notation */ // Instruction set for Fizz inline scripts. // DO NOT DIRECTLY IMPORT THIS FILE. This is the source for the compiled and // minified code in ReactDOMFizzInstructionSetInlineCodeStrings. import { clientRenderBoundary, completeBoundary, completeSegment, } from './ReactDOMFizzInstructionSetShared'; export {clientRenderBoundary, completeBoundary, completeSegment}; // This function is almost identical to the version used by the external // runtime (ReactDOMFizzInstructionSetExternalRuntime), with the exception of // how we read completeBoundaryImpl and resourceMap export function completeBoundaryWithStyles( suspenseBoundaryID, contentID, stylesheetDescriptors, ) { const completeBoundaryImpl = window['$RC']; const resourceMap = window['$RM']; const precedences = new Map(); const thisDocument = document; let lastResource, node; // Seed the precedence list with existing resources and collect hoistable style tags const nodes = thisDocument.querySelectorAll( 'link[data-precedence],style[data-precedence]', ); const styleTagsToHoist = []; for (let i = 0; (node = nodes[i++]); ) { if (node.getAttribute('media') === 'not all') { styleTagsToHoist.push(node); } else { if (node.tagName === 'LINK') { resourceMap.set(node.getAttribute('href'), node); } precedences.set(node.dataset['precedence'], (lastResource = node)); } } let i = 0; const dependencies = []; let href, precedence, attr, loadingState, resourceEl, media; // Sheets Mode let sheetMode = true; while (true) { if (sheetMode) { // Sheet Mode iterates over the stylesheet arguments and constructs them if new or checks them for // dependency if they already existed const stylesheetDescriptor = stylesheetDescriptors[i++]; if (!stylesheetDescriptor) { // enter <style> Mode sheetMode = false; i = 0; continue; } let avoidInsert = false; let j = 0; href = stylesheetDescriptor[j++]; if ((resourceEl = resourceMap.get(href))) { // We have an already inserted stylesheet. loadingState = resourceEl['_p']; avoidInsert = true; } else { // We haven't already processed this href so we need to construct a stylesheet and hoist it // We construct it here and attach a loadingState. We also check whether it matches // media before we include it in the dependency array. resourceEl = thisDocument.createElement('link'); resourceEl.href = href; resourceEl.rel = 'stylesheet'; resourceEl.dataset['precedence'] = precedence = stylesheetDescriptor[j++]; while ((attr = stylesheetDescriptor[j++])) { resourceEl.setAttribute(attr, stylesheetDescriptor[j++]); } loadingState = resourceEl['_p'] = new Promise((resolve, reject) => { resourceEl.onload = resolve; resourceEl.onerror = reject; }); // Save this resource element so we can bailout if it is used again resourceMap.set(href, resourceEl); } media = resourceEl.getAttribute('media'); if ( loadingState && loadingState['s'] !== 'l' && (!media || window['matchMedia'](media).matches) ) { dependencies.push(loadingState); } if (avoidInsert) { // We have a link that is already in the document. We don't want to fall through to the insert path continue; } } else { // <style> mode iterates over not-yet-hoisted <style> tags with data-precedence and hoists them. resourceEl = styleTagsToHoist[i++]; if (!resourceEl) { // we are done with all style tags break; } precedence = resourceEl.getAttribute('data-precedence'); resourceEl.removeAttribute('media'); } // resourceEl is either a newly constructed <link rel="stylesheet" ...> or a <style> tag requiring hoisting const prior = precedences.get(precedence) || lastResource; if (prior === lastResource) { lastResource = resourceEl; } precedences.set(precedence, resourceEl); // Finally, we insert the newly constructed instance at an appropriate location // in the Document. if (prior) { prior.parentNode.insertBefore(resourceEl, prior.nextSibling); } else { const head = thisDocument.head; head.insertBefore(resourceEl, head.firstChild); } } Promise.all(dependencies).then( completeBoundaryImpl.bind(null, suspenseBoundaryID, contentID, ''), completeBoundaryImpl.bind( null, suspenseBoundaryID, contentID, 'Resource failed to load', ), ); }
32.464789
111
0.653968
PenTesting
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-webpack-client.node.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-webpack-client.node.development.js'); }
30.625
91
0.706349
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
null
/** * @externs */ /* eslint-disable */ 'use strict'; /** @type {function} */ var addEventListener;
9.4
23
0.582524
Python-Penetration-Testing-for-Developers
let React; let ReactNoop; let Scheduler; let startTransition; let useState; let useEffect; let act; let assertLog; let waitFor; let waitForPaint; describe('ReactInterleavedUpdates', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; startTransition = React.startTransition; useState = React.useState; useEffect = React.useEffect; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; waitFor = InternalTestUtils.waitFor; waitForPaint = InternalTestUtils.waitForPaint; }); function Text({text}) { Scheduler.log(text); return text; } test('update during an interleaved event is not processed during the current render', async () => { const updaters = []; function Child() { const [state, setState] = useState(0); useEffect(() => { updaters.push(setState); }, []); return <Text text={state} />; } function updateChildren(value) { for (let i = 0; i < updaters.length; i++) { const setState = updaters[i]; setState(value); } } const root = ReactNoop.createRoot(); await act(() => { root.render( <> <Child /> <Child /> <Child /> </>, ); }); assertLog([0, 0, 0]); expect(root).toMatchRenderedOutput('000'); await act(async () => { React.startTransition(() => { updateChildren(1); }); // Partially render the children. Only the first one. await waitFor([1]); // In an interleaved event, schedule an update on each of the children. // Including the two that haven't rendered yet. React.startTransition(() => { updateChildren(2); }); // We should continue rendering without including the interleaved updates. await waitForPaint([1, 1]); expect(root).toMatchRenderedOutput('111'); }); // The interleaved updates flush in a separate render. assertLog([2, 2, 2]); expect(root).toMatchRenderedOutput('222'); }); // @gate forceConcurrentByDefaultForTesting test('low priority update during an interleaved event is not processed during the current render', async () => { // Same as previous test, but the interleaved update is lower priority than // the in-progress render. const updaters = []; function Child() { const [state, setState] = useState(0); useEffect(() => { updaters.push(setState); }, []); return <Text text={state} />; } function updateChildren(value) { for (let i = 0; i < updaters.length; i++) { const setState = updaters[i]; setState(value); } } const root = ReactNoop.createRoot(); await act(async () => { root.render( <> <Child /> <Child /> <Child /> </>, ); }); assertLog([0, 0, 0]); expect(root).toMatchRenderedOutput('000'); await act(async () => { updateChildren(1); // Partially render the children. Only the first one. await waitFor([1]); // In an interleaved event, schedule an update on each of the children. // Including the two that haven't rendered yet. startTransition(() => { updateChildren(2); }); // We should continue rendering without including the interleaved updates. await waitForPaint([1, 1]); expect(root).toMatchRenderedOutput('111'); }); // The interleaved updates flush in a separate render. assertLog([2, 2, 2]); expect(root).toMatchRenderedOutput('222'); }); test('regression for #24350: does not add to main update queue until interleaved update queue has been cleared', async () => { let setStep; function App() { const [step, _setState] = useState(0); setStep = _setState; return ( <> <Text text={'A' + step} /> <Text text={'B' + step} /> <Text text={'C' + step} /> </> ); } const root = ReactNoop.createRoot(); await act(() => { root.render(<App />); }); assertLog(['A0', 'B0', 'C0']); expect(root).toMatchRenderedOutput('A0B0C0'); await act(async () => { // Start the render phase. startTransition(() => { setStep(1); }); await waitFor(['A1', 'B1']); // Schedule an interleaved update. This gets placed on a special queue. startTransition(() => { setStep(2); }); // Finish rendering the first update. await waitForPaint(['C1']); // Schedule another update. (In the regression case, this was treated // as a normal, non-interleaved update and it was inserted into the queue // before the interleaved one was processed.) startTransition(() => { setStep(3); }); }); // The last update should win. assertLog(['A3', 'B3', 'C3']); expect(root).toMatchRenderedOutput('A3B3C3'); }); });
25.864583
128
0.582897
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-art/src/ReactFiberConfigART';
22.272727
66
0.705882
null
'use strict'; const chalk = require('chalk'); const {exec} = require('child-process-promise'); const {existsSync, mkdirSync} = require('fs'); const {readJsonSync, writeJsonSync} = require('fs-extra'); const inquirer = require('inquirer'); const {join} = require('path'); const createLogger = require('progress-estimator'); const { BUILD_METADATA_TEMP_DIRECTORY, NPM_PACKAGES, } = require('./configuration'); const logger = createLogger({ storagePath: join(__dirname, '.progress-estimator'), }); async function checkNPMPermissions() { const currentUser = await execRead('npm whoami'); const failedProjects = []; const checkProject = async project => { const owners = (await execRead(`npm owner ls ${project}`)) .split('\n') .filter(owner => owner) .map(owner => owner.split(' ')[0]); if (!owners.includes(currentUser)) { failedProjects.push(project); } }; await logger( Promise.all(NPM_PACKAGES.map(checkProject)), `Checking NPM permissions for ${chalk.bold(currentUser)}.`, {estimate: 2500} ); console.log(''); if (failedProjects.length) { console.error(chalk.red.bold('Insufficient NPM permissions')); console.error(''); console.error( chalk.red( `NPM user {underline ${currentUser}} is not an owner for: ${chalk.bold( failedProjects.join(', ') )}` ) ); console.error( chalk.red( 'Please contact a React team member to be added to the above project(s).' ) ); process.exit(1); } } function clear() { console.clear(); } async function confirm(message, exitFunction) { console.log(''); const {confirmation} = await inquirer.prompt({ name: 'confirmation', type: 'confirm', message, }); console.log(''); if (!confirmation) { if (typeof exitFunction === 'function') { exitFunction(); } process.exit(0); } } async function confirmContinue(exitFunction) { await confirm('Continue the release?', exitFunction); } async function execRead(command, options) { const {stdout} = await exec(command, options); return stdout.trim(); } function readSavedBuildMetadata() { const path = join(BUILD_METADATA_TEMP_DIRECTORY, 'metadata'); if (!existsSync(path)) { console.error(chalk.red('Expected to find build metadata at:')); console.error(chalk.dim(` ${path}`)); process.exit(1); } const {archivePath, buildID} = readJsonSync(path); return {archivePath, buildID}; } function saveBuildMetadata({archivePath, buildID}) { const path = join(BUILD_METADATA_TEMP_DIRECTORY, 'metadata'); if (!existsSync(BUILD_METADATA_TEMP_DIRECTORY)) { mkdirSync(BUILD_METADATA_TEMP_DIRECTORY); } writeJsonSync(path, {archivePath, buildID}, {spaces: 2}); } module.exports = { checkNPMPermissions, clear, confirm, confirmContinue, execRead, logger, readSavedBuildMetadata, saveBuildMetadata, };
21.790698
81
0.656005
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 */ // This is a host config that's used for the `react-server` 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-server` we treat host config as a module. // This file is a shim between two worlds. // // It works because the `react-server` bundle is wrapped in something like: // // module.exports = function ($$$config) { // /* renderer 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 Destination = mixed; // eslint-disable-line no-undef export opaque type PrecomputedChunk = mixed; // eslint-disable-line no-undef export opaque type Chunk = mixed; // eslint-disable-line no-undef export opaque type BinaryChunk = mixed; // eslint-disable-line no-undef export const scheduleWork = $$$config.scheduleWork; export const beginWriting = $$$config.beginWriting; export const writeChunk = $$$config.writeChunk; export const writeChunkAndReturn = $$$config.writeChunkAndReturn; export const completeWriting = $$$config.completeWriting; export const flushBuffered = $$$config.flushBuffered; export const close = $$$config.close; export const closeWithError = $$$config.closeWithError; export const stringToChunk = $$$config.stringToChunk; export const stringToPrecomputedChunk = $$$config.stringToPrecomputedChunk; export const typedArrayToBinaryChunk = $$$config.typedArrayToBinaryChunk; export const clonePrecomputedChunk = $$$config.clonePrecomputedChunk; export const byteLengthOfChunk = $$$config.byteLengthOfChunk; export const byteLengthOfBinaryChunk = $$$config.byteLengthOfBinaryChunk; export const createFastHash = $$$config.createFastHash;
40.25
76
0.757453
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 getVendorPrefixedEventName from './getVendorPrefixedEventName'; export type DOMEventName = | 'abort' | 'afterblur' // Not a real event. This is used by event experiments. // These are vendor-prefixed so you should use the exported constants instead: // 'animationiteration' | // 'animationend | // 'animationstart' | | 'beforeblur' // Not a real event. This is used by event experiments. | 'beforeinput' | 'blur' | 'canplay' | 'canplaythrough' | 'cancel' | 'change' | 'click' | 'close' | 'compositionend' | 'compositionstart' | 'compositionupdate' | 'contextmenu' | 'copy' | 'cut' | 'dblclick' | 'auxclick' | 'drag' | 'dragend' | 'dragenter' | 'dragexit' | 'dragleave' | 'dragover' | 'dragstart' | 'drop' | 'durationchange' | 'emptied' | 'encrypted' | 'ended' | 'error' | 'focus' | 'focusin' | 'focusout' | 'fullscreenchange' | 'gotpointercapture' | 'hashchange' | 'input' | 'invalid' | 'keydown' | 'keypress' | 'keyup' | 'load' | 'loadstart' | 'loadeddata' | 'loadedmetadata' | 'lostpointercapture' | 'message' | 'mousedown' | 'mouseenter' | 'mouseleave' | 'mousemove' | 'mouseout' | 'mouseover' | 'mouseup' | 'paste' | 'pause' | 'play' | 'playing' | 'pointercancel' | 'pointerdown' | 'pointerenter' | 'pointerleave' | 'pointermove' | 'pointerout' | 'pointerover' | 'pointerup' | 'popstate' | 'progress' | 'ratechange' | 'reset' | 'resize' | 'scroll' | 'scrollend' | 'seeked' | 'seeking' | 'select' | 'selectstart' | 'selectionchange' | 'stalled' | 'submit' | 'suspend' | 'textInput' // Intentionally camelCase. Non-standard. | 'timeupdate' | 'toggle' | 'touchcancel' | 'touchend' | 'touchmove' | 'touchstart' // These are vendor-prefixed so you should use the exported constants instead: // 'transitionend' | | 'volumechange' | 'waiting' | 'wheel'; export const ANIMATION_END: DOMEventName = getVendorPrefixedEventName('animationend'); export const ANIMATION_ITERATION: DOMEventName = getVendorPrefixedEventName('animationiteration'); export const ANIMATION_START: DOMEventName = getVendorPrefixedEventName('animationstart'); export const TRANSITION_END: DOMEventName = getVendorPrefixedEventName('transitionend');
19.966942
80
0.641167
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict */ import type {PublicInstance} from './ReactNativePrivateInterface'; export default function getNativeTagFromPublicInstance( publicInstance: PublicInstance, ) { return publicInstance.__nativeTag; }
23.294118
66
0.75
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 { Menu, MenuList as ReachMenuList, MenuButton, MenuItem, } from '@reach/menu-button'; import useThemeStyles from '../../useThemeStyles'; const MenuList = ({ children, ...props }: { children: React$Node, ... }): React.Node => { const style = useThemeStyles(); return ( // $FlowFixMe[cannot-spread-inexact] unsafe spread <ReachMenuList style={style} {...props}> {children} </ReachMenuList> ); }; export {MenuItem, MenuButton, MenuList, Menu};
19.194444
66
0.657025
cybersecurity-penetration-testing
'use strict'; var s; if (process.env.NODE_ENV === 'production') { s = require('./cjs/react-dom-server.edge.production.min.js'); } else { s = require('./cjs/react-dom-server.edge.development.js'); } exports.version = s.version; exports.prerender = s.prerender;
21.25
63
0.676692
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-turbopack-server.browser.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-turbopack-server.browser.development.js'); }
31.875
96
0.717557
PenetrationTestingScripts
/* global chrome */ // Firefox doesn't support ExecutionWorld.MAIN yet // https://bugzilla.mozilla.org/show_bug.cgi?id=1736575 function executeScriptForFirefoxInMainWorld({target, files}) { return chrome.scripting.executeScript({ target, func: fileNames => { function injectScriptSync(src) { let code = ''; const request = new XMLHttpRequest(); request.addEventListener('load', function () { code = this.responseText; }); request.open('GET', src, false); request.send(); const script = document.createElement('script'); script.textContent = code; // This script runs before the <head> element is created, // so we add the script to <html> instead. if (document.documentElement) { document.documentElement.appendChild(script); } if (script.parentNode) { script.parentNode.removeChild(script); } } fileNames.forEach(file => injectScriptSync(chrome.runtime.getURL(file))); }, args: [files], }); } export function executeScriptInIsolatedWorld({target, files}) { return chrome.scripting.executeScript({ target, files, world: chrome.scripting.ExecutionWorld.ISOLATED, }); } export function executeScriptInMainWorld({target, files}) { if (__IS_FIREFOX__) { return executeScriptForFirefoxInMainWorld({target, files}); } return chrome.scripting.executeScript({ target, files, world: chrome.scripting.ExecutionWorld.MAIN, }); }
26.140351
79
0.647477
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-reconciler.production.min.js'); } else { module.exports = require('./cjs/react-reconciler.development.js'); }
25.625
71
0.688679
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 */ import {parse} from '@babel/parser'; import {generateHookMap} from '../generateHookMap'; import {getHookNameForLocation} from '../getHookNameForLocation'; function expectHookMapToEqual(actual, expected) { expect(actual.names).toEqual(expected.names); const formattedMappings = []; actual.mappings.forEach(lines => { lines.forEach(segment => { const name = actual.names[segment[2]]; if (name == null) { throw new Error(`Expected to find name at position ${segment[2]}`); } formattedMappings.push(`${name} from ${segment[0]}:${segment[1]}`); }); }); expect(formattedMappings).toEqual(expected.mappings); } describe('generateHookMap', () => { it('should parse names for built-in hooks', () => { const code = ` import {useState, useContext, useMemo, useReducer} from 'react'; export function Component() { const a = useMemo(() => A); const [b, setB] = useState(0); // prettier-ignore const c = useContext(A), d = useContext(B); // eslint-disable-line one-var const [e, dispatch] = useReducer(reducer, initialState); const f = useRef(null) return a + b + c + d + e + f.current; }`; const parsed = parse(code, { sourceType: 'module', plugins: ['jsx', 'flow'], }); const hookMap = generateHookMap(parsed); expectHookMapToEqual(hookMap, { names: ['<no-hook>', 'a', 'b', 'c', 'd', 'e', 'f'], mappings: [ '<no-hook> from 1:0', 'a from 5:12', '<no-hook> from 5:28', 'b from 6:20', '<no-hook> from 6:31', 'c from 9:12', '<no-hook> from 9:25', 'd from 9:31', '<no-hook> from 9:44', 'e from 11:24', '<no-hook> from 11:57', 'f from 12:12', '<no-hook> from 12:24', ], }); expect(getHookNameForLocation({line: 1, column: 0}, hookMap)).toEqual(null); expect(getHookNameForLocation({line: 2, column: 25}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 5, column: 12}, hookMap)).toEqual('a'); expect(getHookNameForLocation({line: 5, column: 13}, hookMap)).toEqual('a'); expect(getHookNameForLocation({line: 5, column: 28}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 5, column: 29}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 6, column: 20}, hookMap)).toEqual('b'); expect(getHookNameForLocation({line: 6, column: 30}, hookMap)).toEqual('b'); expect(getHookNameForLocation({line: 6, column: 31}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 7, column: 31}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 8, column: 20}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 9, column: 12}, hookMap)).toEqual('c'); expect(getHookNameForLocation({line: 9, column: 13}, hookMap)).toEqual('c'); expect(getHookNameForLocation({line: 9, column: 25}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 9, column: 26}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 9, column: 31}, hookMap)).toEqual('d'); expect(getHookNameForLocation({line: 9, column: 32}, hookMap)).toEqual('d'); expect(getHookNameForLocation({line: 9, column: 44}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 9, column: 45}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 11, column: 24}, hookMap)).toEqual( 'e', ); expect(getHookNameForLocation({line: 11, column: 56}, hookMap)).toEqual( 'e', ); expect(getHookNameForLocation({line: 11, column: 57}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 11, column: 58}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 12, column: 12}, hookMap)).toEqual( 'f', ); expect(getHookNameForLocation({line: 12, column: 23}, hookMap)).toEqual( 'f', ); expect(getHookNameForLocation({line: 12, column: 24}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 100, column: 50}, hookMap)).toEqual( null, ); }); it('should parse names for custom hooks', () => { const code = ` import useTheme from 'useTheme'; import useValue from 'useValue'; export function Component() { const theme = useTheme(); const [val, setVal] = useValue(); return theme; }`; const parsed = parse(code, { sourceType: 'module', plugins: ['jsx', 'flow'], }); const hookMap = generateHookMap(parsed); expectHookMapToEqual(hookMap, { names: ['<no-hook>', 'theme', 'val'], mappings: [ '<no-hook> from 1:0', 'theme from 6:16', '<no-hook> from 6:26', 'val from 7:24', '<no-hook> from 7:34', ], }); expect(getHookNameForLocation({line: 1, column: 0}, hookMap)).toEqual(null); expect(getHookNameForLocation({line: 6, column: 16}, hookMap)).toEqual( 'theme', ); expect(getHookNameForLocation({line: 6, column: 26}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 7, column: 24}, hookMap)).toEqual( 'val', ); expect(getHookNameForLocation({line: 7, column: 34}, hookMap)).toEqual( null, ); }); it('should parse names for nested hook calls', () => { const code = ` import {useMemo, useState} from 'react'; export function Component() { const InnerComponent = useMemo(() => () => { const [state, setState] = useState(0); return state; }); return null; }`; const parsed = parse(code, { sourceType: 'module', plugins: ['jsx', 'flow'], }); const hookMap = generateHookMap(parsed); expectHookMapToEqual(hookMap, { names: ['<no-hook>', 'InnerComponent', 'state'], mappings: [ '<no-hook> from 1:0', 'InnerComponent from 5:25', 'state from 6:30', 'InnerComponent from 6:41', '<no-hook> from 9:4', ], }); expect(getHookNameForLocation({line: 1, column: 0}, hookMap)).toEqual(null); expect(getHookNameForLocation({line: 5, column: 25}, hookMap)).toEqual( 'InnerComponent', ); expect(getHookNameForLocation({line: 6, column: 30}, hookMap)).toEqual( 'state', ); expect(getHookNameForLocation({line: 6, column: 40}, hookMap)).toEqual( 'state', ); expect(getHookNameForLocation({line: 6, column: 41}, hookMap)).toEqual( 'InnerComponent', ); expect(getHookNameForLocation({line: 9, column: 4}, hookMap)).toEqual(null); }); it('should skip names for non-nameable hooks', () => { const code = ` import useTheme from 'useTheme'; import useValue from 'useValue'; export function Component() { const [val, setVal] = useState(0); useEffect(() => { // ... }); useLayoutEffect(() => { // ... }); return val; }`; const parsed = parse(code, { sourceType: 'module', plugins: ['jsx', 'flow'], }); const hookMap = generateHookMap(parsed); expectHookMapToEqual(hookMap, { names: ['<no-hook>', 'val'], mappings: ['<no-hook> from 1:0', 'val from 6:24', '<no-hook> from 6:35'], }); expect(getHookNameForLocation({line: 1, column: 0}, hookMap)).toEqual(null); expect(getHookNameForLocation({line: 6, column: 24}, hookMap)).toEqual( 'val', ); expect(getHookNameForLocation({line: 6, column: 35}, hookMap)).toEqual( null, ); expect(getHookNameForLocation({line: 8, column: 2}, hookMap)).toEqual(null); }); });
28.633962
80
0.604559
PenetrationTestingScripts
module.exports = require('./dist/frontend');
22
44
0.711111
Penetration_Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import { resetCurrentFiber as resetCurrentDebugFiberInDEV, setCurrentFiber as setCurrentDebugFiberInDEV, } from './ReactCurrentFiber'; import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; import {StrictLegacyMode} from './ReactTypeOfMode'; type FiberArray = Array<Fiber>; type FiberToFiberComponentsMap = Map<Fiber, FiberArray>; const ReactStrictModeWarnings = { recordUnsafeLifecycleWarnings: (fiber: Fiber, instance: any): void => {}, flushPendingUnsafeLifecycleWarnings: (): void => {}, recordLegacyContextWarning: (fiber: Fiber, instance: any): void => {}, flushLegacyContextWarning: (): void => {}, discardPendingWarnings: (): void => {}, }; if (__DEV__) { const findStrictRoot = (fiber: Fiber): Fiber | null => { let maybeStrictRoot = null; let node: null | Fiber = fiber; while (node !== null) { if (node.mode & StrictLegacyMode) { maybeStrictRoot = node; } node = node.return; } return maybeStrictRoot; }; const setToSortedString = (set: Set<string>) => { const array = []; set.forEach(value => { array.push(value); }); return array.sort().join(', '); }; let pendingComponentWillMountWarnings: Array<Fiber> = []; let pendingUNSAFE_ComponentWillMountWarnings: Array<Fiber> = []; let pendingComponentWillReceivePropsWarnings: Array<Fiber> = []; let pendingUNSAFE_ComponentWillReceivePropsWarnings: Array<Fiber> = []; let pendingComponentWillUpdateWarnings: Array<Fiber> = []; let pendingUNSAFE_ComponentWillUpdateWarnings: Array<Fiber> = []; // Tracks components we have already warned about. const didWarnAboutUnsafeLifecycles = new Set<mixed>(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = ( fiber: Fiber, instance: any, ) => { // Dedupe strategy: Warn once per component. if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { return; } if ( typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components. instance.componentWillMount.__suppressDeprecationWarning !== true ) { pendingComponentWillMountWarnings.push(fiber); } if ( fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function' ) { pendingUNSAFE_ComponentWillMountWarnings.push(fiber); } if ( typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true ) { pendingComponentWillReceivePropsWarnings.push(fiber); } if ( fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function' ) { pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); } if ( typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true ) { pendingComponentWillUpdateWarnings.push(fiber); } if ( fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function' ) { pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); } }; ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = () => { // We do an initial pass to gather component names const componentWillMountUniqueNames = new Set<string>(); if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(fiber => { componentWillMountUniqueNames.add( getComponentNameFromFiber(fiber) || 'Component', ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillMountWarnings = []; } const UNSAFE_componentWillMountUniqueNames = new Set<string>(); if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(fiber => { UNSAFE_componentWillMountUniqueNames.add( getComponentNameFromFiber(fiber) || 'Component', ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillMountWarnings = []; } const componentWillReceivePropsUniqueNames = new Set<string>(); if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(fiber => { componentWillReceivePropsUniqueNames.add( getComponentNameFromFiber(fiber) || 'Component', ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillReceivePropsWarnings = []; } const UNSAFE_componentWillReceivePropsUniqueNames = new Set<string>(); if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(fiber => { UNSAFE_componentWillReceivePropsUniqueNames.add( getComponentNameFromFiber(fiber) || 'Component', ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } const componentWillUpdateUniqueNames = new Set<string>(); if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(fiber => { componentWillUpdateUniqueNames.add( getComponentNameFromFiber(fiber) || 'Component', ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillUpdateWarnings = []; } const UNSAFE_componentWillUpdateUniqueNames = new Set<string>(); if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(fiber => { UNSAFE_componentWillUpdateUniqueNames.add( getComponentNameFromFiber(fiber) || 'Component', ); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillUpdateWarnings = []; } // Finally, we flush all the warnings // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' if (UNSAFE_componentWillMountUniqueNames.size > 0) { const sortedNames = setToSortedString( UNSAFE_componentWillMountUniqueNames, ); console.error( 'Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames, ); } if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { const sortedNames = setToSortedString( UNSAFE_componentWillReceivePropsUniqueNames, ); console.error( 'Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', sortedNames, ); } if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { const sortedNames = setToSortedString( UNSAFE_componentWillUpdateUniqueNames, ); console.error( 'Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', sortedNames, ); } if (componentWillMountUniqueNames.size > 0) { const sortedNames = setToSortedString(componentWillMountUniqueNames); console.warn( 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', sortedNames, ); } if (componentWillReceivePropsUniqueNames.size > 0) { const sortedNames = setToSortedString( componentWillReceivePropsUniqueNames, ); console.warn( 'componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', sortedNames, ); } if (componentWillUpdateUniqueNames.size > 0) { const sortedNames = setToSortedString(componentWillUpdateUniqueNames); console.warn( 'componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', sortedNames, ); } }; let pendingLegacyContextWarning: FiberToFiberComponentsMap = new Map(); // Tracks components we have already warned about. const didWarnAboutLegacyContext = new Set<mixed>(); ReactStrictModeWarnings.recordLegacyContextWarning = ( fiber: Fiber, instance: any, ) => { const strictRoot = findStrictRoot(fiber); if (strictRoot === null) { console.error( 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); return; } // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } let warningsForRoot = pendingLegacyContextWarning.get(strictRoot); if ( fiber.type.contextTypes != null || fiber.type.childContextTypes != null || (instance !== null && typeof instance.getChildContext === 'function') ) { if (warningsForRoot === undefined) { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } warningsForRoot.push(fiber); } }; ReactStrictModeWarnings.flushLegacyContextWarning = () => { ((pendingLegacyContextWarning: any): FiberToFiberComponentsMap).forEach( (fiberArray: FiberArray, strictRoot) => { if (fiberArray.length === 0) { return; } const firstFiber = fiberArray[0]; const uniqueNames = new Set<string>(); fiberArray.forEach(fiber => { uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutLegacyContext.add(fiber.type); }); const sortedNames = setToSortedString(uniqueNames); try { setCurrentDebugFiberInDEV(firstFiber); console.error( 'Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames, ); } finally { resetCurrentDebugFiberInDEV(); } }, ); }; ReactStrictModeWarnings.discardPendingWarnings = () => { pendingComponentWillMountWarnings = []; pendingUNSAFE_ComponentWillMountWarnings = []; pendingComponentWillReceivePropsWarnings = []; pendingUNSAFE_ComponentWillReceivePropsWarnings = []; pendingComponentWillUpdateWarnings = []; pendingUNSAFE_ComponentWillUpdateWarnings = []; pendingLegacyContextWarning = new Map(); }; } export default ReactStrictModeWarnings;
36.83558
114
0.673625
Effective-Python-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /************************************************************************ * This file is forked between different DevTools implementations. * It should never be imported directly! * It should always be imported from "react-devtools-feature-flags". ************************************************************************/ export const consoleManagedByDevToolsDuringStrictMode = true; export const enableLogger = false; export const enableStyleXFeatures = false; export const isInternalFacebookBuild = false; /************************************************************************ * Do not edit the code below. * It ensures this fork exports the same types as the default flags file. ************************************************************************/ import typeof * as FeatureFlagsType from './DevToolsFeatureFlags.default'; import typeof * as ExportsType from './DevToolsFeatureFlags.extension-oss'; // Flow magic to verify the exports of this file match the original version. ((((null: any): ExportsType): FeatureFlagsType): ExportsType);
39.83871
76
0.586561
owtf
/* * Copyright (c) Facebook, Inc. and its affiliates. */ // Used in next.config.js to remove the raf transitive dependency. export default window.requestAnimationFrame;
23.714286
66
0.75
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 {InternalInstance} from './renderer'; export function decorate(object: Object, attr: string, fn: Function): Function { const old = object[attr]; // $FlowFixMe[missing-this-annot] webpack config needs to be updated to allow `this` type annotations object[attr] = function (instance: InternalInstance) { return fn.call(this, old, arguments); }; return old; } export function decorateMany( source: Object, fns: {[attr: string]: Function, ...}, ): Object { const olds: {[string]: $FlowFixMe} = {}; for (const name in fns) { olds[name] = decorate(source, name, fns[name]); } return olds; } export function restoreMany(source: Object, olds: Object): void { for (const name in olds) { source[name] = olds[name]; } } // $FlowFixMe[missing-this-annot] webpack config needs to be updated to allow `this` type annotations export function forceUpdate(instance: InternalInstance): void { if (typeof instance.forceUpdate === 'function') { instance.forceUpdate(); } else if ( instance.updater != null && typeof instance.updater.enqueueForceUpdate === 'function' ) { instance.updater.enqueueForceUpdate(this, () => {}, 'forceUpdate'); } }
27.693878
103
0.683274
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/ReactReconcilerConstants';
19.615385
66
0.696629
PenTesting
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-webpack-client.browser.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-webpack-client.browser.development.js'); }
31.375
94
0.713178
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 PropTypes; let React; let ReactDOM; let ReactFeatureFlags; // TODO: Refactor this test once componentDidCatch setState is deprecated. describe('ReactLegacyErrorBoundaries', () => { let log; let BrokenConstructor; let BrokenComponentWillMount; let BrokenComponentDidMount; let BrokenComponentWillReceiveProps; let BrokenComponentWillUpdate; let BrokenComponentDidUpdate; let BrokenComponentWillUnmount; let BrokenRenderErrorBoundary; let BrokenComponentWillMountErrorBoundary; let BrokenComponentDidMountErrorBoundary; let BrokenRender; let ErrorBoundary; let BothErrorBoundaries; let ErrorMessage; let NoopErrorBoundary; let RetryErrorBoundary; let Normal; beforeEach(() => { jest.resetModules(); PropTypes = require('prop-types'); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; ReactDOM = require('react-dom'); React = require('react'); log = []; BrokenConstructor = class extends React.Component { constructor(props) { super(props); log.push('BrokenConstructor constructor [!]'); throw new Error('Hello'); } render() { log.push('BrokenConstructor render'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenConstructor componentWillMount'); } componentDidMount() { log.push('BrokenConstructor componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push('BrokenConstructor componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BrokenConstructor componentWillUpdate'); } componentDidUpdate() { log.push('BrokenConstructor componentDidUpdate'); } componentWillUnmount() { log.push('BrokenConstructor componentWillUnmount'); } }; BrokenComponentWillMount = class extends React.Component { constructor(props) { super(props); log.push('BrokenComponentWillMount constructor'); } render() { log.push('BrokenComponentWillMount render'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenComponentWillMount componentWillMount [!]'); throw new Error('Hello'); } componentDidMount() { log.push('BrokenComponentWillMount componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push('BrokenComponentWillMount componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BrokenComponentWillMount componentWillUpdate'); } componentDidUpdate() { log.push('BrokenComponentWillMount componentDidUpdate'); } componentWillUnmount() { log.push('BrokenComponentWillMount componentWillUnmount'); } }; BrokenComponentDidMount = class extends React.Component { constructor(props) { super(props); log.push('BrokenComponentDidMount constructor'); } render() { log.push('BrokenComponentDidMount render'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenComponentDidMount componentWillMount'); } componentDidMount() { log.push('BrokenComponentDidMount componentDidMount [!]'); throw new Error('Hello'); } UNSAFE_componentWillReceiveProps() { log.push('BrokenComponentDidMount componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BrokenComponentDidMount componentWillUpdate'); } componentDidUpdate() { log.push('BrokenComponentDidMount componentDidUpdate'); } componentWillUnmount() { log.push('BrokenComponentDidMount componentWillUnmount'); } }; BrokenComponentWillReceiveProps = class extends React.Component { constructor(props) { super(props); log.push('BrokenComponentWillReceiveProps constructor'); } render() { log.push('BrokenComponentWillReceiveProps render'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenComponentWillReceiveProps componentWillMount'); } componentDidMount() { log.push('BrokenComponentWillReceiveProps componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push( 'BrokenComponentWillReceiveProps componentWillReceiveProps [!]', ); throw new Error('Hello'); } UNSAFE_componentWillUpdate() { log.push('BrokenComponentWillReceiveProps componentWillUpdate'); } componentDidUpdate() { log.push('BrokenComponentWillReceiveProps componentDidUpdate'); } componentWillUnmount() { log.push('BrokenComponentWillReceiveProps componentWillUnmount'); } }; BrokenComponentWillUpdate = class extends React.Component { constructor(props) { super(props); log.push('BrokenComponentWillUpdate constructor'); } render() { log.push('BrokenComponentWillUpdate render'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenComponentWillUpdate componentWillMount'); } componentDidMount() { log.push('BrokenComponentWillUpdate componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push('BrokenComponentWillUpdate componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BrokenComponentWillUpdate componentWillUpdate [!]'); throw new Error('Hello'); } componentDidUpdate() { log.push('BrokenComponentWillUpdate componentDidUpdate'); } componentWillUnmount() { log.push('BrokenComponentWillUpdate componentWillUnmount'); } }; BrokenComponentDidUpdate = class extends React.Component { static defaultProps = { errorText: 'Hello', }; constructor(props) { super(props); log.push('BrokenComponentDidUpdate constructor'); } render() { log.push('BrokenComponentDidUpdate render'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenComponentDidUpdate componentWillMount'); } componentDidMount() { log.push('BrokenComponentDidUpdate componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push('BrokenComponentDidUpdate componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BrokenComponentDidUpdate componentWillUpdate'); } componentDidUpdate() { log.push('BrokenComponentDidUpdate componentDidUpdate [!]'); throw new Error(this.props.errorText); } componentWillUnmount() { log.push('BrokenComponentDidUpdate componentWillUnmount'); } }; BrokenComponentWillUnmount = class extends React.Component { static defaultProps = { errorText: 'Hello', }; constructor(props) { super(props); log.push('BrokenComponentWillUnmount constructor'); } render() { log.push('BrokenComponentWillUnmount render'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenComponentWillUnmount componentWillMount'); } componentDidMount() { log.push('BrokenComponentWillUnmount componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push('BrokenComponentWillUnmount componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BrokenComponentWillUnmount componentWillUpdate'); } componentDidUpdate() { log.push('BrokenComponentWillUnmount componentDidUpdate'); } componentWillUnmount() { log.push('BrokenComponentWillUnmount componentWillUnmount [!]'); throw new Error(this.props.errorText); } }; BrokenComponentWillMountErrorBoundary = class extends React.Component { constructor(props) { super(props); this.state = {error: null}; log.push('BrokenComponentWillMountErrorBoundary constructor'); } render() { if (this.state.error) { log.push('BrokenComponentWillMountErrorBoundary render error'); return <div>Caught an error: {this.state.error.message}.</div>; } log.push('BrokenComponentWillMountErrorBoundary render success'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push( 'BrokenComponentWillMountErrorBoundary componentWillMount [!]', ); throw new Error('Hello'); } componentDidMount() { log.push('BrokenComponentWillMountErrorBoundary componentDidMount'); } componentWillUnmount() { log.push('BrokenComponentWillMountErrorBoundary componentWillUnmount'); } componentDidCatch(error) { log.push('BrokenComponentWillMountErrorBoundary componentDidCatch'); this.setState({error}); } }; BrokenComponentDidMountErrorBoundary = class extends React.Component { constructor(props) { super(props); this.state = {error: null}; log.push('BrokenComponentDidMountErrorBoundary constructor'); } render() { if (this.state.error) { log.push('BrokenComponentDidMountErrorBoundary render error'); return <div>Caught an error: {this.state.error.message}.</div>; } log.push('BrokenComponentDidMountErrorBoundary render success'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenComponentDidMountErrorBoundary componentWillMount'); } componentDidMount() { log.push('BrokenComponentDidMountErrorBoundary componentDidMount [!]'); throw new Error('Hello'); } componentWillUnmount() { log.push('BrokenComponentDidMountErrorBoundary componentWillUnmount'); } componentDidCatch(error) { log.push('BrokenComponentDidMountErrorBoundary componentDidCatch'); this.setState({error}); } }; BrokenRenderErrorBoundary = class extends React.Component { constructor(props) { super(props); this.state = {error: null}; log.push('BrokenRenderErrorBoundary constructor'); } render() { if (this.state.error) { log.push('BrokenRenderErrorBoundary render error [!]'); throw new Error('Hello'); } log.push('BrokenRenderErrorBoundary render success'); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push('BrokenRenderErrorBoundary componentWillMount'); } componentDidMount() { log.push('BrokenRenderErrorBoundary componentDidMount'); } componentWillUnmount() { log.push('BrokenRenderErrorBoundary componentWillUnmount'); } componentDidCatch(error) { log.push('BrokenRenderErrorBoundary componentDidCatch'); this.setState({error}); } }; BrokenRender = class extends React.Component { constructor(props) { super(props); log.push('BrokenRender constructor'); } render() { log.push('BrokenRender render [!]'); throw new Error('Hello'); } UNSAFE_componentWillMount() { log.push('BrokenRender componentWillMount'); } componentDidMount() { log.push('BrokenRender componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push('BrokenRender componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BrokenRender componentWillUpdate'); } componentDidUpdate() { log.push('BrokenRender componentDidUpdate'); } componentWillUnmount() { log.push('BrokenRender componentWillUnmount'); } }; NoopErrorBoundary = class extends React.Component { constructor(props) { super(props); log.push('NoopErrorBoundary constructor'); } render() { log.push('NoopErrorBoundary render'); return <BrokenRender />; } UNSAFE_componentWillMount() { log.push('NoopErrorBoundary componentWillMount'); } componentDidMount() { log.push('NoopErrorBoundary componentDidMount'); } componentWillUnmount() { log.push('NoopErrorBoundary componentWillUnmount'); } componentDidCatch() { log.push('NoopErrorBoundary componentDidCatch'); } }; Normal = class extends React.Component { static defaultProps = { logName: 'Normal', }; constructor(props) { super(props); log.push(`${this.props.logName} constructor`); } render() { log.push(`${this.props.logName} render`); return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { log.push(`${this.props.logName} componentWillMount`); } componentDidMount() { log.push(`${this.props.logName} componentDidMount`); } UNSAFE_componentWillReceiveProps() { log.push(`${this.props.logName} componentWillReceiveProps`); } UNSAFE_componentWillUpdate() { log.push(`${this.props.logName} componentWillUpdate`); } componentDidUpdate() { log.push(`${this.props.logName} componentDidUpdate`); } componentWillUnmount() { log.push(`${this.props.logName} componentWillUnmount`); } }; ErrorBoundary = class extends React.Component { constructor(props) { super(props); this.state = {error: null}; log.push(`${this.props.logName} constructor`); } render() { if (this.state.error && !this.props.forceRetry) { log.push(`${this.props.logName} render error`); return this.props.renderError(this.state.error, this.props); } log.push(`${this.props.logName} render success`); return <div>{this.props.children}</div>; } componentDidCatch(error) { log.push(`${this.props.logName} componentDidCatch`); this.setState({error}); } UNSAFE_componentWillMount() { log.push(`${this.props.logName} componentWillMount`); } componentDidMount() { log.push(`${this.props.logName} componentDidMount`); } UNSAFE_componentWillReceiveProps() { log.push(`${this.props.logName} componentWillReceiveProps`); } UNSAFE_componentWillUpdate() { log.push(`${this.props.logName} componentWillUpdate`); } componentDidUpdate() { log.push(`${this.props.logName} componentDidUpdate`); } componentWillUnmount() { log.push(`${this.props.logName} componentWillUnmount`); } }; ErrorBoundary.defaultProps = { logName: 'ErrorBoundary', renderError(error, props) { return ( <div ref={props.errorMessageRef}> Caught an error: {error.message}. </div> ); }, }; BothErrorBoundaries = class extends React.Component { constructor(props) { super(props); this.state = {error: null}; log.push('BothErrorBoundaries constructor'); } static getDerivedStateFromError(error) { log.push('BothErrorBoundaries static getDerivedStateFromError'); return {error}; } render() { if (this.state.error) { log.push('BothErrorBoundaries render error'); return <div>Caught an error: {this.state.error.message}.</div>; } log.push('BothErrorBoundaries render success'); return <div>{this.props.children}</div>; } componentDidCatch(error) { log.push('BothErrorBoundaries componentDidCatch'); this.setState({error}); } UNSAFE_componentWillMount() { log.push('BothErrorBoundaries componentWillMount'); } componentDidMount() { log.push('BothErrorBoundaries componentDidMount'); } UNSAFE_componentWillReceiveProps() { log.push('BothErrorBoundaries componentWillReceiveProps'); } UNSAFE_componentWillUpdate() { log.push('BothErrorBoundaries componentWillUpdate'); } componentDidUpdate() { log.push('BothErrorBoundaries componentDidUpdate'); } componentWillUnmount() { log.push('BothErrorBoundaries componentWillUnmount'); } }; RetryErrorBoundary = class extends React.Component { constructor(props) { super(props); log.push('RetryErrorBoundary constructor'); } render() { log.push('RetryErrorBoundary render'); return <BrokenRender />; } UNSAFE_componentWillMount() { log.push('RetryErrorBoundary componentWillMount'); } componentDidMount() { log.push('RetryErrorBoundary componentDidMount'); } componentWillUnmount() { log.push('RetryErrorBoundary componentWillUnmount'); } componentDidCatch(error) { log.push('RetryErrorBoundary componentDidCatch [!]'); // In Fiber, calling setState() (and failing) is treated as a rethrow. this.setState({}); } }; ErrorMessage = class extends React.Component { constructor(props) { super(props); log.push('ErrorMessage constructor'); } UNSAFE_componentWillMount() { log.push('ErrorMessage componentWillMount'); } componentDidMount() { log.push('ErrorMessage componentDidMount'); } componentWillUnmount() { log.push('ErrorMessage componentWillUnmount'); } render() { log.push('ErrorMessage render'); return <div>Caught an error: {this.props.message}.</div>; } }; }); afterEach(() => { jest.restoreAllMocks(); }); it('does not swallow exceptions on mounting without boundaries', () => { let container = document.createElement('div'); expect(() => { ReactDOM.render(<BrokenRender />, container); }).toThrow('Hello'); container = document.createElement('div'); expect(() => { ReactDOM.render(<BrokenComponentWillMount />, container); }).toThrow('Hello'); container = document.createElement('div'); expect(() => { ReactDOM.render(<BrokenComponentDidMount />, container); }).toThrow('Hello'); }); it('does not swallow exceptions on updating without boundaries', () => { let container = document.createElement('div'); ReactDOM.render(<BrokenComponentWillUpdate />, container); expect(() => { ReactDOM.render(<BrokenComponentWillUpdate />, container); }).toThrow('Hello'); container = document.createElement('div'); ReactDOM.render(<BrokenComponentWillReceiveProps />, container); expect(() => { ReactDOM.render(<BrokenComponentWillReceiveProps />, container); }).toThrow('Hello'); container = document.createElement('div'); ReactDOM.render(<BrokenComponentDidUpdate />, container); expect(() => { ReactDOM.render(<BrokenComponentDidUpdate />, container); }).toThrow('Hello'); }); it('does not swallow exceptions on unmounting without boundaries', () => { const container = document.createElement('div'); ReactDOM.render(<BrokenComponentWillUnmount />, container); expect(() => { ReactDOM.unmountComponentAtNode(container); }).toThrow('Hello'); }); it('prevents errors from leaking into other roots', () => { const container1 = document.createElement('div'); const container2 = document.createElement('div'); const container3 = document.createElement('div'); ReactDOM.render(<span>Before 1</span>, container1); expect(() => { ReactDOM.render(<BrokenRender />, container2); }).toThrow('Hello'); ReactDOM.render( <ErrorBoundary> <BrokenRender /> </ErrorBoundary>, container3, ); expect(container1.firstChild.textContent).toBe('Before 1'); expect(container2.firstChild).toBe(null); expect(container3.firstChild.textContent).toBe('Caught an error: Hello.'); ReactDOM.render(<span>After 1</span>, container1); ReactDOM.render(<span>After 2</span>, container2); ReactDOM.render( <ErrorBoundary forceRetry={true}>After 3</ErrorBoundary>, container3, ); expect(container1.firstChild.textContent).toBe('After 1'); expect(container2.firstChild.textContent).toBe('After 2'); expect(container3.firstChild.textContent).toBe('After 3'); ReactDOM.unmountComponentAtNode(container1); ReactDOM.unmountComponentAtNode(container2); ReactDOM.unmountComponentAtNode(container3); expect(container1.firstChild).toBe(null); expect(container2.firstChild).toBe(null); expect(container3.firstChild).toBe(null); }); it('logs a single error using both error boundaries', () => { const container = document.createElement('div'); spyOnDev(console, 'error'); ReactDOM.render( <BothErrorBoundaries> <BrokenRender /> </BothErrorBoundaries>, container, ); if (__DEV__) { expect(console.error).toHaveBeenCalledTimes(2); expect(console.error.mock.calls[0][0]).toContain( 'ReactDOM.render is no longer supported', ); expect(console.error.mock.calls[1][0]).toContain( 'The above error occurred in the <BrokenRender> component:', ); } expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'BothErrorBoundaries constructor', 'BothErrorBoundaries componentWillMount', 'BothErrorBoundaries render success', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // Both getDerivedStateFromError and componentDidCatch should be called 'BothErrorBoundaries static getDerivedStateFromError', 'BothErrorBoundaries componentWillMount', 'BothErrorBoundaries render error', // Fiber mounts with null children before capturing error 'BothErrorBoundaries componentDidMount', // Catch and render an error message 'BothErrorBoundaries componentDidCatch', 'BothErrorBoundaries componentWillUpdate', 'BothErrorBoundaries render error', 'BothErrorBoundaries componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['BothErrorBoundaries componentWillUnmount']); }); it('renders an error state if child throws in render', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenRender /> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // Fiber mounts with null children before capturing error 'ErrorBoundary componentDidMount', // Catch and render an error message 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('renders an error state if child throws in constructor', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenConstructor /> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenConstructor constructor [!]', // Fiber mounts with null children before capturing error 'ErrorBoundary componentDidMount', // Catch and render an error message 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('renders an error state if child throws in componentWillMount', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenComponentWillMount /> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenComponentWillMount constructor', 'BrokenComponentWillMount componentWillMount [!]', 'ErrorBoundary componentDidMount', 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); // @gate !disableLegacyContext || !__DEV__ it('renders an error state if context provider throws in componentWillMount', () => { class BrokenComponentWillMountWithContext extends React.Component { static childContextTypes = {foo: PropTypes.number}; getChildContext() { return {foo: 42}; } render() { return <div>{this.props.children}</div>; } UNSAFE_componentWillMount() { throw new Error('Hello'); } } const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenComponentWillMountWithContext /> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); }); if (!require('shared/ReactFeatureFlags').disableModulePatternComponents) { it('renders an error state if module-style context provider throws in componentWillMount', () => { function BrokenComponentWillMountWithContext() { return { getChildContext() { return {foo: 42}; }, render() { return <div>{this.props.children}</div>; }, UNSAFE_componentWillMount() { throw new Error('Hello'); }, }; } BrokenComponentWillMountWithContext.childContextTypes = { foo: PropTypes.number, }; const container = document.createElement('div'); expect(() => ReactDOM.render( <ErrorBoundary> <BrokenComponentWillMountWithContext /> </ErrorBoundary>, container, ), ).toErrorDev( 'Warning: The <BrokenComponentWillMountWithContext /> component appears to be a function component that ' + 'returns a class instance. ' + 'Change BrokenComponentWillMountWithContext to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + '`BrokenComponentWillMountWithContext.prototype = React.Component.prototype`. ' + "Don't use an arrow function since it cannot be called with `new` by React.", ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); }); } it('mounts the error message if mounting fails', () => { function renderError(error) { return <ErrorMessage message={error.message} />; } const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary renderError={renderError}> <BrokenRender /> </ErrorBoundary>, container, ); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', 'ErrorBoundary componentDidMount', 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorMessage constructor', 'ErrorMessage componentWillMount', 'ErrorMessage render', 'ErrorMessage componentDidMount', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual([ 'ErrorBoundary componentWillUnmount', 'ErrorMessage componentWillUnmount', ]); }); it('propagates errors on retry on mounting', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <RetryErrorBoundary> <BrokenRender /> </RetryErrorBoundary> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'RetryErrorBoundary constructor', 'RetryErrorBoundary componentWillMount', 'RetryErrorBoundary render', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // In Fiber, failed error boundaries render null before attempting to recover 'RetryErrorBoundary componentDidMount', 'RetryErrorBoundary componentDidCatch [!]', 'ErrorBoundary componentDidMount', // Retry 'RetryErrorBoundary render', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // This time, the error propagates to the higher boundary 'RetryErrorBoundary componentWillUnmount', 'ErrorBoundary componentDidCatch', // Render the error 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('propagates errors inside boundary during componentWillMount', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenComponentWillMountErrorBoundary /> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenComponentWillMountErrorBoundary constructor', 'BrokenComponentWillMountErrorBoundary componentWillMount [!]', // The error propagates to the higher boundary 'ErrorBoundary componentDidMount', 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('propagates errors inside boundary while rendering error state', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenRenderErrorBoundary> <BrokenRender /> </BrokenRenderErrorBoundary> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenRenderErrorBoundary constructor', 'BrokenRenderErrorBoundary componentWillMount', 'BrokenRenderErrorBoundary render success', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // The first error boundary catches the error // It adjusts state but throws displaying the message // Finish mounting with null children 'BrokenRenderErrorBoundary componentDidMount', // Attempt to handle the error 'BrokenRenderErrorBoundary componentDidCatch', 'ErrorBoundary componentDidMount', 'BrokenRenderErrorBoundary render error [!]', // Boundary fails with new error, propagate to next boundary 'BrokenRenderErrorBoundary componentWillUnmount', // Attempt to handle the error again 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('does not call componentWillUnmount when aborting initial mount', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal /> <BrokenRender /> <Normal /> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', // Render first child 'Normal constructor', 'Normal componentWillMount', 'Normal render', // Render second child (it throws) 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // Skip the remaining siblings // Finish mounting with null children 'ErrorBoundary componentDidMount', // Handle the error 'ErrorBoundary componentDidCatch', // Render the error message 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('resets callback refs if mounting aborts', () => { function childRef(x) { log.push('Child ref is set to ' + x); } function errorMessageRef(x) { log.push('Error message ref is set to ' + x); } const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary errorMessageRef={errorMessageRef}> <div ref={childRef} /> <BrokenRender /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // Handle error: // Finish mounting with null children 'ErrorBoundary componentDidMount', // Handle the error 'ErrorBoundary componentDidCatch', // Render the error message 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'Error message ref is set to [object HTMLDivElement]', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual([ 'ErrorBoundary componentWillUnmount', 'Error message ref is set to null', ]); }); it('resets object refs if mounting aborts', () => { const childRef = React.createRef(); const errorMessageRef = React.createRef(); const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary errorMessageRef={errorMessageRef}> <div ref={childRef} /> <BrokenRender /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // Handle error: // Finish mounting with null children 'ErrorBoundary componentDidMount', // Handle the error 'ErrorBoundary componentDidCatch', // Render the error message 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); expect(errorMessageRef.current.toString()).toEqual( '[object HTMLDivElement]', ); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); expect(errorMessageRef.current).toEqual(null); }); it('successfully mounts if no error occurs', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <div>Mounted successfully.</div> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Mounted successfully.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'ErrorBoundary componentDidMount', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches if child throws in constructor during update', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <Normal /> <Normal logName="Normal2" /> <BrokenConstructor /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', 'Normal componentWillReceiveProps', 'Normal componentWillUpdate', 'Normal render', // Normal2 will attempt to mount: 'Normal2 constructor', 'Normal2 componentWillMount', 'Normal2 render', // BrokenConstructor will abort rendering: 'BrokenConstructor constructor [!]', // Finish updating with null children 'Normal componentWillUnmount', 'ErrorBoundary componentDidUpdate', // Handle the error 'ErrorBoundary componentDidCatch', // Render the error message 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches if child throws in componentWillMount during update', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <Normal /> <Normal logName="Normal2" /> <BrokenComponentWillMount /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', 'Normal componentWillReceiveProps', 'Normal componentWillUpdate', 'Normal render', // Normal2 will attempt to mount: 'Normal2 constructor', 'Normal2 componentWillMount', 'Normal2 render', // BrokenComponentWillMount will abort rendering: 'BrokenComponentWillMount constructor', 'BrokenComponentWillMount componentWillMount [!]', // Finish updating with null children 'Normal componentWillUnmount', 'ErrorBoundary componentDidUpdate', // Handle the error 'ErrorBoundary componentDidCatch', // Render the error message 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches if child throws in componentWillReceiveProps during update', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal /> <BrokenComponentWillReceiveProps /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <Normal /> <BrokenComponentWillReceiveProps /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', 'Normal componentWillReceiveProps', 'Normal componentWillUpdate', 'Normal render', // BrokenComponentWillReceiveProps will abort rendering: 'BrokenComponentWillReceiveProps componentWillReceiveProps [!]', // Finish updating with null children 'Normal componentWillUnmount', 'BrokenComponentWillReceiveProps componentWillUnmount', 'ErrorBoundary componentDidUpdate', // Handle the error 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches if child throws in componentWillUpdate during update', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal /> <BrokenComponentWillUpdate /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <Normal /> <BrokenComponentWillUpdate /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', 'Normal componentWillReceiveProps', 'Normal componentWillUpdate', 'Normal render', // BrokenComponentWillUpdate will abort rendering: 'BrokenComponentWillUpdate componentWillReceiveProps', 'BrokenComponentWillUpdate componentWillUpdate [!]', // Finish updating with null children 'Normal componentWillUnmount', 'BrokenComponentWillUpdate componentWillUnmount', 'ErrorBoundary componentDidUpdate', // Handle the error 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches if child throws in render during update', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <Normal /> <Normal logName="Normal2" /> <BrokenRender /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', 'Normal componentWillReceiveProps', 'Normal componentWillUpdate', 'Normal render', // Normal2 will attempt to mount: 'Normal2 constructor', 'Normal2 componentWillMount', 'Normal2 render', // BrokenRender will abort rendering: 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // Finish updating with null children 'Normal componentWillUnmount', 'ErrorBoundary componentDidUpdate', // Handle the error 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('keeps refs up-to-date during updates', () => { function child1Ref(x) { log.push('Child1 ref is set to ' + x); } function child2Ref(x) { log.push('Child2 ref is set to ' + x); } function errorMessageRef(x) { log.push('Error message ref is set to ' + x); } const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary errorMessageRef={errorMessageRef}> <div ref={child1Ref} /> </ErrorBoundary>, container, ); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'Child1 ref is set to [object HTMLDivElement]', 'ErrorBoundary componentDidMount', ]); log.length = 0; ReactDOM.render( <ErrorBoundary errorMessageRef={errorMessageRef}> <div ref={child1Ref} /> <div ref={child2Ref} /> <BrokenRender /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', // BrokenRender will abort rendering: 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // Finish updating with null children 'Child1 ref is set to null', 'ErrorBoundary componentDidUpdate', // Handle the error 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'Error message ref is set to [object HTMLDivElement]', // Child2 ref is never set because its mounting aborted 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual([ 'ErrorBoundary componentWillUnmount', 'Error message ref is set to null', ]); }); it('recovers from componentWillUnmount errors on update', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenComponentWillUnmount /> <BrokenComponentWillUnmount /> <Normal /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <BrokenComponentWillUnmount /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', // Update existing child: 'BrokenComponentWillUnmount componentWillReceiveProps', 'BrokenComponentWillUnmount componentWillUpdate', 'BrokenComponentWillUnmount render', // Unmounting throws: 'BrokenComponentWillUnmount componentWillUnmount [!]', // Fiber proceeds with lifecycles despite errors 'Normal componentWillUnmount', // The components have updated in this phase 'BrokenComponentWillUnmount componentDidUpdate', 'ErrorBoundary componentDidUpdate', // Now that commit phase is done, Fiber unmounts the boundary's children 'BrokenComponentWillUnmount componentWillUnmount [!]', 'ErrorBoundary componentDidCatch', // The initial render was aborted, so // Fiber retries from the root. 'ErrorBoundary componentWillUpdate', 'ErrorBoundary componentDidUpdate', // The second willUnmount error should be captured and logged, too. 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', // Render an error now (stack will do it later) 'ErrorBoundary render error', // Attempt to unmount previous child: // Done 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('recovers from nested componentWillUnmount errors on update', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal> <BrokenComponentWillUnmount /> </Normal> <BrokenComponentWillUnmount /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <Normal> <BrokenComponentWillUnmount /> </Normal> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', // Update existing children: 'Normal componentWillReceiveProps', 'Normal componentWillUpdate', 'Normal render', 'BrokenComponentWillUnmount componentWillReceiveProps', 'BrokenComponentWillUnmount componentWillUpdate', 'BrokenComponentWillUnmount render', // Unmounting throws: 'BrokenComponentWillUnmount componentWillUnmount [!]', // Fiber proceeds with lifecycles despite errors 'BrokenComponentWillUnmount componentDidUpdate', 'Normal componentDidUpdate', 'ErrorBoundary componentDidUpdate', 'Normal componentWillUnmount', 'BrokenComponentWillUnmount componentWillUnmount [!]', // Now that commit phase is done, Fiber handles errors 'ErrorBoundary componentDidCatch', // The initial render was aborted, so // Fiber retries from the root. 'ErrorBoundary componentWillUpdate', 'ErrorBoundary componentDidUpdate', // The second willUnmount error should be captured and logged, too. 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', // Render an error now (stack will do it later) 'ErrorBoundary render error', // Done 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('picks the right boundary when handling unmounting errors', () => { function renderInnerError(error) { return <div>Caught an inner error: {error.message}.</div>; } function renderOuterError(error) { return <div>Caught an outer error: {error.message}.</div>; } const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary logName="OuterErrorBoundary" renderError={renderOuterError}> <ErrorBoundary logName="InnerErrorBoundary" renderError={renderInnerError}> <BrokenComponentWillUnmount /> </ErrorBoundary> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary logName="OuterErrorBoundary" renderError={renderOuterError}> <ErrorBoundary logName="InnerErrorBoundary" renderError={renderInnerError} /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an inner error: Hello.'); expect(log).toEqual([ // Update outer boundary 'OuterErrorBoundary componentWillReceiveProps', 'OuterErrorBoundary componentWillUpdate', 'OuterErrorBoundary render success', // Update inner boundary 'InnerErrorBoundary componentWillReceiveProps', 'InnerErrorBoundary componentWillUpdate', 'InnerErrorBoundary render success', // Try unmounting child 'BrokenComponentWillUnmount componentWillUnmount [!]', // Fiber proceeds with lifecycles despite errors // Inner and outer boundaries have updated in this phase 'InnerErrorBoundary componentDidUpdate', 'OuterErrorBoundary componentDidUpdate', // Now that commit phase is done, Fiber handles errors // Only inner boundary receives the error: 'InnerErrorBoundary componentDidCatch', 'InnerErrorBoundary componentWillUpdate', // Render an error now 'InnerErrorBoundary render error', // In Fiber, this was a local update to the // inner boundary so only its hook fires 'InnerErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual([ 'OuterErrorBoundary componentWillUnmount', 'InnerErrorBoundary componentWillUnmount', ]); }); it('can recover from error state', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenRender /> </ErrorBoundary>, container, ); ReactDOM.render( <ErrorBoundary> <Normal /> </ErrorBoundary>, container, ); // Error boundary doesn't retry by itself: expect(container.textContent).toBe('Caught an error: Hello.'); // Force the success path: log.length = 0; ReactDOM.render( <ErrorBoundary forceRetry={true}> <Normal /> </ErrorBoundary>, container, ); expect(container.textContent).not.toContain('Caught an error'); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', // Mount children: 'Normal constructor', 'Normal componentWillMount', 'Normal render', // Finalize updates: 'Normal componentDidMount', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual([ 'ErrorBoundary componentWillUnmount', 'Normal componentWillUnmount', ]); }); it('can update multiple times in error state', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenRender /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); ReactDOM.render( <ErrorBoundary> <BrokenRender /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); ReactDOM.render(<div>Other screen</div>, container); expect(container.textContent).toBe('Other screen'); ReactDOM.unmountComponentAtNode(container); }); it("doesn't get into inconsistent state during removals", () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Normal /> <BrokenComponentWillUnmount /> <Normal /> </ErrorBoundary>, container, ); ReactDOM.render(<ErrorBoundary />, container); expect(container.textContent).toBe('Caught an error: Hello.'); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it("doesn't get into inconsistent state during additions", () => { const container = document.createElement('div'); ReactDOM.render(<ErrorBoundary />, container); ReactDOM.render( <ErrorBoundary> <Normal /> <BrokenRender /> <Normal /> </ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it("doesn't get into inconsistent state during reorders", () => { function getAMixOfNormalAndBrokenRenderElements() { const elements = []; for (let i = 0; i < 100; i++) { elements.push(<Normal key={i} />); } elements.push(<MaybeBrokenRender key={100} />); let currentIndex = elements.length; while (0 !== currentIndex) { const randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; const temporaryValue = elements[currentIndex]; elements[currentIndex] = elements[randomIndex]; elements[randomIndex] = temporaryValue; } return elements; } class MaybeBrokenRender extends React.Component { render() { if (fail) { throw new Error('Hello'); } return <div>{this.props.children}</div>; } } let fail = false; const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary>{getAMixOfNormalAndBrokenRenderElements()}</ErrorBoundary>, container, ); expect(container.textContent).not.toContain('Caught an error'); fail = true; ReactDOM.render( <ErrorBoundary>{getAMixOfNormalAndBrokenRenderElements()}</ErrorBoundary>, container, ); expect(container.textContent).toBe('Caught an error: Hello.'); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches errors originating downstream', () => { let fail = false; class Stateful extends React.Component { state = {shouldThrow: false}; render() { if (fail) { log.push('Stateful render [!]'); throw new Error('Hello'); } return <div>{this.props.children}</div>; } } let statefulInst; const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <Stateful ref={inst => (statefulInst = inst)} /> </ErrorBoundary>, container, ); log.length = 0; expect(() => { fail = true; statefulInst.forceUpdate(); }).not.toThrow(); expect(log).toEqual([ 'Stateful render [!]', 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches errors in componentDidMount', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenComponentWillUnmount> <Normal /> </BrokenComponentWillUnmount> <BrokenComponentDidMount /> <Normal logName="LastChild" /> </ErrorBoundary>, container, ); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenComponentWillUnmount constructor', 'BrokenComponentWillUnmount componentWillMount', 'BrokenComponentWillUnmount render', 'Normal constructor', 'Normal componentWillMount', 'Normal render', 'BrokenComponentDidMount constructor', 'BrokenComponentDidMount componentWillMount', 'BrokenComponentDidMount render', 'LastChild constructor', 'LastChild componentWillMount', 'LastChild render', // Start flushing didMount queue 'Normal componentDidMount', 'BrokenComponentWillUnmount componentDidMount', 'BrokenComponentDidMount componentDidMount [!]', // Continue despite the error 'LastChild componentDidMount', 'ErrorBoundary componentDidMount', // Now we are ready to handle the error // Safely unmount every child 'BrokenComponentWillUnmount componentWillUnmount [!]', // Continue unmounting safely despite any errors 'Normal componentWillUnmount', 'BrokenComponentDidMount componentWillUnmount', 'LastChild componentWillUnmount', // Handle the error 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', // The willUnmount error should be captured and logged, too. 'ErrorBoundary componentDidUpdate', 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', // The update has finished 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('catches errors in componentDidUpdate', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenComponentDidUpdate /> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary> <BrokenComponentDidUpdate /> </ErrorBoundary>, container, ); expect(log).toEqual([ 'ErrorBoundary componentWillReceiveProps', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render success', 'BrokenComponentDidUpdate componentWillReceiveProps', 'BrokenComponentDidUpdate componentWillUpdate', 'BrokenComponentDidUpdate render', // All lifecycles run 'BrokenComponentDidUpdate componentDidUpdate [!]', 'ErrorBoundary componentDidUpdate', 'BrokenComponentDidUpdate componentWillUnmount', // Then, error is handled 'ErrorBoundary componentDidCatch', 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('propagates errors inside boundary during componentDidMount', () => { const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary> <BrokenComponentDidMountErrorBoundary renderError={error => ( <div>We should never catch our own error: {error.message}.</div> )} /> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe('Caught an error: Hello.'); expect(log).toEqual([ 'ErrorBoundary constructor', 'ErrorBoundary componentWillMount', 'ErrorBoundary render success', 'BrokenComponentDidMountErrorBoundary constructor', 'BrokenComponentDidMountErrorBoundary componentWillMount', 'BrokenComponentDidMountErrorBoundary render success', 'BrokenComponentDidMountErrorBoundary componentDidMount [!]', // Fiber proceeds with the hooks 'ErrorBoundary componentDidMount', 'BrokenComponentDidMountErrorBoundary componentWillUnmount', // The error propagates to the higher boundary 'ErrorBoundary componentDidCatch', // Fiber retries from the root 'ErrorBoundary componentWillUpdate', 'ErrorBoundary render error', 'ErrorBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['ErrorBoundary componentWillUnmount']); }); it('calls componentDidCatch for each error that is captured', () => { function renderUnmountError(error) { return <div>Caught an unmounting error: {error.message}.</div>; } function renderUpdateError(error) { return <div>Caught an updating error: {error.message}.</div>; } const container = document.createElement('div'); ReactDOM.render( <ErrorBoundary logName="OuterErrorBoundary"> <ErrorBoundary logName="InnerUnmountBoundary" renderError={renderUnmountError}> <BrokenComponentWillUnmount errorText="E1" /> <BrokenComponentWillUnmount errorText="E2" /> </ErrorBoundary> <ErrorBoundary logName="InnerUpdateBoundary" renderError={renderUpdateError}> <BrokenComponentDidUpdate errorText="E3" /> <BrokenComponentDidUpdate errorText="E4" /> </ErrorBoundary> </ErrorBoundary>, container, ); log.length = 0; ReactDOM.render( <ErrorBoundary logName="OuterErrorBoundary"> <ErrorBoundary logName="InnerUnmountBoundary" renderError={renderUnmountError} /> <ErrorBoundary logName="InnerUpdateBoundary" renderError={renderUpdateError}> <BrokenComponentDidUpdate errorText="E3" /> <BrokenComponentDidUpdate errorText="E4" /> </ErrorBoundary> </ErrorBoundary>, container, ); expect(container.firstChild.textContent).toBe( 'Caught an unmounting error: E2.' + 'Caught an updating error: E4.', ); expect(log).toEqual([ // Begin update phase 'OuterErrorBoundary componentWillReceiveProps', 'OuterErrorBoundary componentWillUpdate', 'OuterErrorBoundary render success', 'InnerUnmountBoundary componentWillReceiveProps', 'InnerUnmountBoundary componentWillUpdate', 'InnerUnmountBoundary render success', 'InnerUpdateBoundary componentWillReceiveProps', 'InnerUpdateBoundary componentWillUpdate', 'InnerUpdateBoundary render success', // First come the updates 'BrokenComponentDidUpdate componentWillReceiveProps', 'BrokenComponentDidUpdate componentWillUpdate', 'BrokenComponentDidUpdate render', 'BrokenComponentDidUpdate componentWillReceiveProps', 'BrokenComponentDidUpdate componentWillUpdate', 'BrokenComponentDidUpdate render', // We're in commit phase now, deleting 'BrokenComponentWillUnmount componentWillUnmount [!]', 'BrokenComponentWillUnmount componentWillUnmount [!]', // Continue despite errors, handle them after commit is done 'InnerUnmountBoundary componentDidUpdate', // We're still in commit phase, now calling update lifecycles 'BrokenComponentDidUpdate componentDidUpdate [!]', // Again, continue despite errors, we'll handle them later 'BrokenComponentDidUpdate componentDidUpdate [!]', 'InnerUpdateBoundary componentDidUpdate', 'OuterErrorBoundary componentDidUpdate', // After the commit phase, attempt to recover from any errors that // were captured 'BrokenComponentDidUpdate componentWillUnmount', 'BrokenComponentDidUpdate componentWillUnmount', 'InnerUnmountBoundary componentDidCatch', 'InnerUnmountBoundary componentDidCatch', 'InnerUpdateBoundary componentDidCatch', 'InnerUpdateBoundary componentDidCatch', 'InnerUnmountBoundary componentWillUpdate', 'InnerUnmountBoundary render error', 'InnerUpdateBoundary componentWillUpdate', 'InnerUpdateBoundary render error', 'InnerUnmountBoundary componentDidUpdate', 'InnerUpdateBoundary componentDidUpdate', ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual([ 'OuterErrorBoundary componentWillUnmount', 'InnerUnmountBoundary componentWillUnmount', 'InnerUpdateBoundary componentWillUnmount', ]); }); it('discards a bad root if the root component fails', () => { const X = null; const Y = undefined; let err1; let err2; try { const container = document.createElement('div'); expect(() => ReactDOM.render(<X />, container)).toErrorDev( 'React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function ' + '(for composite components) but got: null.', ); } catch (err) { err1 = err; } try { const container = document.createElement('div'); expect(() => ReactDOM.render(<Y />, container)).toErrorDev( 'React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function ' + '(for composite components) but got: undefined.', ); } catch (err) { err2 = err; } expect(err1.message).toMatch(/got: null/); expect(err2.message).toMatch(/got: undefined/); }); it('renders empty output if error boundary does not handle the error', () => { const container = document.createElement('div'); expect(() => { ReactDOM.render( <div> Sibling <NoopErrorBoundary> <BrokenRender /> </NoopErrorBoundary> </div>, container, ); }).toErrorDev( 'ErrorBoundary: Error boundaries should implement getDerivedStateFromError()', ); expect(container.firstChild.textContent).toBe('Sibling'); expect(log).toEqual([ 'NoopErrorBoundary constructor', 'NoopErrorBoundary componentWillMount', 'NoopErrorBoundary render', 'BrokenRender constructor', 'BrokenRender componentWillMount', 'BrokenRender render [!]', // In Fiber, noop error boundaries render null 'NoopErrorBoundary componentDidMount', 'NoopErrorBoundary componentDidCatch', // Nothing happens. ]); log.length = 0; ReactDOM.unmountComponentAtNode(container); expect(log).toEqual(['NoopErrorBoundary componentWillUnmount']); }); it('passes first error when two errors happen in commit', () => { const errors = []; let caughtError; class Parent extends React.Component { render() { return <Child />; } componentDidMount() { errors.push('parent sad'); throw new Error('parent sad'); } } class Child extends React.Component { render() { return <div />; } componentDidMount() { errors.push('child sad'); throw new Error('child sad'); } } const container = document.createElement('div'); try { // Here, we test the behavior where there is no error boundary and we // delegate to the host root. ReactDOM.render(<Parent />, container); } catch (e) { if (e.message !== 'parent sad' && e.message !== 'child sad') { throw e; } caughtError = e; } expect(errors).toEqual(['child sad', 'parent sad']); // Error should be the first thrown expect(caughtError.message).toBe('child sad'); }); it('propagates uncaught error inside unbatched initial mount', () => { function Foo() { throw new Error('foo error'); } const container = document.createElement('div'); expect(() => { ReactDOM.unstable_batchedUpdates(() => { ReactDOM.render(<Foo />, container); }); }).toThrow('foo error'); }); it('handles errors that occur in before-mutation commit hook', () => { const errors = []; let caughtError; class Parent extends React.Component { getSnapshotBeforeUpdate() { errors.push('parent sad'); throw new Error('parent sad'); } componentDidUpdate() {} render() { return <Child {...this.props} />; } } class Child extends React.Component { getSnapshotBeforeUpdate() { errors.push('child sad'); throw new Error('child sad'); } componentDidUpdate() {} render() { return <div />; } } const container = document.createElement('div'); ReactDOM.render(<Parent value={1} />, container); try { ReactDOM.render(<Parent value={2} />, container); } catch (e) { if (e.message !== 'parent sad' && e.message !== 'child sad') { throw e; } caughtError = e; } expect(errors).toEqual(['child sad', 'parent sad']); // Error should be the first thrown expect(caughtError.message).toBe('child sad'); }); });
31.732143
115
0.652682
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('../cjs/use-sync-external-store-shim.native.production.min.js'); } else { module.exports = require('../cjs/use-sync-external-store-shim.native.development.js'); }
30.625
91
0.698413
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; export { isValidElementType, typeOf, ContextConsumer, ContextProvider, Element, ForwardRef, Fragment, Lazy, Memo, Portal, Profiler, StrictMode, Suspense, SuspenseList, isAsyncMode, isConcurrentMode, isContextConsumer, isContextProvider, isElement, isForwardRef, isFragment, isLazy, isMemo, isPortal, isProfiler, isStrictMode, isSuspense, isSuspenseList, } from './src/ReactIs';
14.571429
66
0.701378
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ describe('Bridge', () => { let Bridge; beforeEach(() => { Bridge = require('react-devtools-shared/src/bridge').default; }); // @reactVersion >=16.0 it('should shutdown properly', () => { const wall = { listen: jest.fn(() => () => {}), send: jest.fn(), }; const bridge = new Bridge(wall); const shutdownCallback = jest.fn(); bridge.addListener('shutdown', shutdownCallback); // Check that we're wired up correctly. bridge.send('reloadAppForProfiling'); jest.runAllTimers(); expect(wall.send).toHaveBeenCalledWith('reloadAppForProfiling'); // Should flush pending messages and then shut down. wall.send.mockClear(); bridge.send('update', '1'); bridge.send('update', '2'); bridge.shutdown(); jest.runAllTimers(); expect(wall.send).toHaveBeenCalledWith('update', '1'); expect(wall.send).toHaveBeenCalledWith('update', '2'); expect(wall.send).toHaveBeenCalledWith('shutdown'); expect(shutdownCallback).toHaveBeenCalledTimes(1); // Verify that the Bridge doesn't send messages after shutdown. jest.spyOn(console, 'warn').mockImplementation(() => {}); wall.send.mockClear(); bridge.send('should not send'); jest.runAllTimers(); expect(wall.send).not.toHaveBeenCalled(); expect(console.warn).toHaveBeenCalledWith( 'Cannot send message "should not send" through a Bridge that has been shutdown.', ); }); });
29.574074
87
0.655152
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let ReactDOM; let React; let ReactCache; let ReactTestRenderer; let waitForAll; describe('ReactTestRenderer', () => { beforeEach(() => { jest.resetModules(); ReactDOM = require('react-dom'); // Isolate test renderer. jest.resetModules(); React = require('react'); ReactCache = require('react-cache'); ReactTestRenderer = require('react-test-renderer'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; }); it('should warn if used to render a ReactDOM portal', () => { const container = document.createElement('div'); expect(() => { let error; try { ReactTestRenderer.create(ReactDOM.createPortal('foo', container)); } catch (e) { error = e; } // After the update throws, a subsequent render is scheduled to // unmount the whole tree. This update also causes an error, so React // throws an AggregateError. const errors = error.errors; expect(errors.length).toBe(2); expect(errors[0].message.includes('indexOf is not a function')).toBe( true, ); expect(errors[1].message.includes('indexOf is not a function')).toBe( true, ); }).toErrorDev('An invalid container has been provided.', { withoutStack: true, }); }); describe('timed out Suspense hidden subtrees should not be observable via toJSON', () => { let AsyncText; let PendingResources; let TextResource; beforeEach(() => { PendingResources = {}; TextResource = ReactCache.unstable_createResource( text => new Promise(resolve => { PendingResources[text] = resolve; }), text => text, ); AsyncText = ({text}) => { const value = TextResource.read(text); return value; }; }); it('for root Suspense components', async () => { const App = ({text}) => { return ( <React.Suspense fallback="fallback"> <AsyncText text={text} /> </React.Suspense> ); }; const root = ReactTestRenderer.create(<App text="initial" />); PendingResources.initial('initial'); await waitForAll([]); expect(root.toJSON()).toEqual('initial'); root.update(<App text="dynamic" />); expect(root.toJSON()).toEqual('fallback'); PendingResources.dynamic('dynamic'); await waitForAll([]); expect(root.toJSON()).toEqual('dynamic'); }); it('for nested Suspense components', async () => { const App = ({text}) => { return ( <div> <React.Suspense fallback="fallback"> <AsyncText text={text} /> </React.Suspense> </div> ); }; const root = ReactTestRenderer.create(<App text="initial" />); PendingResources.initial('initial'); await waitForAll([]); expect(root.toJSON().children).toEqual(['initial']); root.update(<App text="dynamic" />); expect(root.toJSON().children).toEqual(['fallback']); PendingResources.dynamic('dynamic'); await waitForAll([]); expect(root.toJSON().children).toEqual(['dynamic']); }); }); });
26.864
92
0.589891
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict */ export type PriorityLevel = 0 | 1 | 2 | 3 | 4 | 5; // TODO: Use symbols? export const NoPriority = 0; export const ImmediatePriority = 1; export const UserBlockingPriority = 2; export const NormalPriority = 3; export const LowPriority = 4; export const IdlePriority = 5;
24.473684
66
0.714286
owtf
import Fixture from '../../Fixture'; import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; const React = window.React; const ReactDOM = window.ReactDOM; const Suspense = React.Suspense; let cache = new Set(); function AsyncStep({text, ms}) { if (!cache.has(text)) { throw new Promise(resolve => setTimeout(() => { cache.add(text); resolve(); }, ms) ); } return null; } let suspendyTreeIdCounter = 0; class SuspendyTreeChild extends React.Component { id = suspendyTreeIdCounter++; state = { step: 1, isHidden: false, }; increment = () => this.setState(s => ({step: s.step + 1})); componentDidMount() { document.addEventListener('keydown', this.onKeydown); } componentWillUnmount() { document.removeEventListener('keydown', this.onKeydown); } onKeydown = event => { if (event.metaKey && event.key === 'Enter') { this.increment(); } }; render() { return ( <> <Suspense fallback={<div>(display: none)</div>}> <div> <AsyncStep text={`${this.state.step} + ${this.id}`} ms={500} /> {this.props.children} </div> </Suspense> <button onClick={this.increment}>Hide</button> </> ); } } class SuspendyTree extends React.Component { parentContainer = React.createRef(null); container = React.createRef(null); componentDidMount() { this.setState({}); document.addEventListener('keydown', this.onKeydown); } componentWillUnmount() { document.removeEventListener('keydown', this.onKeydown); } onKeydown = event => { if (event.metaKey && event.key === '/') { this.removeAndRestore(); } }; removeAndRestore = () => { const parentContainer = this.parentContainer.current; const container = this.container.current; parentContainer.removeChild(container); parentContainer.textContent = '(removed from DOM)'; setTimeout(() => { parentContainer.textContent = ''; parentContainer.appendChild(container); }, 500); }; render() { return ( <> <div ref={this.parentContainer}> <div ref={this.container} /> </div> <div> {this.container.current !== null ? ReactDOM.createPortal( <> <SuspendyTreeChild>{this.props.children}</SuspendyTreeChild> <button onClick={this.removeAndRestore}>Remove</button> </>, this.container.current ) : null} </div> </> ); } } class TextInputFixtures extends React.Component { render() { return ( <FixtureSet title="Suspense" description="Preserving the state of timed-out children"> <p> Clicking "Hide" will hide the fixture context using{' '} <code>display: none</code> for 0.5 seconds, then restore. This is the built-in behavior for timed-out children. Each fixture tests whether the state of the DOM is preserved. Clicking "Remove" will remove the fixture content from the DOM for 0.5 seconds, then restore. This is{' '} <strong>not</strong> how timed-out children are hidden, but is included for comparison purposes. </p> <div className="footnote"> As a shortcut, you can use Command + Enter (or Control + Enter on Windows, Linux) to "Hide" all the fixtures, or Command + / to "Remove" them. </div> <TestCase title="Text selection where entire range times out"> <TestCase.Steps> <li>Use your cursor to select the text below.</li> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> Text selection is preserved when hiding, but not when removing. </TestCase.ExpectedResult> <Fixture> <SuspendyTree> Select this entire sentence (and only this sentence). </SuspendyTree> </Fixture> </TestCase> <TestCase title="Text selection that extends outside timed-out subtree"> <TestCase.Steps> <li> Use your cursor to select a range that includes both the text and the "Go" button. </li> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> Text selection is preserved when hiding, but not when removing. </TestCase.ExpectedResult> <Fixture> <SuspendyTree> Select a range that includes both this sentence and the "Go" button. </SuspendyTree> </Fixture> </TestCase> <TestCase title="Focus"> <TestCase.Steps> <li> Use your cursor to select a range that includes both the text and the "Go" button. </li> <li> Instead of clicking "Go", which switches focus, press Command + Enter (or Control + Enter on Windows, Linux). </li> </TestCase.Steps> <TestCase.ExpectedResult> The ideal behavior is that the focus would not be lost, but currently it is (both when hiding and removing). </TestCase.ExpectedResult> <Fixture> <SuspendyTree> <button>Focus me</button> </SuspendyTree> </Fixture> </TestCase> <TestCase title="Uncontrolled form input"> <TestCase.Steps> <li>Type something ("Hello") into the text input.</li> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> Input is preserved when hiding, but not when removing. </TestCase.ExpectedResult> <Fixture> <SuspendyTree> <input type="text" /> </SuspendyTree> </Fixture> </TestCase> <TestCase title="Image flicker"> <TestCase.Steps> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> The image should reappear without flickering. The text should not reflow. </TestCase.ExpectedResult> <Fixture> <SuspendyTree> <img src="https://upload.wikimedia.org/wikipedia/commons/e/ee/Atom_%282%29.png" /> React is cool </SuspendyTree> </Fixture> </TestCase> <TestCase title="Iframe"> <TestCase.Steps> <li> The iframe shows a nested version of this fixtures app. Navigate to the "Text inputs" page. </li> <li>Select one of the checkboxes.</li> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> When removing, the iframe is reloaded. When hiding, the iframe should still be on the "Text inputs" page. The checkbox should still be checked. (Unfortunately, scroll position is lost.) </TestCase.ExpectedResult> <Fixture> <SuspendyTree> <iframe width="500" height="300" src="/" /> </SuspendyTree> </Fixture> </TestCase> <TestCase title="Video playback"> <TestCase.Steps> <li>Start playing the video, or seek to a specific position.</li> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> The playback position should stay the same. When hiding, the video plays in the background for the entire duration. When removing, the video stops playing, but the position is not lost. </TestCase.ExpectedResult> <Fixture> <SuspendyTree> <video controls> <source src="http://techslides.com/demos/sample-videos/small.webm" type="video/webm" /> <source src="http://techslides.com/demos/sample-videos/small.ogv" type="video/ogg" /> <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4" /> <source src="http://techslides.com/demos/sample-videos/small.3gp" type="video/3gp" /> </video> </SuspendyTree> </Fixture> </TestCase> <TestCase title="Audio playback"> <TestCase.Steps> <li>Start playing the audio, or seek to a specific position.</li> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> The playback position should stay the same. When hiding, the audio plays in the background for the entire duration. When removing, the audio stops playing, but the position is not lost. </TestCase.ExpectedResult> <Fixture> <SuspendyTree> <audio controls={true}> <source src="https://upload.wikimedia.org/wikipedia/commons/e/ec/Mozart_K448.ogg" /> </audio> </SuspendyTree> </Fixture> </TestCase> <TestCase title="Scroll position"> <TestCase.Steps> <li>Scroll to a position in the list.</li> <li>Click "Hide" or "Remove".</li> </TestCase.Steps> <TestCase.ExpectedResult> Scroll position is preserved when hiding, but not when removing. </TestCase.ExpectedResult> <Fixture> <SuspendyTree> <div style={{height: 200, overflow: 'scroll'}}> {Array(20) .fill() .map((_, i) => ( <h2 key={i}>{i + 1}</h2> ))} </div> </SuspendyTree> </Fixture> </TestCase> </FixtureSet> ); } } export default TextInputFixtures;
30.975309
100
0.540303
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 */ interface Reference {} type TaintEntry = { message: string, count: number, }; export const TaintRegistryObjects: WeakMap<Reference, string> = new WeakMap(); export const TaintRegistryValues: Map<string | bigint, TaintEntry> = new Map(); // Byte lengths of all binary values we've ever seen. We don't both refcounting this. // We expect to see only a few lengths here such as the length of token. export const TaintRegistryByteLengths: Set<number> = new Set(); // When a value is finalized, it means that it has been removed from any global caches. // No future requests can get a handle on it but any ongoing requests can still have // a handle on it. It's still tainted until that happens. type RequestCleanupQueue = Array<string | bigint>; export const TaintRegistryPendingRequests: Set<RequestCleanupQueue> = new Set();
35.964286
87
0.745648
owtf
/** @license React v16.14.0 * react-jsx-runtime.production.min.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var f=require("react"),g=60103;exports.Fragment=60107;if("function"===typeof Symbol&&Symbol.for){var h=Symbol.for;g=h("react.element");exports.Fragment=h("react.fragment")}var m=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n=Object.prototype.hasOwnProperty,p={key:!0,ref:!0,__self:!0,__source:!0}; function q(c,a,k){var b,d={},e=null,l=null;void 0!==k&&(e=""+k);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(l=a.ref);for(b in a)n.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:g,type:c,key:e,ref:l,props:d,_owner:m.current}}exports.jsx=q;exports.jsxs=q;
84.545455
345
0.688298
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 {ReactClientValue} from 'react-server/src/ReactFlightServer'; import type { ImportMetadata, ImportManifestEntry, } from './shared/ReactFlightImportMetadata'; import type { ClientReference, ServerReference, } from './ReactFlightTurbopackReferences'; export type {ClientReference, ServerReference}; export type ClientManifest = { [id: string]: ClientReferenceManifestEntry, }; export type ServerReferenceId = string; export type ClientReferenceMetadata = ImportMetadata; export opaque type ClientReferenceManifestEntry = ImportManifestEntry; export type ClientReferenceKey = string; export { isClientReference, isServerReference, } from './ReactFlightTurbopackReferences'; export function getClientReferenceKey( reference: ClientReference<any>, ): ClientReferenceKey { return reference.$$async ? reference.$$id + '#async' : reference.$$id; } export function resolveClientReferenceMetadata<T>( config: ClientManifest, clientReference: ClientReference<T>, ): ClientReferenceMetadata { const modulePath = clientReference.$$id; let name = ''; let resolvedModuleData = config[modulePath]; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // We didn't find this specific export name but we might have the * export // which contains this name as well. // TODO: It's unfortunate that we now have to parse this string. We should // probably go back to encoding path and name separately on the client reference. const idx = modulePath.lastIndexOf('#'); if (idx !== -1) { name = modulePath.slice(idx + 1); resolvedModuleData = config[modulePath.slice(0, idx)]; } if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } } if (clientReference.$$async === true) { return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1]; } else { return [resolvedModuleData.id, resolvedModuleData.chunks, name]; } } export function getServerReferenceId<T>( config: ClientManifest, serverReference: ServerReference<T>, ): ServerReferenceId { return serverReference.$$id; } export function getServerReferenceBoundArguments<T>( config: ClientManifest, serverReference: ServerReference<T>, ): null | Array<ReactClientValue> { return serverReference.$$bound; }
27.93617
85
0.720485
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactClientValue} from 'react-server/src/ReactFlightServer'; import type { ImportMetadata, ImportManifestEntry, } from './shared/ReactFlightImportMetadata'; import type { ClientReference, ServerReference, } from './ReactFlightWebpackReferences'; export type {ClientReference, ServerReference}; export type ClientManifest = { [id: string]: ClientReferenceManifestEntry, }; export type ServerReferenceId = string; export type ClientReferenceMetadata = ImportMetadata; export opaque type ClientReferenceManifestEntry = ImportManifestEntry; export type ClientReferenceKey = string; export { isClientReference, isServerReference, } from './ReactFlightWebpackReferences'; export function getClientReferenceKey( reference: ClientReference<any>, ): ClientReferenceKey { return reference.$$async ? reference.$$id + '#async' : reference.$$id; } export function resolveClientReferenceMetadata<T>( config: ClientManifest, clientReference: ClientReference<T>, ): ClientReferenceMetadata { const modulePath = clientReference.$$id; let name = ''; let resolvedModuleData = config[modulePath]; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // We didn't find this specific export name but we might have the * export // which contains this name as well. // TODO: It's unfortunate that we now have to parse this string. We should // probably go back to encoding path and name separately on the client reference. const idx = modulePath.lastIndexOf('#'); if (idx !== -1) { name = modulePath.slice(idx + 1); resolvedModuleData = config[modulePath.slice(0, idx)]; } if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } } if (clientReference.$$async === true) { return [resolvedModuleData.id, resolvedModuleData.chunks, name, 1]; } else { return [resolvedModuleData.id, resolvedModuleData.chunks, name]; } } export function getServerReferenceId<T>( config: ClientManifest, serverReference: ServerReference<T>, ): ServerReferenceId { return serverReference.$$id; } export function getServerReferenceBoundArguments<T>( config: ClientManifest, serverReference: ServerReference<T>, ): null | Array<ReactClientValue> { return serverReference.$$bound; }
27.893617
85
0.720074
null
#!/usr/bin/env node 'use strict'; const {exec} = require('child-process-promise'); const {join} = require('path'); const {tmpdir} = require('os'); const {logPromise} = require('../utils'); const theme = require('../theme'); const run = async ({commit, cwd, tempDirectory}) => { const directory = `react-${commit}`; const temp = tmpdir(); if (tempDirectory !== join(tmpdir(), directory)) { throw Error(`Unexpected temporary directory "${tempDirectory}"`); } await exec(`rm -rf ${directory}`, {cwd: temp}); await exec(`git archive --format=tar --output=${temp}/react.tgz ${commit}`, { cwd, }); await exec(`mkdir ${directory}`, {cwd: temp}); await exec(`tar -xf ./react.tgz -C ./${directory}`, {cwd: temp}); }; module.exports = async params => { return logPromise( run(params), theme`Copying React repo to temporary directory ({path ${params.tempDirectory}})` ); };
26.515152
85
0.63065
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 HookFlags = number; export const NoFlags = /* */ 0b0000; // Represents whether effect should fire. export const HasEffect = /* */ 0b0001; // Represents the phase in which the effect (not the clean-up) fires. export const Insertion = /* */ 0b0010; export const Layout = /* */ 0b0100; export const Passive = /* */ 0b1000;
25.047619
69
0.68315
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 {Dispatcher} from 'react-reconciler/src/ReactInternalTypes'; /** * Keeps track of the current dispatcher. */ const ReactCurrentDispatcher = { current: (null: null | Dispatcher), }; export default ReactCurrentDispatcher;
21.15
72
0.721719
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 */ // Adapted from: https://github.com/facebookarchive/fixed-data-table/blob/main/src/vendor_upstream/dom/normalizeWheel.js export type NormalizedWheelDelta = { deltaX: number, deltaY: number, }; // Reasonable defaults const LINE_HEIGHT = 40; const PAGE_HEIGHT = 800; /** * Mouse wheel (and 2-finger trackpad) support on the web sucks. It is * complicated, thus this doc is long and (hopefully) detailed enough to answer * your questions. * * If you need to react to the mouse wheel in a predictable way, this code is * like your bestest friend. * hugs * * * In your event callback, use this code to get sane interpretation of the * deltas. This code will return an object with properties: * * - deltaX -- normalized distance (to pixels) - x plane * - deltaY -- " - y plane * * Wheel values are provided by the browser assuming you are using the wheel to * scroll a web page by a number of lines or pixels (or pages). Values can vary * significantly on different platforms and browsers, forgetting that you can * scroll at different speeds. Some devices (like trackpads) emit more events * at smaller increments with fine granularity, and some emit massive jumps with * linear speed or acceleration. * * This code does its best to normalize the deltas for you: * * - delta* is normalizing the desired scroll delta in pixel units. * * - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This * should translate to positive value zooming IN, negative zooming OUT. * This matches the 'wheel' event. * * Implementation info: * * The basics of the standard 'wheel' event is that it includes a unit, * deltaMode (pixels, lines, pages), and deltaX, deltaY and deltaZ. * See: http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents * * Examples of 'wheel' event if you scroll slowly (down) by one step with an * average mouse: * * OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120) * OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12) * OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A) * Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120) * Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120) * * On the trackpad: * * OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6) * OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A) */ export function normalizeWheel(event: WheelEvent): NormalizedWheelDelta { let deltaX = event.deltaX; let deltaY = event.deltaY; if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) { // delta in LINE units deltaX *= LINE_HEIGHT; deltaY *= LINE_HEIGHT; } else if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) { // delta in PAGE units deltaX *= PAGE_HEIGHT; deltaY *= PAGE_HEIGHT; } return {deltaX, deltaY}; }
34.918605
120
0.680376
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-native-renderer/src/ReactFiberConfigNative';
23.636364
66
0.718519
PenetrationTestingScripts
/* global chrome */ 'use strict'; function setExtensionIconAndPopup(reactBuildType, tabId) { const action = __IS_FIREFOX__ ? chrome.browserAction : chrome.action; action.setIcon({ tabId, path: { '16': chrome.runtime.getURL(`icons/16-${reactBuildType}.png`), '32': chrome.runtime.getURL(`icons/32-${reactBuildType}.png`), '48': chrome.runtime.getURL(`icons/48-${reactBuildType}.png`), '128': chrome.runtime.getURL(`icons/128-${reactBuildType}.png`), }, }); action.setPopup({ tabId, popup: chrome.runtime.getURL(`popups/${reactBuildType}.html`), }); } export default setExtensionIconAndPopup;
25.04
71
0.663077
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 { Instance, TextInstance, SuspenseInstance, Container, ChildSet, UpdatePayload, HoistableRoot, } from './ReactFiberConfig'; import type {Fiber, FiberRoot} from './ReactInternalTypes'; import type {Lanes} from './ReactFiberLane'; import {SyncLane} from './ReactFiberLane'; import type {SuspenseState, RetryQueue} from './ReactFiberSuspenseComponent'; import type {UpdateQueue} from './ReactFiberClassUpdateQueue'; import type {FunctionComponentUpdateQueue} from './ReactFiberHooks'; import type {Wakeable} from 'shared/ReactTypes'; import {isOffscreenManual} from './ReactFiberActivityComponent'; import type { OffscreenState, OffscreenInstance, OffscreenQueue, OffscreenProps, } from './ReactFiberActivityComponent'; import type {HookFlags} from './ReactHookEffectTags'; import type {Cache} from './ReactFiberCacheComponent'; import type {RootState} from './ReactFiberRoot'; import type { Transition, TracingMarkerInstance, TransitionAbort, } from './ReactFiberTracingMarkerComponent'; import { enableCreateEventHandleAPI, enableProfilerTimer, enableProfilerCommitHooks, enableProfilerNestedUpdatePhase, enableSchedulingProfiler, enableSuspenseCallback, enableScopeAPI, enableUpdaterTracking, enableCache, enableTransitionTracing, enableUseEffectEventHook, enableFloat, enableLegacyHidden, alwaysThrottleRetries, } from 'shared/ReactFeatureFlags'; import { FunctionComponent, ForwardRef, ClassComponent, HostRoot, HostComponent, HostHoistable, HostSingleton, HostText, HostPortal, Profiler, SuspenseComponent, DehydratedFragment, IncompleteClassComponent, MemoComponent, SimpleMemoComponent, SuspenseListComponent, ScopeComponent, OffscreenComponent, LegacyHiddenComponent, CacheComponent, TracingMarkerComponent, } from './ReactWorkTags'; import { NoFlags, ContentReset, Placement, ChildDeletion, Snapshot, Update, Callback, Ref, Hydrating, Passive, BeforeMutationMask, MutationMask, LayoutMask, PassiveMask, Visibility, ShouldSuspendCommit, MaySuspendCommit, } from './ReactFiberFlags'; import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; import { resetCurrentFiber as resetCurrentDebugFiberInDEV, setCurrentFiber as setCurrentDebugFiberInDEV, getCurrentFiber as getCurrentDebugFiberInDEV, } from './ReactCurrentFiber'; import {resolveDefaultProps} from './ReactFiberLazyComponent'; import { isCurrentUpdateNested, getCommitTime, recordLayoutEffectDuration, startLayoutEffectTimer, recordPassiveEffectDuration, startPassiveEffectTimer, } from './ReactProfilerTimer'; import {ConcurrentMode, NoMode, ProfileMode} from './ReactTypeOfMode'; import { deferHiddenCallbacks, commitHiddenCallbacks, commitCallbacks, } from './ReactFiberClassUpdateQueue'; import { getPublicInstance, supportsMutation, supportsPersistence, supportsHydration, supportsResources, supportsSingletons, commitMount, commitUpdate, resetTextContent, commitTextUpdate, appendChild, appendChildToContainer, insertBefore, insertInContainerBefore, removeChild, removeChildFromContainer, clearSuspenseBoundary, clearSuspenseBoundaryFromContainer, replaceContainerChildren, createContainerChildSet, hideInstance, hideTextInstance, unhideInstance, unhideTextInstance, commitHydratedContainer, commitHydratedSuspenseInstance, clearContainer, prepareScopeUpdate, prepareForCommit, beforeActiveInstanceBlur, detachDeletedInstance, clearSingleton, acquireSingletonInstance, releaseSingletonInstance, getHoistableRoot, acquireResource, releaseResource, hydrateHoistable, mountHoistable, unmountHoistable, prepareToCommitHoistables, suspendInstance, suspendResource, } from './ReactFiberConfig'; import { captureCommitPhaseError, resolveRetryWakeable, markCommitTimeOfFallback, enqueuePendingPassiveProfilerEffect, restorePendingUpdaters, addTransitionStartCallbackToPendingTransition, addTransitionProgressCallbackToPendingTransition, addTransitionCompleteCallbackToPendingTransition, addMarkerProgressCallbackToPendingTransition, addMarkerIncompleteCallbackToPendingTransition, addMarkerCompleteCallbackToPendingTransition, setIsRunningInsertionEffect, getExecutionContext, CommitContext, NoContext, } from './ReactFiberWorkLoop'; import { NoFlags as NoHookEffect, HasEffect as HookHasEffect, Layout as HookLayout, Insertion as HookInsertion, Passive as HookPassive, } from './ReactHookEffectTags'; import {didWarnAboutReassigningProps} from './ReactFiberBeginWork'; import {doesFiberContain} from './ReactFiberTreeReflection'; import {invokeGuardedCallback, clearCaughtError} from 'shared/ReactErrorUtils'; import { isDevToolsPresent, markComponentPassiveEffectMountStarted, markComponentPassiveEffectMountStopped, markComponentPassiveEffectUnmountStarted, markComponentPassiveEffectUnmountStopped, markComponentLayoutEffectMountStarted, markComponentLayoutEffectMountStopped, markComponentLayoutEffectUnmountStarted, markComponentLayoutEffectUnmountStopped, onCommitUnmount, } from './ReactFiberDevToolsHook'; import {releaseCache, retainCache} from './ReactFiberCacheComponent'; import {clearTransitionsForLanes} from './ReactFiberLane'; import { OffscreenVisible, OffscreenDetached, OffscreenPassiveEffectsConnected, } from './ReactFiberActivityComponent'; import { TransitionRoot, TransitionTracingMarker, } from './ReactFiberTracingMarkerComponent'; import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop'; import {enqueueConcurrentRenderForLane} from './ReactFiberConcurrentUpdates'; let didWarnAboutUndefinedSnapshotBeforeUpdate: Set<mixed> | null = null; if (__DEV__) { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } // Used during the commit phase to track the state of the Offscreen component stack. // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. let offscreenSubtreeIsHidden: boolean = false; let offscreenSubtreeWasHidden: boolean = false; const PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; let nextEffect: Fiber | null = null; // Used for Profiling builds to track updaters. let inProgressLanes: Lanes | null = null; let inProgressRoot: FiberRoot | null = null; function shouldProfile(current: Fiber): boolean { return ( enableProfilerTimer && enableProfilerCommitHooks && (current.mode & ProfileMode) !== NoMode && (getExecutionContext() & CommitContext) !== NoContext ); } export function reportUncaughtErrorInDEV(error: mixed) { // Wrapping each small part of the commit phase into a guarded // callback is a bit too slow (https://github.com/facebook/react/pull/21666). // But we rely on it to surface errors to DEV tools like overlays // (https://github.com/facebook/react/issues/21712). // As a compromise, rethrow only caught errors in a guard. if (__DEV__) { invokeGuardedCallback(null, () => { throw error; }); clearCaughtError(); } } function callComponentWillUnmountWithTimer(current: Fiber, instance: any) { instance.props = current.memoizedProps; instance.state = current.memoizedState; if (shouldProfile(current)) { try { startLayoutEffectTimer(); instance.componentWillUnmount(); } finally { recordLayoutEffectDuration(current); } } else { instance.componentWillUnmount(); } } // Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount( current: Fiber, nearestMountedAncestor: Fiber | null, instance: any, ) { try { callComponentWillUnmountWithTimer(current, instance); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } // Capture errors so they don't interrupt mounting. function safelyAttachRef(current: Fiber, nearestMountedAncestor: Fiber | null) { try { commitAttachRef(current); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } function safelyDetachRef(current: Fiber, nearestMountedAncestor: Fiber | null) { const ref = current.ref; const refCleanup = current.refCleanup; if (ref !== null) { if (typeof refCleanup === 'function') { try { if (shouldProfile(current)) { try { startLayoutEffectTimer(); refCleanup(); } finally { recordLayoutEffectDuration(current); } } else { refCleanup(); } } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } finally { // `refCleanup` has been called. Nullify all references to it to prevent double invocation. current.refCleanup = null; const finishedWork = current.alternate; if (finishedWork != null) { finishedWork.refCleanup = null; } } } else if (typeof ref === 'function') { let retVal; try { if (shouldProfile(current)) { try { startLayoutEffectTimer(); retVal = ref(null); } finally { recordLayoutEffectDuration(current); } } else { retVal = ref(null); } } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } if (__DEV__) { if (typeof retVal === 'function') { console.error( 'Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current), ); } } } else { // $FlowFixMe[incompatible-use] unable to narrow type to RefObject ref.current = null; } } } function safelyCallDestroy( current: Fiber, nearestMountedAncestor: Fiber | null, destroy: () => void, ) { try { destroy(); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } let focusedInstanceHandle: null | Fiber = null; let shouldFireAfterActiveInstanceBlur: boolean = false; export function commitBeforeMutationEffects( root: FiberRoot, firstChild: Fiber, ): boolean { focusedInstanceHandle = prepareForCommit(root.containerInfo); nextEffect = firstChild; commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber const shouldFire = shouldFireAfterActiveInstanceBlur; shouldFireAfterActiveInstanceBlur = false; focusedInstanceHandle = null; return shouldFire; } function commitBeforeMutationEffects_begin() { while (nextEffect !== null) { const fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur. // Let's skip the whole loop if it's off. if (enableCreateEventHandleAPI) { // TODO: Should wrap this in flags check, too, as optimization const deletions = fiber.deletions; if (deletions !== null) { for (let i = 0; i < deletions.length; i++) { const deletion = deletions[i]; commitBeforeMutationEffectsDeletion(deletion); } } } const child = fiber.child; if ( (fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null ) { child.return = fiber; nextEffect = child; } else { commitBeforeMutationEffects_complete(); } } } function commitBeforeMutationEffects_complete() { while (nextEffect !== null) { const fiber = nextEffect; setCurrentDebugFiberInDEV(fiber); try { commitBeforeMutationEffectsOnFiber(fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentDebugFiberInDEV(); const sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitBeforeMutationEffectsOnFiber(finishedWork: Fiber) { const current = finishedWork.alternate; const flags = finishedWork.flags; if (enableCreateEventHandleAPI) { if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) { // Check to see if the focused element was inside of a hidden (Suspense) subtree. // TODO: Move this out of the hot path using a dedicated effect tag. if ( finishedWork.tag === SuspenseComponent && isSuspenseBoundaryBeingHidden(current, finishedWork) && // $FlowFixMe[incompatible-call] found when upgrading Flow doesFiberContain(finishedWork, focusedInstanceHandle) ) { shouldFireAfterActiveInstanceBlur = true; beforeActiveInstanceBlur(finishedWork); } } } if ((flags & Snapshot) !== NoFlags) { setCurrentDebugFiberInDEV(finishedWork); } switch (finishedWork.tag) { case FunctionComponent: { if (enableUseEffectEventHook) { if ((flags & Update) !== NoFlags) { commitUseEffectEventMount(finishedWork); } } break; } case ForwardRef: case SimpleMemoComponent: { break; } case ClassComponent: { if ((flags & Snapshot) !== NoFlags) { if (current !== null) { const prevProps = current.memoizedProps; const prevState = current.memoizedState; const instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. if (__DEV__) { if ( finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps ) { if (instance.props !== finishedWork.memoizedProps) { console.error( 'Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } if (instance.state !== finishedWork.memoizedState) { console.error( 'Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } } } const snapshot = instance.getSnapshotBeforeUpdate( finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState, ); if (__DEV__) { const didWarnSet = ((didWarnAboutUndefinedSnapshotBeforeUpdate: any): Set<mixed>); if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); console.error( '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork), ); } } instance.__reactInternalSnapshotBeforeUpdate = snapshot; } } break; } case HostRoot: { if ((flags & Snapshot) !== NoFlags) { if (supportsMutation) { const root = finishedWork.stateNode; clearContainer(root.containerInfo); } } break; } case HostComponent: case HostHoistable: case HostSingleton: case HostText: case HostPortal: case IncompleteClassComponent: // Nothing to do for these component types break; default: { if ((flags & Snapshot) !== NoFlags) { throw new Error( 'This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.', ); } } } if ((flags & Snapshot) !== NoFlags) { resetCurrentDebugFiberInDEV(); } } function commitBeforeMutationEffectsDeletion(deletion: Fiber) { if (enableCreateEventHandleAPI) { // TODO (effects) It would be nice to avoid calling doesFiberContain() // Maybe we can repurpose one of the subtreeFlags positions for this instead? // Use it to store which part of the tree the focused instance is in? // This assumes we can safely determine that instance during the "render" phase. if (doesFiberContain(deletion, ((focusedInstanceHandle: any): Fiber))) { shouldFireAfterActiveInstanceBlur = true; beforeActiveInstanceBlur(deletion); } } } function commitHookEffectListUnmount( flags: HookFlags, finishedWork: Fiber, nearestMountedAncestor: Fiber | null, ) { const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any); const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; if (lastEffect !== null) { const firstEffect = lastEffect.next; let effect = firstEffect; do { if ((effect.tag & flags) === flags) { // Unmount const inst = effect.inst; const destroy = inst.destroy; if (destroy !== undefined) { inst.destroy = undefined; if (enableSchedulingProfiler) { if ((flags & HookPassive) !== NoHookEffect) { markComponentPassiveEffectUnmountStarted(finishedWork); } else if ((flags & HookLayout) !== NoHookEffect) { markComponentLayoutEffectUnmountStarted(finishedWork); } } if (__DEV__) { if ((flags & HookInsertion) !== NoHookEffect) { setIsRunningInsertionEffect(true); } } safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); if (__DEV__) { if ((flags & HookInsertion) !== NoHookEffect) { setIsRunningInsertionEffect(false); } } if (enableSchedulingProfiler) { if ((flags & HookPassive) !== NoHookEffect) { markComponentPassiveEffectUnmountStopped(); } else if ((flags & HookLayout) !== NoHookEffect) { markComponentLayoutEffectUnmountStopped(); } } } } effect = effect.next; } while (effect !== firstEffect); } } function commitHookEffectListMount(flags: HookFlags, finishedWork: Fiber) { const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any); const lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; if (lastEffect !== null) { const firstEffect = lastEffect.next; let effect = firstEffect; do { if ((effect.tag & flags) === flags) { if (enableSchedulingProfiler) { if ((flags & HookPassive) !== NoHookEffect) { markComponentPassiveEffectMountStarted(finishedWork); } else if ((flags & HookLayout) !== NoHookEffect) { markComponentLayoutEffectMountStarted(finishedWork); } } // Mount const create = effect.create; if (__DEV__) { if ((flags & HookInsertion) !== NoHookEffect) { setIsRunningInsertionEffect(true); } } const inst = effect.inst; const destroy = create(); inst.destroy = destroy; if (__DEV__) { if ((flags & HookInsertion) !== NoHookEffect) { setIsRunningInsertionEffect(false); } } if (enableSchedulingProfiler) { if ((flags & HookPassive) !== NoHookEffect) { markComponentPassiveEffectMountStopped(); } else if ((flags & HookLayout) !== NoHookEffect) { markComponentLayoutEffectMountStopped(); } } if (__DEV__) { if (destroy !== undefined && typeof destroy !== 'function') { let hookName; if ((effect.tag & HookLayout) !== NoFlags) { hookName = 'useLayoutEffect'; } else if ((effect.tag & HookInsertion) !== NoFlags) { hookName = 'useInsertionEffect'; } else { hookName = 'useEffect'; } let addendum; if (destroy === null) { addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; } else if (typeof destroy.then === 'function') { addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + `}, [someId]); // Or [] if effect doesn't need props or state\n\n` + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; } else { addendum = ' You returned: ' + destroy; } console.error( '%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum, ); } } } effect = effect.next; } while (effect !== firstEffect); } } function commitUseEffectEventMount(finishedWork: Fiber) { const updateQueue: FunctionComponentUpdateQueue | null = (finishedWork.updateQueue: any); const eventPayloads = updateQueue !== null ? updateQueue.events : null; if (eventPayloads !== null) { for (let ii = 0; ii < eventPayloads.length; ii++) { const {ref, nextImpl} = eventPayloads[ii]; ref.impl = nextImpl; } } } export function commitPassiveEffectDurations( finishedRoot: FiberRoot, finishedWork: Fiber, ): void { if ( enableProfilerTimer && enableProfilerCommitHooks && getExecutionContext() & CommitContext ) { // Only Profilers with work in their subtree will have an Update effect scheduled. if ((finishedWork.flags & Update) !== NoFlags) { switch (finishedWork.tag) { case Profiler: { const {passiveEffectDuration} = finishedWork.stateNode; const {id, onPostCommit} = finishedWork.memoizedProps; // This value will still reflect the previous commit phase. // It does not get reset until the start of the next commit phase. const commitTime = getCommitTime(); let phase = finishedWork.alternate === null ? 'mount' : 'update'; if (enableProfilerNestedUpdatePhase) { if (isCurrentUpdateNested()) { phase = 'nested-update'; } } if (typeof onPostCommit === 'function') { onPostCommit(id, phase, passiveEffectDuration, commitTime); } // Bubble times to the next nearest ancestor Profiler. // After we process that Profiler, we'll bubble further up. let parentFiber = finishedWork.return; outer: while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: const root = parentFiber.stateNode; root.passiveEffectDuration += passiveEffectDuration; break outer; case Profiler: const parentStateNode = parentFiber.stateNode; parentStateNode.passiveEffectDuration += passiveEffectDuration; break outer; } parentFiber = parentFiber.return; } break; } default: break; } } } } function commitHookLayoutEffects(finishedWork: Fiber, hookFlags: HookFlags) { // At this point layout effects have already been destroyed (during mutation phase). // This is done to prevent sibling component effects from interfering with each other, // e.g. a destroy function in one component should never override a ref set // by a create function in another component during the same commit. if (shouldProfile(finishedWork)) { try { startLayoutEffectTimer(); commitHookEffectListMount(hookFlags, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } recordLayoutEffectDuration(finishedWork); } else { try { commitHookEffectListMount(hookFlags, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } function commitClassLayoutLifecycles( finishedWork: Fiber, current: Fiber | null, ) { const instance = finishedWork.stateNode; if (current === null) { // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. if (__DEV__) { if ( finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps ) { if (instance.props !== finishedWork.memoizedProps) { console.error( 'Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } if (instance.state !== finishedWork.memoizedState) { console.error( 'Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } } } if (shouldProfile(finishedWork)) { try { startLayoutEffectTimer(); instance.componentDidMount(); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } recordLayoutEffectDuration(finishedWork); } else { try { instance.componentDidMount(); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } else { const prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps); const prevState = current.memoizedState; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. if (__DEV__) { if ( finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps ) { if (instance.props !== finishedWork.memoizedProps) { console.error( 'Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } if (instance.state !== finishedWork.memoizedState) { console.error( 'Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } } } if (shouldProfile(finishedWork)) { try { startLayoutEffectTimer(); instance.componentDidUpdate( prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate, ); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } recordLayoutEffectDuration(finishedWork); } else { try { instance.componentDidUpdate( prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate, ); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } } function commitClassCallbacks(finishedWork: Fiber) { // TODO: I think this is now always non-null by the time it reaches the // commit phase. Consider removing the type check. const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any); if (updateQueue !== null) { const instance = finishedWork.stateNode; if (__DEV__) { if ( finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps ) { if (instance.props !== finishedWork.memoizedProps) { console.error( 'Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } if (instance.state !== finishedWork.memoizedState) { console.error( 'Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance', ); } } } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. try { commitCallbacks(updateQueue, instance); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } function commitHostComponentMount(finishedWork: Fiber) { const type = finishedWork.type; const props = finishedWork.memoizedProps; const instance: Instance = finishedWork.stateNode; try { commitMount(instance, type, props, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } function commitProfilerUpdate(finishedWork: Fiber, current: Fiber | null) { if (enableProfilerTimer && getExecutionContext() & CommitContext) { try { const {onCommit, onRender} = finishedWork.memoizedProps; const {effectDuration} = finishedWork.stateNode; const commitTime = getCommitTime(); let phase = current === null ? 'mount' : 'update'; if (enableProfilerNestedUpdatePhase) { if (isCurrentUpdateNested()) { phase = 'nested-update'; } } if (typeof onRender === 'function') { onRender( finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime, ); } if (enableProfilerCommitHooks) { if (typeof onCommit === 'function') { onCommit( finishedWork.memoizedProps.id, phase, effectDuration, commitTime, ); } // Schedule a passive effect for this Profiler to call onPostCommit hooks. // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, // because the effect is also where times bubble to parent Profilers. enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor. // Do not reset these values until the next render so DevTools has a chance to read them first. let parentFiber = finishedWork.return; outer: while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: const root = parentFiber.stateNode; root.effectDuration += effectDuration; break outer; case Profiler: const parentStateNode = parentFiber.stateNode; parentStateNode.effectDuration += effectDuration; break outer; } parentFiber = parentFiber.return; } } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } function commitLayoutEffectOnFiber( finishedRoot: FiberRoot, current: Fiber | null, finishedWork: Fiber, committedLanes: Lanes, ): void { // When updating this function, also update reappearLayoutEffects, which does // most of the same things when an offscreen tree goes from hidden -> visible. const flags = finishedWork.flags; switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); if (flags & Update) { commitHookLayoutEffects(finishedWork, HookLayout | HookHasEffect); } break; } case ClassComponent: { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); if (flags & Update) { commitClassLayoutLifecycles(finishedWork, current); } if (flags & Callback) { commitClassCallbacks(finishedWork); } if (flags & Ref) { safelyAttachRef(finishedWork, finishedWork.return); } break; } case HostRoot: { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); if (flags & Callback) { // TODO: I think this is now always non-null by the time it reaches the // commit phase. Consider removing the type check. const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any); if (updateQueue !== null) { let instance = null; if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostSingleton: case HostComponent: instance = getPublicInstance(finishedWork.child.stateNode); break; case ClassComponent: instance = finishedWork.child.stateNode; break; } } try { commitCallbacks(updateQueue, instance); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } break; } case HostHoistable: { if (enableFloat && supportsResources) { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); if (flags & Ref) { safelyAttachRef(finishedWork, finishedWork.return); } break; } // Fall through } case HostSingleton: case HostComponent: { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. if (current === null && flags & Update) { commitHostComponentMount(finishedWork); } if (flags & Ref) { safelyAttachRef(finishedWork, finishedWork.return); } break; } case Profiler: { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); // TODO: Should this fire inside an offscreen tree? Or should it wait to // fire when the tree becomes visible again. if (flags & Update) { commitProfilerUpdate(finishedWork, current); } break; } case SuspenseComponent: { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); if (flags & Update) { commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); } break; } case OffscreenComponent: { const isModernRoot = (finishedWork.mode & ConcurrentMode) !== NoMode; if (isModernRoot) { const isHidden = finishedWork.memoizedState !== null; const newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; if (newOffscreenSubtreeIsHidden) { // The Offscreen tree is hidden. Skip over its layout effects. } else { // The Offscreen tree is visible. const wasHidden = current !== null && current.memoizedState !== null; const newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; const prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { // This is the root of a reappearing boundary. As we continue // traversing the layout effects, we must also re-mount layout // effects that were unmounted when the Offscreen subtree was // hidden. So this is a superset of the normal commitLayoutEffects. const includeWorkInProgressEffects = (finishedWork.subtreeFlags & LayoutMask) !== NoFlags; recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); } else { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); } offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; } } else { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); } if (flags & Ref) { const props: OffscreenProps = finishedWork.memoizedProps; if (props.mode === 'manual') { safelyAttachRef(finishedWork, finishedWork.return); } else { safelyDetachRef(finishedWork, finishedWork.return); } } break; } default: { recursivelyTraverseLayoutEffects( finishedRoot, finishedWork, committedLanes, ); break; } } } function abortRootTransitions( root: FiberRoot, abort: TransitionAbort, deletedTransitions: Set<Transition>, deletedOffscreenInstance: OffscreenInstance | null, isInDeletedTree: boolean, ) { if (enableTransitionTracing) { const rootTransitions = root.incompleteTransitions; deletedTransitions.forEach(transition => { if (rootTransitions.has(transition)) { const transitionInstance: TracingMarkerInstance = (rootTransitions.get( transition, ): any); if (transitionInstance.aborts === null) { transitionInstance.aborts = []; } transitionInstance.aborts.push(abort); if (deletedOffscreenInstance !== null) { if ( transitionInstance.pendingBoundaries !== null && transitionInstance.pendingBoundaries.has(deletedOffscreenInstance) ) { // $FlowFixMe[incompatible-use] found when upgrading Flow transitionInstance.pendingBoundaries.delete( deletedOffscreenInstance, ); } } } }); } } function abortTracingMarkerTransitions( abortedFiber: Fiber, abort: TransitionAbort, deletedTransitions: Set<Transition>, deletedOffscreenInstance: OffscreenInstance | null, isInDeletedTree: boolean, ) { if (enableTransitionTracing) { const markerInstance: TracingMarkerInstance = abortedFiber.stateNode; const markerTransitions = markerInstance.transitions; const pendingBoundaries = markerInstance.pendingBoundaries; if (markerTransitions !== null) { // TODO: Refactor this code. Is there a way to move this code to // the deletions phase instead of calculating it here while making sure // complete is called appropriately? deletedTransitions.forEach(transition => { // If one of the transitions on the tracing marker is a transition // that was in an aborted subtree, we will abort that tracing marker if ( abortedFiber !== null && markerTransitions.has(transition) && (markerInstance.aborts === null || !markerInstance.aborts.includes(abort)) ) { if (markerInstance.transitions !== null) { if (markerInstance.aborts === null) { markerInstance.aborts = [abort]; addMarkerIncompleteCallbackToPendingTransition( abortedFiber.memoizedProps.name, markerInstance.transitions, markerInstance.aborts, ); } else { markerInstance.aborts.push(abort); } // We only want to call onTransitionProgress when the marker hasn't been // deleted if ( deletedOffscreenInstance !== null && !isInDeletedTree && pendingBoundaries !== null && pendingBoundaries.has(deletedOffscreenInstance) ) { pendingBoundaries.delete(deletedOffscreenInstance); addMarkerProgressCallbackToPendingTransition( abortedFiber.memoizedProps.name, deletedTransitions, pendingBoundaries, ); } } } }); } } } function abortParentMarkerTransitionsForDeletedFiber( abortedFiber: Fiber, abort: TransitionAbort, deletedTransitions: Set<Transition>, deletedOffscreenInstance: OffscreenInstance | null, isInDeletedTree: boolean, ) { if (enableTransitionTracing) { // Find all pending markers that are waiting on child suspense boundaries in the // aborted subtree and cancels them let fiber: null | Fiber = abortedFiber; while (fiber !== null) { switch (fiber.tag) { case TracingMarkerComponent: abortTracingMarkerTransitions( fiber, abort, deletedTransitions, deletedOffscreenInstance, isInDeletedTree, ); break; case HostRoot: const root = fiber.stateNode; abortRootTransitions( root, abort, deletedTransitions, deletedOffscreenInstance, isInDeletedTree, ); break; default: break; } fiber = fiber.return; } } } function commitTransitionProgress(offscreenFiber: Fiber) { if (enableTransitionTracing) { // This function adds suspense boundaries to the root // or tracing marker's pendingBoundaries map. // When a suspense boundary goes from a resolved to a fallback // state we add the boundary to the map, and when it goes from // a fallback to a resolved state, we remove the boundary from // the map. // We use stateNode on the Offscreen component as a stable object // that doesnt change from render to render. This way we can // distinguish between different Offscreen instances (vs. the same // Offscreen instance with different fibers) const offscreenInstance: OffscreenInstance = offscreenFiber.stateNode; let prevState: SuspenseState | null = null; const previousFiber = offscreenFiber.alternate; if (previousFiber !== null && previousFiber.memoizedState !== null) { prevState = previousFiber.memoizedState; } const nextState: SuspenseState | null = offscreenFiber.memoizedState; const wasHidden = prevState !== null; const isHidden = nextState !== null; const pendingMarkers = offscreenInstance._pendingMarkers; // If there is a name on the suspense boundary, store that in // the pending boundaries. let name = null; const parent = offscreenFiber.return; if ( parent !== null && parent.tag === SuspenseComponent && parent.memoizedProps.unstable_name ) { name = parent.memoizedProps.unstable_name; } if (!wasHidden && isHidden) { // The suspense boundaries was just hidden. Add the boundary // to the pending boundary set if it's there if (pendingMarkers !== null) { pendingMarkers.forEach(markerInstance => { const pendingBoundaries = markerInstance.pendingBoundaries; const transitions = markerInstance.transitions; const markerName = markerInstance.name; if ( pendingBoundaries !== null && !pendingBoundaries.has(offscreenInstance) ) { pendingBoundaries.set(offscreenInstance, { name, }); if (transitions !== null) { if ( markerInstance.tag === TransitionTracingMarker && markerName !== null ) { addMarkerProgressCallbackToPendingTransition( markerName, transitions, pendingBoundaries, ); } else if (markerInstance.tag === TransitionRoot) { transitions.forEach(transition => { addTransitionProgressCallbackToPendingTransition( transition, pendingBoundaries, ); }); } } } }); } } else if (wasHidden && !isHidden) { // The suspense boundary went from hidden to visible. Remove // the boundary from the pending suspense boundaries set // if it's there if (pendingMarkers !== null) { pendingMarkers.forEach(markerInstance => { const pendingBoundaries = markerInstance.pendingBoundaries; const transitions = markerInstance.transitions; const markerName = markerInstance.name; if ( pendingBoundaries !== null && pendingBoundaries.has(offscreenInstance) ) { pendingBoundaries.delete(offscreenInstance); if (transitions !== null) { if ( markerInstance.tag === TransitionTracingMarker && markerName !== null ) { addMarkerProgressCallbackToPendingTransition( markerName, transitions, pendingBoundaries, ); // If there are no more unresolved suspense boundaries, the interaction // is considered finished if (pendingBoundaries.size === 0) { if (markerInstance.aborts === null) { addMarkerCompleteCallbackToPendingTransition( markerName, transitions, ); } markerInstance.transitions = null; markerInstance.pendingBoundaries = null; markerInstance.aborts = null; } } else if (markerInstance.tag === TransitionRoot) { transitions.forEach(transition => { addTransitionProgressCallbackToPendingTransition( transition, pendingBoundaries, ); }); } } } }); } } } } function hideOrUnhideAllChildren(finishedWork: Fiber, isHidden: boolean) { // Only hide or unhide the top-most host nodes. let hostSubtreeRoot = null; if (supportsMutation) { // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. let node: Fiber = finishedWork; while (true) { if ( node.tag === HostComponent || (enableFloat && supportsResources ? node.tag === HostHoistable : false) || (supportsSingletons ? node.tag === HostSingleton : false) ) { if (hostSubtreeRoot === null) { hostSubtreeRoot = node; try { const instance = node.stateNode; if (isHidden) { hideInstance(instance); } else { unhideInstance(node.stateNode, node.memoizedProps); } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } else if (node.tag === HostText) { if (hostSubtreeRoot === null) { try { const instance = node.stateNode; if (isHidden) { hideTextInstance(instance); } else { unhideTextInstance(instance, node.memoizedProps); } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } else if ( (node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && (node.memoizedState: OffscreenState) !== null && node !== finishedWork ) { // Found a nested Offscreen component that is hidden. // Don't search any deeper. This tree should remain hidden. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === finishedWork) { return; } while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } if (hostSubtreeRoot === node) { hostSubtreeRoot = null; } node = node.return; } if (hostSubtreeRoot === node) { hostSubtreeRoot = null; } node.sibling.return = node.return; node = node.sibling; } } } function commitAttachRef(finishedWork: Fiber) { const ref = finishedWork.ref; if (ref !== null) { const instance = finishedWork.stateNode; let instanceToUse; switch (finishedWork.tag) { case HostHoistable: case HostSingleton: case HostComponent: instanceToUse = getPublicInstance(instance); break; default: instanceToUse = instance; } // Moved outside to ensure DCE works with this flag if (enableScopeAPI && finishedWork.tag === ScopeComponent) { instanceToUse = instance; } if (typeof ref === 'function') { if (shouldProfile(finishedWork)) { try { startLayoutEffectTimer(); finishedWork.refCleanup = ref(instanceToUse); } finally { recordLayoutEffectDuration(finishedWork); } } else { finishedWork.refCleanup = ref(instanceToUse); } } else { if (__DEV__) { if (!ref.hasOwnProperty('current')) { console.error( 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork), ); } } // $FlowFixMe[incompatible-use] unable to narrow type to the non-function case ref.current = instanceToUse; } } } function detachFiberMutation(fiber: Fiber) { // Cut off the return pointer to disconnect it from the tree. // This enables us to detect and warn against state updates on an unmounted component. // It also prevents events from bubbling from within disconnected components. // // Ideally, we should also clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. // This child itself will be GC:ed when the parent updates the next time. // // Note that we can't clear child or sibling pointers yet. // They're needed for passive effects and for findDOMNode. // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). // // Don't reset the alternate yet, either. We need that so we can detach the // alternate's fields in the passive phase. Clearing the return pointer is // sufficient for findDOMNode semantics. const alternate = fiber.alternate; if (alternate !== null) { alternate.return = null; } fiber.return = null; } function detachFiberAfterEffects(fiber: Fiber) { const alternate = fiber.alternate; if (alternate !== null) { fiber.alternate = null; detachFiberAfterEffects(alternate); } // Clear cyclical Fiber fields. This level alone is designed to roughly // approximate the planned Fiber refactor. In that world, `setState` will be // bound to a special "instance" object instead of a Fiber. The Instance // object will not have any of these fields. It will only be connected to // the fiber tree via a single link at the root. So if this level alone is // sufficient to fix memory issues, that bodes well for our plans. fiber.child = null; fiber.deletions = null; fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host // tree, which has its own pointers to children, parents, and siblings. // The other host nodes also point back to fibers, so we should detach that // one, too. if (fiber.tag === HostComponent) { const hostInstance: Instance = fiber.stateNode; if (hostInstance !== null) { detachDeletedInstance(hostInstance); } } fiber.stateNode = null; if (__DEV__) { fiber._debugSource = null; fiber._debugOwner = null; } // Theoretically, nothing in here should be necessary, because we already // disconnected the fiber from the tree. So even if something leaks this // particular fiber, it won't leak anything else. fiber.return = null; fiber.dependencies = null; fiber.memoizedProps = null; fiber.memoizedState = null; fiber.pendingProps = null; fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. fiber.updateQueue = null; } function emptyPortalContainer(current: Fiber) { if (!supportsPersistence) { return; } const portal: { containerInfo: Container, pendingChildren: ChildSet, ... } = current.stateNode; const {containerInfo} = portal; const emptyChildSet = createContainerChildSet(); replaceContainerChildren(containerInfo, emptyChildSet); } function getHostParentFiber(fiber: Fiber): Fiber { let parent = fiber.return; while (parent !== null) { if (isHostParent(parent)) { return parent; } parent = parent.return; } throw new Error( 'Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.', ); } function isHostParent(fiber: Fiber): boolean { return ( fiber.tag === HostComponent || fiber.tag === HostRoot || (enableFloat && supportsResources ? fiber.tag === HostHoistable : false) || (supportsSingletons ? fiber.tag === HostSingleton : false) || fiber.tag === HostPortal ); } function getHostSibling(fiber: Fiber): ?Instance { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. // TODO: Find a more efficient way to do this. let node: Fiber = fiber; siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { if (node.return === null || isHostParent(node.return)) { // If we pop out of the root or hit the parent the fiber we are the // last sibling. return null; } // $FlowFixMe[incompatible-type] found when upgrading Flow node = node.return; } node.sibling.return = node.return; node = node.sibling; while ( node.tag !== HostComponent && node.tag !== HostText && (!supportsSingletons ? true : node.tag !== HostSingleton) && node.tag !== DehydratedFragment ) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.flags & Placement) { // If we don't have a child, try the siblings instead. continue siblings; } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } } // Check if this host node is stable or about to be placed. if (!(node.flags & Placement)) { // Found it! return node.stateNode; } } } function commitPlacement(finishedWork: Fiber): void { if (!supportsMutation) { return; } if (supportsSingletons) { if (finishedWork.tag === HostSingleton) { // Singletons are already in the Host and don't need to be placed // Since they operate somewhat like Portals though their children will // have Placement and will get placed inside them return; } } // Recursively insert all host nodes into the parent. const parentFiber = getHostParentFiber(finishedWork); switch (parentFiber.tag) { case HostSingleton: { if (supportsSingletons) { const parent: Instance = parentFiber.stateNode; const before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. insertOrAppendPlacementNode(finishedWork, before, parent); break; } // Fall through } case HostComponent: { const parent: Instance = parentFiber.stateNode; if (parentFiber.flags & ContentReset) { // Reset the text content of the parent before doing any insertions resetTextContent(parent); // Clear ContentReset from the effect tag parentFiber.flags &= ~ContentReset; } const before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. insertOrAppendPlacementNode(finishedWork, before, parent); break; } case HostRoot: case HostPortal: { const parent: Container = parentFiber.stateNode.containerInfo; const before = getHostSibling(finishedWork); insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent); break; } default: throw new Error( 'Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.', ); } } function insertOrAppendPlacementNodeIntoContainer( node: Fiber, before: ?Instance, parent: Container, ): void { const {tag} = node; const isHost = tag === HostComponent || tag === HostText; if (isHost) { const stateNode = node.stateNode; if (before) { insertInContainerBefore(parent, stateNode, before); } else { appendChildToContainer(parent, stateNode); } } else if ( tag === HostPortal || (supportsSingletons ? tag === HostSingleton : false) ) { // If the insertion itself is a portal, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. // If the insertion is a HostSingleton then it will be placed independently } else { const child = node.child; if (child !== null) { insertOrAppendPlacementNodeIntoContainer(child, before, parent); let sibling = child.sibling; while (sibling !== null) { insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); sibling = sibling.sibling; } } } } function insertOrAppendPlacementNode( node: Fiber, before: ?Instance, parent: Instance, ): void { const {tag} = node; const isHost = tag === HostComponent || tag === HostText; if (isHost) { const stateNode = node.stateNode; if (before) { insertBefore(parent, stateNode, before); } else { appendChild(parent, stateNode); } } else if ( tag === HostPortal || (supportsSingletons ? tag === HostSingleton : false) ) { // If the insertion itself is a portal, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. // If the insertion is a HostSingleton then it will be placed independently } else { const child = node.child; if (child !== null) { insertOrAppendPlacementNode(child, before, parent); let sibling = child.sibling; while (sibling !== null) { insertOrAppendPlacementNode(sibling, before, parent); sibling = sibling.sibling; } } } } // These are tracked on the stack as we recursively traverse a // deleted subtree. // TODO: Update these during the whole mutation phase, not just during // a deletion. let hostParent: Instance | Container | null = null; let hostParentIsContainer: boolean = false; function commitDeletionEffects( root: FiberRoot, returnFiber: Fiber, deletedFiber: Fiber, ) { if (supportsMutation) { // We only have the top Fiber that was deleted but we need to recurse down its // children to find all the terminal nodes. // Recursively delete all host nodes from the parent, detach refs, clean // up mounted layout effects, and call componentWillUnmount. // We only need to remove the topmost host child in each branch. But then we // still need to keep traversing to unmount effects, refs, and cWU. TODO: We // could split this into two separate traversals functions, where the second // one doesn't include any removeChild logic. This is maybe the same // function as "disappearLayoutEffects" (or whatever that turns into after // the layout phase is refactored to use recursion). // Before starting, find the nearest host parent on the stack so we know // which instance/container to remove the children from. // TODO: Instead of searching up the fiber return path on every deletion, we // can track the nearest host component on the JS stack as we traverse the // tree during the commit phase. This would make insertions faster, too. let parent: null | Fiber = returnFiber; findParent: while (parent !== null) { switch (parent.tag) { case HostSingleton: case HostComponent: { hostParent = parent.stateNode; hostParentIsContainer = false; break findParent; } case HostRoot: { hostParent = parent.stateNode.containerInfo; hostParentIsContainer = true; break findParent; } case HostPortal: { hostParent = parent.stateNode.containerInfo; hostParentIsContainer = true; break findParent; } } parent = parent.return; } if (hostParent === null) { throw new Error( 'Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.', ); } commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); hostParent = null; hostParentIsContainer = false; } else { // Detach refs and call componentWillUnmount() on the whole subtree. commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); } detachFiberMutation(deletedFiber); } function recursivelyTraverseDeletionEffects( finishedRoot: FiberRoot, nearestMountedAncestor: Fiber, parent: Fiber, ) { // TODO: Use a static flag to skip trees that don't have unmount effects let child = parent.child; while (child !== null) { commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child); child = child.sibling; } } function commitDeletionEffectsOnFiber( finishedRoot: FiberRoot, nearestMountedAncestor: Fiber, deletedFiber: Fiber, ) { onCommitUnmount(deletedFiber); // The cases in this outer switch modify the stack before they traverse // into their subtree. There are simpler cases in the inner switch // that don't modify the stack. switch (deletedFiber.tag) { case HostHoistable: { if (enableFloat && supportsResources) { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); } recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); if (deletedFiber.memoizedState) { releaseResource(deletedFiber.memoizedState); } else if (deletedFiber.stateNode) { unmountHoistable(deletedFiber.stateNode); } return; } // Fall through } case HostSingleton: { if (supportsSingletons) { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); } const prevHostParent = hostParent; const prevHostParentIsContainer = hostParentIsContainer; hostParent = deletedFiber.stateNode; recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); // Normally this is called in passive unmount effect phase however with // HostSingleton we warn if you acquire one that is already associated to // a different fiber. To increase our chances of avoiding this, specifically // if you keyed a HostSingleton so there will be a delete followed by a Placement // we treat detach eagerly here releaseSingletonInstance(deletedFiber.stateNode); hostParent = prevHostParent; hostParentIsContainer = prevHostParentIsContainer; return; } // Fall through } case HostComponent: { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); } // Intentional fallthrough to next branch } case HostText: { // We only need to remove the nearest host child. Set the host parent // to `null` on the stack to indicate that nested children don't // need to be removed. if (supportsMutation) { const prevHostParent = hostParent; const prevHostParentIsContainer = hostParentIsContainer; hostParent = null; recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); hostParent = prevHostParent; hostParentIsContainer = prevHostParentIsContainer; if (hostParent !== null) { // Now that all the child effects have unmounted, we can remove the // node from the tree. if (hostParentIsContainer) { removeChildFromContainer( ((hostParent: any): Container), (deletedFiber.stateNode: Instance | TextInstance), ); } else { removeChild( ((hostParent: any): Instance), (deletedFiber.stateNode: Instance | TextInstance), ); } } } else { recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); } return; } case DehydratedFragment: { if (enableSuspenseCallback) { const hydrationCallbacks = finishedRoot.hydrationCallbacks; if (hydrationCallbacks !== null) { const onDeleted = hydrationCallbacks.onDeleted; if (onDeleted) { onDeleted((deletedFiber.stateNode: SuspenseInstance)); } } } // Dehydrated fragments don't have any children // Delete the dehydrated suspense boundary and all of its content. if (supportsMutation) { if (hostParent !== null) { if (hostParentIsContainer) { clearSuspenseBoundaryFromContainer( ((hostParent: any): Container), (deletedFiber.stateNode: SuspenseInstance), ); } else { clearSuspenseBoundary( ((hostParent: any): Instance), (deletedFiber.stateNode: SuspenseInstance), ); } } } return; } case HostPortal: { if (supportsMutation) { // When we go into a portal, it becomes the parent to remove from. const prevHostParent = hostParent; const prevHostParentIsContainer = hostParentIsContainer; hostParent = deletedFiber.stateNode.containerInfo; hostParentIsContainer = true; recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); hostParent = prevHostParent; hostParentIsContainer = prevHostParentIsContainer; } else { emptyPortalContainer(deletedFiber); recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); } return; } case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { if (!offscreenSubtreeWasHidden) { const updateQueue: FunctionComponentUpdateQueue | null = (deletedFiber.updateQueue: any); if (updateQueue !== null) { const lastEffect = updateQueue.lastEffect; if (lastEffect !== null) { const firstEffect = lastEffect.next; let effect = firstEffect; do { const tag = effect.tag; const inst = effect.inst; const destroy = inst.destroy; if (destroy !== undefined) { if ((tag & HookInsertion) !== NoHookEffect) { inst.destroy = undefined; safelyCallDestroy( deletedFiber, nearestMountedAncestor, destroy, ); } else if ((tag & HookLayout) !== NoHookEffect) { if (enableSchedulingProfiler) { markComponentLayoutEffectUnmountStarted(deletedFiber); } if (shouldProfile(deletedFiber)) { startLayoutEffectTimer(); inst.destroy = undefined; safelyCallDestroy( deletedFiber, nearestMountedAncestor, destroy, ); recordLayoutEffectDuration(deletedFiber); } else { inst.destroy = undefined; safelyCallDestroy( deletedFiber, nearestMountedAncestor, destroy, ); } if (enableSchedulingProfiler) { markComponentLayoutEffectUnmountStopped(); } } } effect = effect.next; } while (effect !== firstEffect); } } } recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); return; } case ClassComponent: { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); const instance = deletedFiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount( deletedFiber, nearestMountedAncestor, instance, ); } } recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); return; } case ScopeComponent: { if (enableScopeAPI) { safelyDetachRef(deletedFiber, nearestMountedAncestor); } recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); return; } case OffscreenComponent: { safelyDetachRef(deletedFiber, nearestMountedAncestor); if (deletedFiber.mode & ConcurrentMode) { // If this offscreen component is hidden, we already unmounted it. Before // deleting the children, track that it's already unmounted so that we // don't attempt to unmount the effects again. // TODO: If the tree is hidden, in most cases we should be able to skip // over the nested children entirely. An exception is we haven't yet found // the topmost host node to delete, which we already track on the stack. // But the other case is portals, which need to be detached no matter how // deeply they are nested. We should use a subtree flag to track whether a // subtree includes a nested portal. const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null; recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; } else { recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); } break; } default: { recursivelyTraverseDeletionEffects( finishedRoot, nearestMountedAncestor, deletedFiber, ); return; } } } function commitSuspenseCallback(finishedWork: Fiber) { // TODO: Move this to passive phase const newState: SuspenseState | null = finishedWork.memoizedState; if (enableSuspenseCallback && newState !== null) { const suspenseCallback = finishedWork.memoizedProps.suspenseCallback; if (typeof suspenseCallback === 'function') { const retryQueue: RetryQueue | null = (finishedWork.updateQueue: any); if (retryQueue !== null) { suspenseCallback(new Set(retryQueue)); } } else if (__DEV__) { if (suspenseCallback !== undefined) { console.error('Unexpected type for suspenseCallback.'); } } } } function commitSuspenseHydrationCallbacks( finishedRoot: FiberRoot, finishedWork: Fiber, ) { if (!supportsHydration) { return; } const newState: SuspenseState | null = finishedWork.memoizedState; if (newState === null) { const current = finishedWork.alternate; if (current !== null) { const prevState: SuspenseState | null = current.memoizedState; if (prevState !== null) { const suspenseInstance = prevState.dehydrated; if (suspenseInstance !== null) { try { commitHydratedSuspenseInstance(suspenseInstance); if (enableSuspenseCallback) { const hydrationCallbacks = finishedRoot.hydrationCallbacks; if (hydrationCallbacks !== null) { const onHydrated = hydrationCallbacks.onHydrated; if (onHydrated) { onHydrated(suspenseInstance); } } } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } } } } function getRetryCache(finishedWork: Fiber) { // TODO: Unify the interface for the retry cache so we don't have to switch // on the tag like this. switch (finishedWork.tag) { case SuspenseComponent: case SuspenseListComponent: { let retryCache = finishedWork.stateNode; if (retryCache === null) { retryCache = finishedWork.stateNode = new PossiblyWeakSet(); } return retryCache; } case OffscreenComponent: { const instance: OffscreenInstance = finishedWork.stateNode; let retryCache: null | Set<Wakeable> | WeakSet<Wakeable> = instance._retryCache; if (retryCache === null) { retryCache = instance._retryCache = new PossiblyWeakSet(); } return retryCache; } default: { throw new Error( `Unexpected Suspense handler tag (${finishedWork.tag}). This is a ` + 'bug in React.', ); } } } export function detachOffscreenInstance(instance: OffscreenInstance): void { const fiber = instance._current; if (fiber === null) { throw new Error( 'Calling Offscreen.detach before instance handle has been set.', ); } if ((instance._pendingVisibility & OffscreenDetached) !== NoFlags) { // The instance is already detached, this is a noop. return; } // TODO: There is an opportunity to optimise this by not entering commit phase // and unmounting effects directly. const root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { instance._pendingVisibility |= OffscreenDetached; scheduleUpdateOnFiber(root, fiber, SyncLane); } } export function attachOffscreenInstance(instance: OffscreenInstance): void { const fiber = instance._current; if (fiber === null) { throw new Error( 'Calling Offscreen.detach before instance handle has been set.', ); } if ((instance._pendingVisibility & OffscreenDetached) === NoFlags) { // The instance is already attached, this is a noop. return; } const root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { instance._pendingVisibility &= ~OffscreenDetached; scheduleUpdateOnFiber(root, fiber, SyncLane); } } function attachSuspenseRetryListeners( finishedWork: Fiber, wakeables: RetryQueue, ) { // If this boundary just timed out, then it will have a set of wakeables. // For each wakeable, attach a listener so that when it resolves, React // attempts to re-render the boundary in the primary (pre-timeout) state. const retryCache = getRetryCache(finishedWork); wakeables.forEach(wakeable => { // Memoize using the boundary fiber to prevent redundant listeners. const retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); if (!retryCache.has(wakeable)) { retryCache.add(wakeable); if (enableUpdaterTracking) { if (isDevToolsPresent) { if (inProgressLanes !== null && inProgressRoot !== null) { // If we have pending work still, associate the original updaters with it. restorePendingUpdaters(inProgressRoot, inProgressLanes); } else { throw Error( 'Expected finished root and lanes to be set. This is a bug in React.', ); } } } wakeable.then(retry, retry); } }); } // This function detects when a Suspense boundary goes from visible to hidden. // It returns false if the boundary is already hidden. // TODO: Use an effect tag. export function isSuspenseBoundaryBeingHidden( current: Fiber | null, finishedWork: Fiber, ): boolean { if (current !== null) { const oldState: SuspenseState | null = current.memoizedState; if (oldState === null || oldState.dehydrated !== null) { const newState: SuspenseState | null = finishedWork.memoizedState; return newState !== null && newState.dehydrated === null; } } return false; } export function commitMutationEffects( root: FiberRoot, finishedWork: Fiber, committedLanes: Lanes, ) { inProgressLanes = committedLanes; inProgressRoot = root; setCurrentDebugFiberInDEV(finishedWork); commitMutationEffectsOnFiber(finishedWork, root, committedLanes); setCurrentDebugFiberInDEV(finishedWork); inProgressLanes = null; inProgressRoot = null; } function recursivelyTraverseMutationEffects( root: FiberRoot, parentFiber: Fiber, lanes: Lanes, ) { // Deletions effects can be scheduled on any fiber type. They need to happen // before the children effects hae fired. const deletions = parentFiber.deletions; if (deletions !== null) { for (let i = 0; i < deletions.length; i++) { const childToDelete = deletions[i]; try { commitDeletionEffects(root, parentFiber, childToDelete); } catch (error) { captureCommitPhaseError(childToDelete, parentFiber, error); } } } const prevDebugFiber = getCurrentDebugFiberInDEV(); if (parentFiber.subtreeFlags & MutationMask) { let child = parentFiber.child; while (child !== null) { setCurrentDebugFiberInDEV(child); commitMutationEffectsOnFiber(child, root, lanes); child = child.sibling; } } setCurrentDebugFiberInDEV(prevDebugFiber); } let currentHoistableRoot: HoistableRoot | null = null; function commitMutationEffectsOnFiber( finishedWork: Fiber, root: FiberRoot, lanes: Lanes, ) { const current = finishedWork.alternate; const flags = finishedWork.flags; // The effect flag should be checked *after* we refine the type of fiber, // because the fiber tag is more specific. An exception is any flag related // to reconciliation, because those can be set on all fiber types. switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); if (flags & Update) { try { commitHookEffectListUnmount( HookInsertion | HookHasEffect, finishedWork, finishedWork.return, ); commitHookEffectListMount( HookInsertion | HookHasEffect, finishedWork, ); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } // Layout effects are destroyed during the mutation phase so that all // destroy functions for all fibers are called before any create functions. // This prevents sibling component effects from interfering with each other, // e.g. a destroy function in one component should never override a ref set // by a create function in another component during the same commit. if (shouldProfile(finishedWork)) { try { startLayoutEffectTimer(); commitHookEffectListUnmount( HookLayout | HookHasEffect, finishedWork, finishedWork.return, ); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } recordLayoutEffectDuration(finishedWork); } else { try { commitHookEffectListUnmount( HookLayout | HookHasEffect, finishedWork, finishedWork.return, ); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case ClassComponent: { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } if (flags & Callback && offscreenSubtreeIsHidden) { const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any); if (updateQueue !== null) { deferHiddenCallbacks(updateQueue); } } return; } case HostHoistable: { if (enableFloat && supportsResources) { // We cast because we always set the root at the React root and so it cannot be // null while we are processing mutation effects const hoistableRoot: HoistableRoot = (currentHoistableRoot: any); recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } if (flags & Update) { const currentResource = current !== null ? current.memoizedState : null; const newResource = finishedWork.memoizedState; if (current === null) { // We are mounting a new HostHoistable Fiber. We fork the mount // behavior based on whether this instance is a Hoistable Instance // or a Hoistable Resource if (newResource === null) { if (finishedWork.stateNode === null) { finishedWork.stateNode = hydrateHoistable( hoistableRoot, finishedWork.type, finishedWork.memoizedProps, finishedWork, ); } else { mountHoistable( hoistableRoot, finishedWork.type, finishedWork.stateNode, ); } } else { finishedWork.stateNode = acquireResource( hoistableRoot, newResource, finishedWork.memoizedProps, ); } } else if (currentResource !== newResource) { // We are moving to or from Hoistable Resource, or between different Hoistable Resources if (currentResource === null) { if (current.stateNode !== null) { unmountHoistable(current.stateNode); } } else { releaseResource(currentResource); } if (newResource === null) { mountHoistable( hoistableRoot, finishedWork.type, finishedWork.stateNode, ); } else { acquireResource( hoistableRoot, newResource, finishedWork.memoizedProps, ); } } else if (newResource === null && finishedWork.stateNode !== null) { // We may have an update on a Hoistable element const updatePayload: null | UpdatePayload = (finishedWork.updateQueue: any); finishedWork.updateQueue = null; try { commitUpdate( finishedWork.stateNode, updatePayload, finishedWork.type, current.memoizedProps, finishedWork.memoizedProps, finishedWork, ); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } // Fall through } case HostSingleton: { if (supportsSingletons) { if (flags & Update) { const previousWork = finishedWork.alternate; if (previousWork === null) { const singleton = finishedWork.stateNode; const props = finishedWork.memoizedProps; // This was a new mount, we need to clear and set initial properties clearSingleton(singleton); acquireSingletonInstance( finishedWork.type, props, singleton, finishedWork, ); } } } // Fall through } case HostComponent: { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } if (supportsMutation) { // TODO: ContentReset gets cleared by the children during the commit // phase. This is a refactor hazard because it means we must read // flags the flags after `commitReconciliationEffects` has already run; // the order matters. We should refactor so that ContentReset does not // rely on mutating the flag during commit. Like by setting a flag // during the render phase instead. if (finishedWork.flags & ContentReset) { const instance: Instance = finishedWork.stateNode; try { resetTextContent(instance); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } if (flags & Update) { const instance: Instance = finishedWork.stateNode; if (instance != null) { // Commit the work prepared earlier. const newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. const oldProps = current !== null ? current.memoizedProps : newProps; const type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. const updatePayload: null | UpdatePayload = (finishedWork.updateQueue: any); finishedWork.updateQueue = null; try { commitUpdate( instance, updatePayload, type, oldProps, newProps, finishedWork, ); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } } return; } case HostText: { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); if (flags & Update) { if (supportsMutation) { if (finishedWork.stateNode === null) { throw new Error( 'This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.', ); } const textInstance: TextInstance = finishedWork.stateNode; const newText: string = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. const oldText: string = current !== null ? current.memoizedProps : newText; try { commitTextUpdate(textInstance, oldText, newText); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case HostRoot: { if (enableFloat && supportsResources) { prepareToCommitHoistables(); const previousHoistableRoot = currentHoistableRoot; currentHoistableRoot = getHoistableRoot(root.containerInfo); recursivelyTraverseMutationEffects(root, finishedWork, lanes); currentHoistableRoot = previousHoistableRoot; commitReconciliationEffects(finishedWork); } else { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); } if (flags & Update) { if (supportsMutation && supportsHydration) { if (current !== null) { const prevRootState: RootState = current.memoizedState; if (prevRootState.isDehydrated) { try { commitHydratedContainer(root.containerInfo); } catch (error) { captureCommitPhaseError( finishedWork, finishedWork.return, error, ); } } } } if (supportsPersistence) { const containerInfo = root.containerInfo; const pendingChildren = root.pendingChildren; try { replaceContainerChildren(containerInfo, pendingChildren); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case HostPortal: { if (enableFloat && supportsResources) { const previousHoistableRoot = currentHoistableRoot; currentHoistableRoot = getHoistableRoot( finishedWork.stateNode.containerInfo, ); recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); currentHoistableRoot = previousHoistableRoot; } else { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); } if (flags & Update) { if (supportsPersistence) { const portal = finishedWork.stateNode; const containerInfo = portal.containerInfo; const pendingChildren = portal.pendingChildren; try { replaceContainerChildren(containerInfo, pendingChildren); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case SuspenseComponent: { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); // TODO: We should mark a flag on the Suspense fiber itself, rather than // relying on the Offscreen fiber having a flag also being marked. The // reason is that this offscreen fiber might not be part of the work-in- // progress tree! It could have been reused from a previous render. This // doesn't lead to incorrect behavior because we don't rely on the flag // check alone; we also compare the states explicitly below. But for // modeling purposes, we _should_ be able to rely on the flag check alone. // So this is a bit fragile. // // Also, all this logic could/should move to the passive phase so it // doesn't block paint. const offscreenFiber: Fiber = (finishedWork.child: any); if (offscreenFiber.flags & Visibility) { // Throttle the appearance and disappearance of Suspense fallbacks. const isShowingFallback = (finishedWork.memoizedState: SuspenseState | null) !== null; const wasShowingFallback = current !== null && (current.memoizedState: SuspenseState | null) !== null; if (alwaysThrottleRetries) { if (isShowingFallback !== wasShowingFallback) { // A fallback is either appearing or disappearing. markCommitTimeOfFallback(); } } else { if (isShowingFallback && !wasShowingFallback) { // Old behavior. Only mark when a fallback appears, not when // it disappears. markCommitTimeOfFallback(); } } } if (flags & Update) { try { commitSuspenseCallback(finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } const retryQueue: RetryQueue | null = (finishedWork.updateQueue: any); if (retryQueue !== null) { finishedWork.updateQueue = null; attachSuspenseRetryListeners(finishedWork, retryQueue); } } return; } case OffscreenComponent: { if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } const newState: OffscreenState | null = finishedWork.memoizedState; const isHidden = newState !== null; const wasHidden = current !== null && current.memoizedState !== null; if (finishedWork.mode & ConcurrentMode) { // Before committing the children, track on the stack whether this // offscreen subtree was already hidden, so that we don't unmount the // effects again. const prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; const prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || isHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden; recursivelyTraverseMutationEffects(root, finishedWork, lanes); offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; } else { recursivelyTraverseMutationEffects(root, finishedWork, lanes); } commitReconciliationEffects(finishedWork); const offscreenInstance: OffscreenInstance = finishedWork.stateNode; // TODO: Add explicit effect flag to set _current. offscreenInstance._current = finishedWork; // Offscreen stores pending changes to visibility in `_pendingVisibility`. This is // to support batching of `attach` and `detach` calls. offscreenInstance._visibility &= ~OffscreenDetached; offscreenInstance._visibility |= offscreenInstance._pendingVisibility & OffscreenDetached; if (flags & Visibility) { // Track the current state on the Offscreen instance so we can // read it during an event if (isHidden) { offscreenInstance._visibility &= ~OffscreenVisible; } else { offscreenInstance._visibility |= OffscreenVisible; } if (isHidden) { const isUpdate = current !== null; const wasHiddenByAncestorOffscreen = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden; // Only trigger disapper layout effects if: // - This is an update, not first mount. // - This Offscreen was not hidden before. // - Ancestor Offscreen was not hidden in previous commit. if (isUpdate && !wasHidden && !wasHiddenByAncestorOffscreen) { if ((finishedWork.mode & ConcurrentMode) !== NoMode) { // Disappear the layout effects of all the children recursivelyTraverseDisappearLayoutEffects(finishedWork); } } } else { if (wasHidden) { // TODO: Move re-appear call here for symmetry? } } // Offscreen with manual mode manages visibility manually. if (supportsMutation && !isOffscreenManual(finishedWork)) { // TODO: This needs to run whenever there's an insertion or update // inside a hidden Offscreen tree. hideOrUnhideAllChildren(finishedWork, isHidden); } } // TODO: Move to passive phase if (flags & Update) { const offscreenQueue: OffscreenQueue | null = (finishedWork.updateQueue: any); if (offscreenQueue !== null) { const retryQueue = offscreenQueue.retryQueue; if (retryQueue !== null) { offscreenQueue.retryQueue = null; attachSuspenseRetryListeners(finishedWork, retryQueue); } } } return; } case SuspenseListComponent: { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); if (flags & Update) { const retryQueue: Set<Wakeable> | null = (finishedWork.updateQueue: any); if (retryQueue !== null) { finishedWork.updateQueue = null; attachSuspenseRetryListeners(finishedWork, retryQueue); } } return; } case ScopeComponent: { if (enableScopeAPI) { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); // TODO: This is a temporary solution that allowed us to transition away // from React Flare on www. if (flags & Ref) { if (current !== null) { safelyDetachRef(finishedWork, finishedWork.return); } safelyAttachRef(finishedWork, finishedWork.return); } if (flags & Update) { const scopeInstance = finishedWork.stateNode; prepareScopeUpdate(scopeInstance, finishedWork); } } return; } default: { recursivelyTraverseMutationEffects(root, finishedWork, lanes); commitReconciliationEffects(finishedWork); return; } } } function commitReconciliationEffects(finishedWork: Fiber) { // Placement effects (insertions, reorders) can be scheduled on any fiber // type. They needs to happen after the children effects have fired, but // before the effects on this fiber have fired. const flags = finishedWork.flags; if (flags & Placement) { try { commitPlacement(finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted does // and isMounted is deprecated anyway so we should be able to kill this. finishedWork.flags &= ~Placement; } if (flags & Hydrating) { finishedWork.flags &= ~Hydrating; } } export function commitLayoutEffects( finishedWork: Fiber, root: FiberRoot, committedLanes: Lanes, ): void { inProgressLanes = committedLanes; inProgressRoot = root; const current = finishedWork.alternate; commitLayoutEffectOnFiber(root, current, finishedWork, committedLanes); inProgressLanes = null; inProgressRoot = null; } function recursivelyTraverseLayoutEffects( root: FiberRoot, parentFiber: Fiber, lanes: Lanes, ) { const prevDebugFiber = getCurrentDebugFiberInDEV(); if (parentFiber.subtreeFlags & LayoutMask) { let child = parentFiber.child; while (child !== null) { setCurrentDebugFiberInDEV(child); const current = child.alternate; commitLayoutEffectOnFiber(root, current, child, lanes); child = child.sibling; } } setCurrentDebugFiberInDEV(prevDebugFiber); } export function disappearLayoutEffects(finishedWork: Fiber) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { // TODO (Offscreen) Check: flags & LayoutStatic if (shouldProfile(finishedWork)) { try { startLayoutEffectTimer(); commitHookEffectListUnmount( HookLayout, finishedWork, finishedWork.return, ); } finally { recordLayoutEffectDuration(finishedWork); } } else { commitHookEffectListUnmount( HookLayout, finishedWork, finishedWork.return, ); } recursivelyTraverseDisappearLayoutEffects(finishedWork); break; } case ClassComponent: { // TODO (Offscreen) Check: flags & RefStatic safelyDetachRef(finishedWork, finishedWork.return); const instance = finishedWork.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount( finishedWork, finishedWork.return, instance, ); } recursivelyTraverseDisappearLayoutEffects(finishedWork); break; } case HostHoistable: case HostSingleton: case HostComponent: { // TODO (Offscreen) Check: flags & RefStatic safelyDetachRef(finishedWork, finishedWork.return); recursivelyTraverseDisappearLayoutEffects(finishedWork); break; } case OffscreenComponent: { // TODO (Offscreen) Check: flags & RefStatic safelyDetachRef(finishedWork, finishedWork.return); const isHidden = finishedWork.memoizedState !== null; if (isHidden) { // Nested Offscreen tree is already hidden. Don't disappear // its effects. } else { recursivelyTraverseDisappearLayoutEffects(finishedWork); } break; } default: { recursivelyTraverseDisappearLayoutEffects(finishedWork); break; } } } function recursivelyTraverseDisappearLayoutEffects(parentFiber: Fiber) { // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) let child = parentFiber.child; while (child !== null) { disappearLayoutEffects(child); child = child.sibling; } } export function reappearLayoutEffects( finishedRoot: FiberRoot, current: Fiber | null, finishedWork: Fiber, // This function visits both newly finished work and nodes that were re-used // from a previously committed tree. We cannot check non-static flags if the // node was reused. includeWorkInProgressEffects: boolean, ) { // Turn on layout effects in a tree that previously disappeared. const flags = finishedWork.flags; switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); // TODO: Check flags & LayoutStatic commitHookLayoutEffects(finishedWork, HookLayout); break; } case ClassComponent: { recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); // TODO: Check for LayoutStatic flag const instance = finishedWork.stateNode; if (typeof instance.componentDidMount === 'function') { try { instance.componentDidMount(); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } // Commit any callbacks that would have fired while the component // was hidden. const updateQueue: UpdateQueue<mixed> | null = (finishedWork.updateQueue: any); if (updateQueue !== null) { commitHiddenCallbacks(updateQueue, instance); } // If this is newly finished work, check for setState callbacks if (includeWorkInProgressEffects && flags & Callback) { commitClassCallbacks(finishedWork); } // TODO: Check flags & RefStatic safelyAttachRef(finishedWork, finishedWork.return); break; } // Unlike commitLayoutEffectsOnFiber, we don't need to handle HostRoot // because this function only visits nodes that are inside an // Offscreen fiber. // case HostRoot: { // ... // } case HostHoistable: case HostSingleton: case HostComponent: { recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. if (includeWorkInProgressEffects && current === null && flags & Update) { commitHostComponentMount(finishedWork); } // TODO: Check flags & Ref safelyAttachRef(finishedWork, finishedWork.return); break; } case Profiler: { recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); // TODO: Figure out how Profiler updates should work with Offscreen if (includeWorkInProgressEffects && flags & Update) { commitProfilerUpdate(finishedWork, current); } break; } case SuspenseComponent: { recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); // TODO: Figure out how Suspense hydration callbacks should work // with Offscreen. if (includeWorkInProgressEffects && flags & Update) { commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); } break; } case OffscreenComponent: { const offscreenState: OffscreenState = finishedWork.memoizedState; const isHidden = offscreenState !== null; if (isHidden) { // Nested Offscreen tree is still hidden. Don't re-appear its effects. } else { recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); } // TODO: Check flags & Ref safelyAttachRef(finishedWork, finishedWork.return); break; } default: { recursivelyTraverseReappearLayoutEffects( finishedRoot, finishedWork, includeWorkInProgressEffects, ); break; } } } function recursivelyTraverseReappearLayoutEffects( finishedRoot: FiberRoot, parentFiber: Fiber, includeWorkInProgressEffects: boolean, ) { // This function visits both newly finished work and nodes that were re-used // from a previously committed tree. We cannot check non-static flags if the // node was reused. const childShouldIncludeWorkInProgressEffects = includeWorkInProgressEffects && (parentFiber.subtreeFlags & LayoutMask) !== NoFlags; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) const prevDebugFiber = getCurrentDebugFiberInDEV(); let child = parentFiber.child; while (child !== null) { const current = child.alternate; reappearLayoutEffects( finishedRoot, current, child, childShouldIncludeWorkInProgressEffects, ); child = child.sibling; } setCurrentDebugFiberInDEV(prevDebugFiber); } function commitHookPassiveMountEffects( finishedWork: Fiber, hookFlags: HookFlags, ) { if (shouldProfile(finishedWork)) { startPassiveEffectTimer(); try { commitHookEffectListMount(hookFlags, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } recordPassiveEffectDuration(finishedWork); } else { try { commitHookEffectListMount(hookFlags, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } function commitOffscreenPassiveMountEffects( current: Fiber | null, finishedWork: Fiber, instance: OffscreenInstance, ) { if (enableCache) { let previousCache: Cache | null = null; if ( current !== null && current.memoizedState !== null && current.memoizedState.cachePool !== null ) { previousCache = current.memoizedState.cachePool.pool; } let nextCache: Cache | null = null; if ( finishedWork.memoizedState !== null && finishedWork.memoizedState.cachePool !== null ) { nextCache = finishedWork.memoizedState.cachePool.pool; } // Retain/release the cache used for pending (suspended) nodes. // Note that this is only reached in the non-suspended/visible case: // when the content is suspended/hidden, the retain/release occurs // via the parent Suspense component (see case above). if (nextCache !== previousCache) { if (nextCache != null) { retainCache(nextCache); } if (previousCache != null) { releaseCache(previousCache); } } } if (enableTransitionTracing) { // TODO: Pre-rendering should not be counted as part of a transition. We // may add separate logs for pre-rendering, but it's not part of the // primary metrics. const offscreenState: OffscreenState = finishedWork.memoizedState; const queue: OffscreenQueue | null = (finishedWork.updateQueue: any); const isHidden = offscreenState !== null; if (queue !== null) { if (isHidden) { const transitions = queue.transitions; if (transitions !== null) { transitions.forEach(transition => { // Add all the transitions saved in the update queue during // the render phase (ie the transitions associated with this boundary) // into the transitions set. if (instance._transitions === null) { instance._transitions = new Set(); } instance._transitions.add(transition); }); } const markerInstances = queue.markerInstances; if (markerInstances !== null) { markerInstances.forEach(markerInstance => { const markerTransitions = markerInstance.transitions; // There should only be a few tracing marker transitions because // they should be only associated with the transition that // caused them if (markerTransitions !== null) { markerTransitions.forEach(transition => { if (instance._transitions === null) { instance._transitions = new Set(); } else if (instance._transitions.has(transition)) { if (markerInstance.pendingBoundaries === null) { markerInstance.pendingBoundaries = new Map(); } if (instance._pendingMarkers === null) { instance._pendingMarkers = new Set(); } instance._pendingMarkers.add(markerInstance); } }); } }); } } finishedWork.updateQueue = null; } commitTransitionProgress(finishedWork); // TODO: Refactor this into an if/else branch if (!isHidden) { instance._transitions = null; instance._pendingMarkers = null; } } } function commitCachePassiveMountEffect( current: Fiber | null, finishedWork: Fiber, ) { if (enableCache) { let previousCache: Cache | null = null; if (finishedWork.alternate !== null) { previousCache = finishedWork.alternate.memoizedState.cache; } const nextCache = finishedWork.memoizedState.cache; // Retain/release the cache. In theory the cache component // could be "borrowing" a cache instance owned by some parent, // in which case we could avoid retaining/releasing. But it // is non-trivial to determine when that is the case, so we // always retain/release. if (nextCache !== previousCache) { retainCache(nextCache); if (previousCache != null) { releaseCache(previousCache); } } } } function commitTracingMarkerPassiveMountEffect(finishedWork: Fiber) { // Get the transitions that were initiatized during the render // and add a start transition callback for each of them // We will only call this on initial mount of the tracing marker // only if there are no suspense children const instance = finishedWork.stateNode; if (instance.transitions !== null && instance.pendingBoundaries === null) { addMarkerCompleteCallbackToPendingTransition( finishedWork.memoizedProps.name, instance.transitions, ); instance.transitions = null; instance.pendingBoundaries = null; instance.aborts = null; instance.name = null; } } export function commitPassiveMountEffects( root: FiberRoot, finishedWork: Fiber, committedLanes: Lanes, committedTransitions: Array<Transition> | null, ): void { setCurrentDebugFiberInDEV(finishedWork); commitPassiveMountOnFiber( root, finishedWork, committedLanes, committedTransitions, ); resetCurrentDebugFiberInDEV(); } function recursivelyTraversePassiveMountEffects( root: FiberRoot, parentFiber: Fiber, committedLanes: Lanes, committedTransitions: Array<Transition> | null, ) { const prevDebugFiber = getCurrentDebugFiberInDEV(); if (parentFiber.subtreeFlags & PassiveMask) { let child = parentFiber.child; while (child !== null) { setCurrentDebugFiberInDEV(child); commitPassiveMountOnFiber( root, child, committedLanes, committedTransitions, ); child = child.sibling; } } setCurrentDebugFiberInDEV(prevDebugFiber); } function commitPassiveMountOnFiber( finishedRoot: FiberRoot, finishedWork: Fiber, committedLanes: Lanes, committedTransitions: Array<Transition> | null, ): void { // When updating this function, also update reconnectPassiveEffects, which does // most of the same things when an offscreen tree goes from hidden -> visible, // or when toggling effects inside a hidden tree. const flags = finishedWork.flags; switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); if (flags & Passive) { commitHookPassiveMountEffects( finishedWork, HookPassive | HookHasEffect, ); } break; } case HostRoot: { recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); if (flags & Passive) { if (enableCache) { let previousCache: Cache | null = null; if (finishedWork.alternate !== null) { previousCache = finishedWork.alternate.memoizedState.cache; } const nextCache = finishedWork.memoizedState.cache; // Retain/release the root cache. // Note that on initial mount, previousCache and nextCache will be the same // and this retain won't occur. To counter this, we instead retain the HostRoot's // initial cache when creating the root itself (see createFiberRoot() in // ReactFiberRoot.js). Subsequent updates that change the cache are reflected // here, such that previous/next caches are retained correctly. if (nextCache !== previousCache) { retainCache(nextCache); if (previousCache != null) { releaseCache(previousCache); } } } if (enableTransitionTracing) { // Get the transitions that were initiatized during the render // and add a start transition callback for each of them const root: FiberRoot = finishedWork.stateNode; const incompleteTransitions = root.incompleteTransitions; // Initial render if (committedTransitions !== null) { committedTransitions.forEach(transition => { addTransitionStartCallbackToPendingTransition(transition); }); clearTransitionsForLanes(finishedRoot, committedLanes); } incompleteTransitions.forEach((markerInstance, transition) => { const pendingBoundaries = markerInstance.pendingBoundaries; if (pendingBoundaries === null || pendingBoundaries.size === 0) { if (markerInstance.aborts === null) { addTransitionCompleteCallbackToPendingTransition(transition); } incompleteTransitions.delete(transition); } }); clearTransitionsForLanes(finishedRoot, committedLanes); } } break; } case LegacyHiddenComponent: { if (enableLegacyHidden) { recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); if (flags & Passive) { const current = finishedWork.alternate; const instance: OffscreenInstance = finishedWork.stateNode; commitOffscreenPassiveMountEffects(current, finishedWork, instance); } } break; } case OffscreenComponent: { // TODO: Pass `current` as argument to this function const instance: OffscreenInstance = finishedWork.stateNode; const nextState: OffscreenState | null = finishedWork.memoizedState; const isHidden = nextState !== null; if (isHidden) { if (instance._visibility & OffscreenPassiveEffectsConnected) { // The effects are currently connected. Update them. recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); } else { if (finishedWork.mode & ConcurrentMode) { // The effects are currently disconnected. Since the tree is hidden, // don't connect them. This also applies to the initial render. if (enableCache || enableTransitionTracing) { // "Atomic" effects are ones that need to fire on every commit, // even during pre-rendering. An example is updating the reference // count on cache instances. recursivelyTraverseAtomicPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); } } else { // Legacy Mode: Fire the effects even if the tree is hidden. instance._visibility |= OffscreenPassiveEffectsConnected; recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); } } } else { // Tree is visible if (instance._visibility & OffscreenPassiveEffectsConnected) { // The effects are currently connected. Update them. recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); } else { // The effects are currently disconnected. Reconnect them, while also // firing effects inside newly mounted trees. This also applies to // the initial render. instance._visibility |= OffscreenPassiveEffectsConnected; const includeWorkInProgressEffects = (finishedWork.subtreeFlags & PassiveMask) !== NoFlags; recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); } } if (flags & Passive) { const current = finishedWork.alternate; commitOffscreenPassiveMountEffects(current, finishedWork, instance); } break; } case CacheComponent: { recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); if (flags & Passive) { // TODO: Pass `current` as argument to this function const current = finishedWork.alternate; commitCachePassiveMountEffect(current, finishedWork); } break; } case TracingMarkerComponent: { if (enableTransitionTracing) { recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); if (flags & Passive) { commitTracingMarkerPassiveMountEffect(finishedWork); } break; } // Intentional fallthrough to next branch } default: { recursivelyTraversePassiveMountEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); break; } } } function recursivelyTraverseReconnectPassiveEffects( finishedRoot: FiberRoot, parentFiber: Fiber, committedLanes: Lanes, committedTransitions: Array<Transition> | null, includeWorkInProgressEffects: boolean, ) { // This function visits both newly finished work and nodes that were re-used // from a previously committed tree. We cannot check non-static flags if the // node was reused. const childShouldIncludeWorkInProgressEffects = includeWorkInProgressEffects && (parentFiber.subtreeFlags & PassiveMask) !== NoFlags; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) const prevDebugFiber = getCurrentDebugFiberInDEV(); let child = parentFiber.child; while (child !== null) { reconnectPassiveEffects( finishedRoot, child, committedLanes, committedTransitions, childShouldIncludeWorkInProgressEffects, ); child = child.sibling; } setCurrentDebugFiberInDEV(prevDebugFiber); } export function reconnectPassiveEffects( finishedRoot: FiberRoot, finishedWork: Fiber, committedLanes: Lanes, committedTransitions: Array<Transition> | null, // This function visits both newly finished work and nodes that were re-used // from a previously committed tree. We cannot check non-static flags if the // node was reused. includeWorkInProgressEffects: boolean, ) { const flags = finishedWork.flags; switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); // TODO: Check for PassiveStatic flag commitHookPassiveMountEffects(finishedWork, HookPassive); break; } // Unlike commitPassiveMountOnFiber, we don't need to handle HostRoot // because this function only visits nodes that are inside an // Offscreen fiber. // case HostRoot: { // ... // } case LegacyHiddenComponent: { if (enableLegacyHidden) { recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); if (includeWorkInProgressEffects && flags & Passive) { // TODO: Pass `current` as argument to this function const current: Fiber | null = finishedWork.alternate; const instance: OffscreenInstance = finishedWork.stateNode; commitOffscreenPassiveMountEffects(current, finishedWork, instance); } } break; } case OffscreenComponent: { const instance: OffscreenInstance = finishedWork.stateNode; const nextState: OffscreenState | null = finishedWork.memoizedState; const isHidden = nextState !== null; if (isHidden) { if (instance._visibility & OffscreenPassiveEffectsConnected) { // The effects are currently connected. Update them. recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); } else { if (finishedWork.mode & ConcurrentMode) { // The effects are currently disconnected. Since the tree is hidden, // don't connect them. This also applies to the initial render. if (enableCache || enableTransitionTracing) { // "Atomic" effects are ones that need to fire on every commit, // even during pre-rendering. An example is updating the reference // count on cache instances. recursivelyTraverseAtomicPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); } } else { // Legacy Mode: Fire the effects even if the tree is hidden. instance._visibility |= OffscreenPassiveEffectsConnected; recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); } } } else { // Tree is visible // Since we're already inside a reconnecting tree, it doesn't matter // whether the effects are currently connected. In either case, we'll // continue traversing the tree and firing all the effects. // // We do need to set the "connected" flag on the instance, though. instance._visibility |= OffscreenPassiveEffectsConnected; recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); } if (includeWorkInProgressEffects && flags & Passive) { // TODO: Pass `current` as argument to this function const current: Fiber | null = finishedWork.alternate; commitOffscreenPassiveMountEffects(current, finishedWork, instance); } break; } case CacheComponent: { recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); if (includeWorkInProgressEffects && flags & Passive) { // TODO: Pass `current` as argument to this function const current = finishedWork.alternate; commitCachePassiveMountEffect(current, finishedWork); } break; } case TracingMarkerComponent: { if (enableTransitionTracing) { recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); if (includeWorkInProgressEffects && flags & Passive) { commitTracingMarkerPassiveMountEffect(finishedWork); } break; } // Intentional fallthrough to next branch } default: { recursivelyTraverseReconnectPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, ); break; } } } function recursivelyTraverseAtomicPassiveEffects( finishedRoot: FiberRoot, parentFiber: Fiber, committedLanes: Lanes, committedTransitions: Array<Transition> | null, ) { // "Atomic" effects are ones that need to fire on every commit, even during // pre-rendering. We call this function when traversing a hidden tree whose // regular effects are currently disconnected. const prevDebugFiber = getCurrentDebugFiberInDEV(); // TODO: Add special flag for atomic effects if (parentFiber.subtreeFlags & PassiveMask) { let child = parentFiber.child; while (child !== null) { setCurrentDebugFiberInDEV(child); commitAtomicPassiveEffects( finishedRoot, child, committedLanes, committedTransitions, ); child = child.sibling; } } setCurrentDebugFiberInDEV(prevDebugFiber); } function commitAtomicPassiveEffects( finishedRoot: FiberRoot, finishedWork: Fiber, committedLanes: Lanes, committedTransitions: Array<Transition> | null, ) { // "Atomic" effects are ones that need to fire on every commit, even during // pre-rendering. We call this function when traversing a hidden tree whose // regular effects are currently disconnected. const flags = finishedWork.flags; switch (finishedWork.tag) { case OffscreenComponent: { recursivelyTraverseAtomicPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); if (flags & Passive) { // TODO: Pass `current` as argument to this function const current = finishedWork.alternate; const instance: OffscreenInstance = finishedWork.stateNode; commitOffscreenPassiveMountEffects(current, finishedWork, instance); } break; } case CacheComponent: { recursivelyTraverseAtomicPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); if (flags & Passive) { // TODO: Pass `current` as argument to this function const current = finishedWork.alternate; commitCachePassiveMountEffect(current, finishedWork); } break; } default: { recursivelyTraverseAtomicPassiveEffects( finishedRoot, finishedWork, committedLanes, committedTransitions, ); break; } } } export function commitPassiveUnmountEffects(finishedWork: Fiber): void { setCurrentDebugFiberInDEV(finishedWork); commitPassiveUnmountOnFiber(finishedWork); resetCurrentDebugFiberInDEV(); } // If we're inside a brand new tree, or a tree that was already visible, then we // should only suspend host components that have a ShouldSuspendCommit flag. // Components without it haven't changed since the last commit, so we can skip // over those. // // When we enter a tree that is being revealed (going from hidden -> visible), // we need to suspend _any_ component that _may_ suspend. Even if they're // already in the "current" tree. Because their visibility has changed, the // browser may not have prerendered them yet. So we check the MaySuspendCommit // flag instead. let suspenseyCommitFlag = ShouldSuspendCommit; export function accumulateSuspenseyCommit(finishedWork: Fiber): void { accumulateSuspenseyCommitOnFiber(finishedWork); } function recursivelyAccumulateSuspenseyCommit(parentFiber: Fiber): void { if (parentFiber.subtreeFlags & suspenseyCommitFlag) { let child = parentFiber.child; while (child !== null) { accumulateSuspenseyCommitOnFiber(child); child = child.sibling; } } } function accumulateSuspenseyCommitOnFiber(fiber: Fiber) { switch (fiber.tag) { case HostHoistable: { recursivelyAccumulateSuspenseyCommit(fiber); if (fiber.flags & suspenseyCommitFlag) { if (fiber.memoizedState !== null) { suspendResource( // This should always be set by visiting HostRoot first (currentHoistableRoot: any), fiber.memoizedState, fiber.memoizedProps, ); } else { const type = fiber.type; const props = fiber.memoizedProps; suspendInstance(type, props); } } break; } case HostComponent: { recursivelyAccumulateSuspenseyCommit(fiber); if (fiber.flags & suspenseyCommitFlag) { const type = fiber.type; const props = fiber.memoizedProps; suspendInstance(type, props); } break; } case HostRoot: case HostPortal: { if (enableFloat && supportsResources) { const previousHoistableRoot = currentHoistableRoot; const container: Container = fiber.stateNode.containerInfo; currentHoistableRoot = getHoistableRoot(container); recursivelyAccumulateSuspenseyCommit(fiber); currentHoistableRoot = previousHoistableRoot; } else { recursivelyAccumulateSuspenseyCommit(fiber); } break; } case OffscreenComponent: { const isHidden = (fiber.memoizedState: OffscreenState | null) !== null; if (isHidden) { // Don't suspend in hidden trees } else { const current = fiber.alternate; const wasHidden = current !== null && (current.memoizedState: OffscreenState | null) !== null; if (wasHidden) { // This tree is being revealed. Visit all newly visible suspensey // instances, even if they're in the current tree. const prevFlags = suspenseyCommitFlag; suspenseyCommitFlag = MaySuspendCommit; recursivelyAccumulateSuspenseyCommit(fiber); suspenseyCommitFlag = prevFlags; } else { recursivelyAccumulateSuspenseyCommit(fiber); } } break; } default: { recursivelyAccumulateSuspenseyCommit(fiber); } } } function detachAlternateSiblings(parentFiber: Fiber) { // A fiber was deleted from this parent fiber, but it's still part of the // previous (alternate) parent fiber's list of children. Because children // are a linked list, an earlier sibling that's still alive will be // connected to the deleted fiber via its `alternate`: // // live fiber --alternate--> previous live fiber --sibling--> deleted // fiber // // We can't disconnect `alternate` on nodes that haven't been deleted yet, // but we can disconnect the `sibling` and `child` pointers. const previousFiber = parentFiber.alternate; if (previousFiber !== null) { let detachedChild = previousFiber.child; if (detachedChild !== null) { previousFiber.child = null; do { // $FlowFixMe[incompatible-use] found when upgrading Flow const detachedSibling = detachedChild.sibling; // $FlowFixMe[incompatible-use] found when upgrading Flow detachedChild.sibling = null; detachedChild = detachedSibling; } while (detachedChild !== null); } } } function commitHookPassiveUnmountEffects( finishedWork: Fiber, nearestMountedAncestor: null | Fiber, hookFlags: HookFlags, ) { if (shouldProfile(finishedWork)) { startPassiveEffectTimer(); commitHookEffectListUnmount( hookFlags, finishedWork, nearestMountedAncestor, ); recordPassiveEffectDuration(finishedWork); } else { commitHookEffectListUnmount( hookFlags, finishedWork, nearestMountedAncestor, ); } } function recursivelyTraversePassiveUnmountEffects(parentFiber: Fiber): void { // Deletions effects can be scheduled on any fiber type. They need to happen // before the children effects have fired. const deletions = parentFiber.deletions; if ((parentFiber.flags & ChildDeletion) !== NoFlags) { if (deletions !== null) { for (let i = 0; i < deletions.length; i++) { const childToDelete = deletions[i]; // TODO: Convert this to use recursion nextEffect = childToDelete; commitPassiveUnmountEffectsInsideOfDeletedTree_begin( childToDelete, parentFiber, ); } } detachAlternateSiblings(parentFiber); } const prevDebugFiber = getCurrentDebugFiberInDEV(); // TODO: Split PassiveMask into separate masks for mount and unmount? if (parentFiber.subtreeFlags & PassiveMask) { let child = parentFiber.child; while (child !== null) { setCurrentDebugFiberInDEV(child); commitPassiveUnmountOnFiber(child); child = child.sibling; } } setCurrentDebugFiberInDEV(prevDebugFiber); } function commitPassiveUnmountOnFiber(finishedWork: Fiber): void { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { recursivelyTraversePassiveUnmountEffects(finishedWork); if (finishedWork.flags & Passive) { commitHookPassiveUnmountEffects( finishedWork, finishedWork.return, HookPassive | HookHasEffect, ); } break; } case OffscreenComponent: { const instance: OffscreenInstance = finishedWork.stateNode; const nextState: OffscreenState | null = finishedWork.memoizedState; const isHidden = nextState !== null; if ( isHidden && instance._visibility & OffscreenPassiveEffectsConnected && // For backwards compatibility, don't unmount when a tree suspends. In // the future we may change this to unmount after a delay. (finishedWork.return === null || finishedWork.return.tag !== SuspenseComponent) ) { // The effects are currently connected. Disconnect them. // TODO: Add option or heuristic to delay before disconnecting the // effects. Then if the tree reappears before the delay has elapsed, we // can skip toggling the effects entirely. instance._visibility &= ~OffscreenPassiveEffectsConnected; recursivelyTraverseDisconnectPassiveEffects(finishedWork); } else { recursivelyTraversePassiveUnmountEffects(finishedWork); } break; } default: { recursivelyTraversePassiveUnmountEffects(finishedWork); break; } } } function recursivelyTraverseDisconnectPassiveEffects(parentFiber: Fiber): void { // Deletions effects can be scheduled on any fiber type. They need to happen // before the children effects have fired. const deletions = parentFiber.deletions; if ((parentFiber.flags & ChildDeletion) !== NoFlags) { if (deletions !== null) { for (let i = 0; i < deletions.length; i++) { const childToDelete = deletions[i]; // TODO: Convert this to use recursion nextEffect = childToDelete; commitPassiveUnmountEffectsInsideOfDeletedTree_begin( childToDelete, parentFiber, ); } } detachAlternateSiblings(parentFiber); } const prevDebugFiber = getCurrentDebugFiberInDEV(); // TODO: Check PassiveStatic flag let child = parentFiber.child; while (child !== null) { setCurrentDebugFiberInDEV(child); disconnectPassiveEffect(child); child = child.sibling; } setCurrentDebugFiberInDEV(prevDebugFiber); } export function disconnectPassiveEffect(finishedWork: Fiber): void { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { // TODO: Check PassiveStatic flag commitHookPassiveUnmountEffects( finishedWork, finishedWork.return, HookPassive, ); // When disconnecting passive effects, we fire the effects in the same // order as during a deletiong: parent before child recursivelyTraverseDisconnectPassiveEffects(finishedWork); break; } case OffscreenComponent: { const instance: OffscreenInstance = finishedWork.stateNode; if (instance._visibility & OffscreenPassiveEffectsConnected) { instance._visibility &= ~OffscreenPassiveEffectsConnected; recursivelyTraverseDisconnectPassiveEffects(finishedWork); } else { // The effects are already disconnected. } break; } default: { recursivelyTraverseDisconnectPassiveEffects(finishedWork); break; } } } function commitPassiveUnmountEffectsInsideOfDeletedTree_begin( deletedSubtreeRoot: Fiber, nearestMountedAncestor: Fiber | null, ) { while (nextEffect !== null) { const fiber = nextEffect; // Deletion effects fire in parent -> child order // TODO: Check if fiber has a PassiveStatic flag setCurrentDebugFiberInDEV(fiber); commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); resetCurrentDebugFiberInDEV(); const child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. if (child !== null) { child.return = fiber; nextEffect = child; } else { commitPassiveUnmountEffectsInsideOfDeletedTree_complete( deletedSubtreeRoot, ); } } } function commitPassiveUnmountEffectsInsideOfDeletedTree_complete( deletedSubtreeRoot: Fiber, ) { while (nextEffect !== null) { const fiber = nextEffect; const sibling = fiber.sibling; const returnFiber = fiber.return; // Recursively traverse the entire deleted tree and clean up fiber fields. // This is more aggressive than ideal, and the long term goal is to only // have to detach the deleted tree at the root. detachFiberAfterEffects(fiber); if (fiber === deletedSubtreeRoot) { nextEffect = null; return; } if (sibling !== null) { sibling.return = returnFiber; nextEffect = sibling; return; } nextEffect = returnFiber; } } function commitPassiveUnmountInsideDeletedTreeOnFiber( current: Fiber, nearestMountedAncestor: Fiber | null, ): void { switch (current.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { commitHookPassiveUnmountEffects( current, nearestMountedAncestor, HookPassive, ); break; } // TODO: run passive unmount effects when unmounting a root. // Because passive unmount effects are not currently run, // the cache instance owned by the root will never be freed. // When effects are run, the cache should be freed here: // case HostRoot: { // if (enableCache) { // const cache = current.memoizedState.cache; // releaseCache(cache); // } // break; // } case LegacyHiddenComponent: case OffscreenComponent: { if (enableCache) { if ( current.memoizedState !== null && current.memoizedState.cachePool !== null ) { const cache: Cache = current.memoizedState.cachePool.pool; // Retain/release the cache used for pending (suspended) nodes. // Note that this is only reached in the non-suspended/visible case: // when the content is suspended/hidden, the retain/release occurs // via the parent Suspense component (see case above). if (cache != null) { retainCache(cache); } } } break; } case SuspenseComponent: { if (enableTransitionTracing) { // We need to mark this fiber's parents as deleted const offscreenFiber: Fiber = (current.child: any); const instance: OffscreenInstance = offscreenFiber.stateNode; const transitions = instance._transitions; if (transitions !== null) { const abortReason = { reason: 'suspense', name: current.memoizedProps.unstable_name || null, }; if ( current.memoizedState === null || current.memoizedState.dehydrated === null ) { abortParentMarkerTransitionsForDeletedFiber( offscreenFiber, abortReason, transitions, instance, true, ); if (nearestMountedAncestor !== null) { abortParentMarkerTransitionsForDeletedFiber( nearestMountedAncestor, abortReason, transitions, instance, false, ); } } } } break; } case CacheComponent: { if (enableCache) { const cache = current.memoizedState.cache; releaseCache(cache); } break; } case TracingMarkerComponent: { if (enableTransitionTracing) { // We need to mark this fiber's parents as deleted const instance: TracingMarkerInstance = current.stateNode; const transitions = instance.transitions; if (transitions !== null) { const abortReason = { reason: 'marker', name: current.memoizedProps.name, }; abortParentMarkerTransitionsForDeletedFiber( current, abortReason, transitions, null, true, ); if (nearestMountedAncestor !== null) { abortParentMarkerTransitionsForDeletedFiber( nearestMountedAncestor, abortReason, transitions, null, false, ); } } } break; } } } function invokeLayoutEffectMountInDEV(fiber: Fiber): void { if (__DEV__) { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListMount(HookLayout | HookHasEffect, fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } case ClassComponent: { const instance = fiber.stateNode; if (typeof instance.componentDidMount === 'function') { try { instance.componentDidMount(); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } } break; } } } } function invokePassiveEffectMountInDEV(fiber: Fiber): void { if (__DEV__) { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListMount(HookPassive | HookHasEffect, fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } } } } function invokeLayoutEffectUnmountInDEV(fiber: Fiber): void { if (__DEV__) { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListUnmount( HookLayout | HookHasEffect, fiber, fiber.return, ); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } case ClassComponent: { const instance = fiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(fiber, fiber.return, instance); } break; } } } } function invokePassiveEffectUnmountInDEV(fiber: Fiber): void { if (__DEV__) { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListUnmount( HookPassive | HookHasEffect, fiber, fiber.return, ); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } } } } } export { commitPlacement, commitAttachRef, invokeLayoutEffectMountInDEV, invokeLayoutEffectUnmountInDEV, invokePassiveEffectMountInDEV, invokePassiveEffectUnmountInDEV, };
31.920611
106
0.629701
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 strict-local */ import type {Position} from './astUtils'; import type { ReactSourceMetadata, IndexSourceMap, BasicSourceMap, MixedSourceMap, } from './SourceMapTypes'; import type {HookMap} from './generateHookMap'; import * as util from 'source-map-js/lib/util'; import {decodeHookMap} from './generateHookMap'; import {getHookNameForLocation} from './getHookNameForLocation'; type MetadataMap = Map<string, ?ReactSourceMetadata>; const HOOK_MAP_INDEX_IN_REACT_METADATA = 0; const REACT_METADATA_INDEX_IN_FB_METADATA = 1; const REACT_SOURCES_EXTENSION_KEY = 'x_react_sources'; const FB_SOURCES_EXTENSION_KEY = 'x_facebook_sources'; /** * Extracted from the logic in [email protected]'s SourceMapConsumer. * By default, source names are normalized using the same logic that the `[email protected]` package uses internally. * This is crucial for keeping the sources list in sync with a `SourceMapConsumer` instance. */ function normalizeSourcePath( sourceInput: string, map: {+sourceRoot?: ?string, ...}, ): string { const {sourceRoot} = map; let source = sourceInput; source = String(source); // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. source = util.normalize(source); // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. source = sourceRoot != null && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; return util.computeSourceURL(sourceRoot, source); } /** * Consumes the `x_react_sources` or `x_facebook_sources` metadata field from a * source map and exposes ways to query the React DevTools specific metadata * included in those fields. */ export class SourceMapMetadataConsumer { _sourceMap: MixedSourceMap; _decodedHookMapCache: Map<string, HookMap>; _metadataBySource: ?MetadataMap; constructor(sourcemap: MixedSourceMap) { this._sourceMap = sourcemap; this._decodedHookMapCache = new Map(); this._metadataBySource = null; } /** * Returns the Hook name assigned to a given location in the source code, * and a HookMap extracted from an extended source map. * See `getHookNameForLocation` for more details on implementation. * * When used with the `source-map` package, you'll first use * `SourceMapConsumer#originalPositionFor` to retrieve a source location, * then pass that location to `hookNameFor`. */ hookNameFor({ line, column, source, }: { ...Position, +source: ?string, }): ?string { if (source == null) { return null; } const hookMap = this._getHookMapForSource(source); if (hookMap == null) { return null; } return getHookNameForLocation({line, column}, hookMap); } hasHookMap(source: ?string): boolean { if (source == null) { return false; } return this._getHookMapForSource(source) != null; } /** * Prepares and caches a lookup table of metadata by source name. */ _getMetadataBySource(): MetadataMap { if (this._metadataBySource == null) { this._metadataBySource = this._getMetadataObjectsBySourceNames( this._sourceMap, ); } return this._metadataBySource; } /** * Collects source metadata from the given map using the current source name * normalization function. Handles both index maps (with sections) and plain * maps. * * NOTE: If any sources are repeated in the map (which shouldn't usually happen, * but is technically possible because of index maps) we only keep the * metadata from the last occurrence of any given source. */ _getMetadataObjectsBySourceNames(sourcemap: MixedSourceMap): MetadataMap { if (sourcemap.mappings === undefined) { const indexSourceMap: IndexSourceMap = sourcemap; const metadataMap = new Map<string, ?ReactSourceMetadata>(); indexSourceMap.sections.forEach(section => { const metadataMapForIndexMap = this._getMetadataObjectsBySourceNames( section.map, ); metadataMapForIndexMap.forEach((value, key) => { metadataMap.set(key, value); }); }); return metadataMap; } const metadataMap: MetadataMap = new Map(); const basicMap: BasicSourceMap = sourcemap; const updateMap = (metadata: ReactSourceMetadata, sourceIndex: number) => { let source = basicMap.sources[sourceIndex]; if (source != null) { source = normalizeSourcePath(source, basicMap); metadataMap.set(source, metadata); } }; if ( sourcemap.hasOwnProperty(REACT_SOURCES_EXTENSION_KEY) && sourcemap[REACT_SOURCES_EXTENSION_KEY] != null ) { const reactMetadataArray = sourcemap[REACT_SOURCES_EXTENSION_KEY]; reactMetadataArray.filter(Boolean).forEach(updateMap); } else if ( sourcemap.hasOwnProperty(FB_SOURCES_EXTENSION_KEY) && sourcemap[FB_SOURCES_EXTENSION_KEY] != null ) { const fbMetadataArray = sourcemap[FB_SOURCES_EXTENSION_KEY]; if (fbMetadataArray != null) { fbMetadataArray.forEach((fbMetadata, sourceIndex) => { // When extending source maps with React metadata using the // x_facebook_sources field, the position at index 1 on the // metadata tuple is reserved for React metadata const reactMetadata = fbMetadata != null ? fbMetadata[REACT_METADATA_INDEX_IN_FB_METADATA] : null; if (reactMetadata != null) { updateMap(reactMetadata, sourceIndex); } }); } } return metadataMap; } /** * Decodes the function name mappings for the given source if needed, and * retrieves a sorted, searchable array of mappings. */ _getHookMapForSource(source: string): ?HookMap { if (this._decodedHookMapCache.has(source)) { return this._decodedHookMapCache.get(source); } let hookMap = null; const metadataBySource = this._getMetadataBySource(); const normalized = normalizeSourcePath(source, this._sourceMap); const metadata = metadataBySource.get(normalized); if (metadata != null) { const encodedHookMap = metadata[HOOK_MAP_INDEX_IN_REACT_METADATA]; hookMap = encodedHookMap != null ? decodeHookMap(encodedHookMap) : null; } if (hookMap != null) { this._decodedHookMapCache.set(source, hookMap); } return hookMap; } }
32.533654
119
0.680671
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {Fragment, useContext, useMemo} from 'react'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import {ProfilerContext} from './ProfilerContext'; import SnapshotCommitList from './SnapshotCommitList'; import {maxBarWidth} from './constants'; import {StoreContext} from '../context'; import styles from './SnapshotSelector.css'; export type Props = {}; export default function SnapshotSelector(_: Props): React.Node { const { isCommitFilterEnabled, minCommitDuration, rootID, selectedCommitIndex, selectCommitIndex, } = useContext(ProfilerContext); const {profilerStore} = useContext(StoreContext); const {commitData} = profilerStore.getDataForRoot(((rootID: any): number)); const totalDurations: Array<number> = []; const commitTimes: Array<number> = []; commitData.forEach(commitDatum => { totalDurations.push( commitDatum.duration + (commitDatum.effectDuration || 0) + (commitDatum.passiveEffectDuration || 0), ); commitTimes.push(commitDatum.timestamp); }); const filteredCommitIndices = useMemo( () => commitData.reduce((reduced: $FlowFixMe, commitDatum, index) => { if ( !isCommitFilterEnabled || commitDatum.duration >= minCommitDuration ) { reduced.push(index); } return reduced; }, []), [commitData, isCommitFilterEnabled, minCommitDuration], ); const numFilteredCommits = filteredCommitIndices.length; // Map the (unfiltered) selected commit index to an index within the filtered data. const selectedFilteredCommitIndex = useMemo(() => { if (selectedCommitIndex !== null) { for (let i = 0; i < filteredCommitIndices.length; i++) { if (filteredCommitIndices[i] === selectedCommitIndex) { return i; } } } return null; }, [filteredCommitIndices, selectedCommitIndex]); // TODO (ProfilerContext) This should be managed by the context controller (reducer). // It doesn't currently know about the filtered commits though (since it doesn't suspend). // Maybe this component should pass filteredCommitIndices up? if (selectedFilteredCommitIndex === null) { if (numFilteredCommits > 0) { selectCommitIndex(0); } else { selectCommitIndex(null); } } else if (selectedFilteredCommitIndex >= numFilteredCommits) { selectCommitIndex(numFilteredCommits === 0 ? null : numFilteredCommits - 1); } let label = null; if (numFilteredCommits > 0) { // $FlowFixMe[missing-local-annot] const handleCommitInputChange = event => { const value = parseInt(event.currentTarget.value, 10); if (!isNaN(value)) { const filteredIndex = Math.min( Math.max(value - 1, 0), // Snashots are shown to the user as 1-based // but the indices within the profiler data array ar 0-based. numFilteredCommits - 1, ); selectCommitIndex(filteredCommitIndices[filteredIndex]); } }; // $FlowFixMe[missing-local-annot] const handleClick = event => { event.currentTarget.select(); }; // $FlowFixMe[missing-local-annot] const handleKeyDown = event => { switch (event.key) { case 'ArrowDown': viewPrevCommit(); event.stopPropagation(); break; case 'ArrowUp': viewNextCommit(); event.stopPropagation(); break; default: break; } }; const input = ( <input className={styles.Input} data-testname="SnapshotSelector-Input" type="text" inputMode="numeric" pattern="[0-9]*" value={ // $FlowFixMe[unsafe-addition] addition with possible null/undefined value selectedFilteredCommitIndex + 1 } size={`${numFilteredCommits}`.length} onChange={handleCommitInputChange} onClick={handleClick} onKeyDown={handleKeyDown} /> ); label = ( <Fragment> {input} / {numFilteredCommits} </Fragment> ); } const viewNextCommit = () => { let nextCommitIndex = ((selectedFilteredCommitIndex: any): number) + 1; if (nextCommitIndex === filteredCommitIndices.length) { nextCommitIndex = 0; } selectCommitIndex(filteredCommitIndices[nextCommitIndex]); }; const viewPrevCommit = () => { let nextCommitIndex = ((selectedFilteredCommitIndex: any): number) - 1; if (nextCommitIndex < 0) { nextCommitIndex = filteredCommitIndices.length - 1; } selectCommitIndex(filteredCommitIndices[nextCommitIndex]); }; // $FlowFixMe[missing-local-annot] const handleKeyDown = event => { switch (event.key) { case 'ArrowLeft': viewPrevCommit(); event.stopPropagation(); break; case 'ArrowRight': viewNextCommit(); event.stopPropagation(); break; default: break; } }; if (commitData.length === 0) { return null; } return ( <Fragment> <span className={styles.IndexLabel} data-testname="SnapshotSelector-Label"> {label} </span> <Button className={styles.Button} data-testname="SnapshotSelector-PreviousButton" disabled={numFilteredCommits === 0} onClick={viewPrevCommit} title="Select previous commit"> <ButtonIcon type="previous" /> </Button> <div className={styles.Commits} onKeyDown={handleKeyDown} style={{ flex: numFilteredCommits > 0 ? '1 1 auto' : '0 0 auto', maxWidth: numFilteredCommits > 0 ? numFilteredCommits * maxBarWidth : undefined, }} tabIndex={0}> {numFilteredCommits > 0 && ( <SnapshotCommitList commitData={commitData} commitTimes={commitTimes} filteredCommitIndices={filteredCommitIndices} selectedCommitIndex={selectedCommitIndex} selectedFilteredCommitIndex={selectedFilteredCommitIndex} selectCommitIndex={selectCommitIndex} totalDurations={totalDurations} /> )} {numFilteredCommits === 0 && ( <div className={styles.NoCommits}>No commits</div> )} </div> <Button className={styles.Button} data-testname="SnapshotSelector-NextButton" disabled={numFilteredCommits === 0} onClick={viewNextCommit} title="Select next commit"> <ButtonIcon type="next" /> </Button> </Fragment> ); }
28.14346
92
0.619027
ShonyDanza
/** * Copyright (c) Meta Platforms, Inc. 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 {forwardRef, useCallback, useContext, useMemo, useState} from 'react'; import AutoSizer from 'react-virtualized-auto-sizer'; import {FixedSizeList} from 'react-window'; import {ProfilerContext} from './ProfilerContext'; import NoCommitData from './NoCommitData'; import CommitFlamegraphListItem from './CommitFlamegraphListItem'; import HoveredFiberInfo from './HoveredFiberInfo'; import {scale} from './utils'; import {useHighlightNativeElement} from '../hooks'; import {StoreContext} from '../context'; import {SettingsContext} from '../Settings/SettingsContext'; import Tooltip from './Tooltip'; import styles from './CommitFlamegraph.css'; import type {TooltipFiberData} from './HoveredFiberInfo'; import type {ChartData, ChartNode} from './FlamegraphChartBuilder'; import type {CommitTree} from './types'; export type ItemData = { chartData: ChartData, onElementMouseEnter: (fiberData: TooltipFiberData) => void, onElementMouseLeave: () => void, scaleX: (value: number, fallbackValue: number) => number, selectedChartNode: ChartNode | null, selectedChartNodeIndex: number, selectFiber: (id: number | null, name: string | null) => void, width: number, }; export default function CommitFlamegraphAutoSizer(_: {}): React.Node { const {profilerStore} = useContext(StoreContext); const {rootID, selectedCommitIndex, selectFiber} = useContext(ProfilerContext); const {profilingCache} = profilerStore; const deselectCurrentFiber = useCallback( (event: $FlowFixMe) => { event.stopPropagation(); selectFiber(null, null); }, [selectFiber], ); let commitTree: CommitTree | null = null; let chartData: ChartData | null = null; if (selectedCommitIndex !== null) { commitTree = profilingCache.getCommitTree({ commitIndex: selectedCommitIndex, rootID: ((rootID: any): number), }); chartData = profilingCache.getFlamegraphChartData({ commitIndex: selectedCommitIndex, commitTree, rootID: ((rootID: any): number), }); } if (commitTree != null && chartData != null && chartData.depth > 0) { return ( <div className={styles.Container} onClick={deselectCurrentFiber}> <AutoSizer> {({height, width}) => ( // Force Flow types to avoid checking for `null` here because there's no static proof that // by the time this render prop function is called, the values of the `let` variables have not changed. <CommitFlamegraph chartData={((chartData: any): ChartData)} commitTree={((commitTree: any): CommitTree)} height={height} width={width} /> )} </AutoSizer> </div> ); } else { return <NoCommitData />; } } type Props = { chartData: ChartData, commitTree: CommitTree, height: number, width: number, }; function CommitFlamegraph({chartData, commitTree, height, width}: Props) { const [hoveredFiberData, setHoveredFiberData] = useState<TooltipFiberData | null>(null); const {lineHeight} = useContext(SettingsContext); const {selectFiber, selectedFiberID} = useContext(ProfilerContext); const {highlightNativeElement, clearHighlightNativeElement} = useHighlightNativeElement(); const selectedChartNodeIndex = useMemo<number>(() => { if (selectedFiberID === null) { return 0; } // The selected node might not be in the tree for this commit, // so it's important that we have a fallback plan. const depth = chartData.idToDepthMap.get(selectedFiberID); return depth !== undefined ? depth - 1 : 0; }, [chartData, selectedFiberID]); const selectedChartNode = useMemo(() => { if (selectedFiberID !== null) { return ( chartData.rows[selectedChartNodeIndex].find( chartNode => chartNode.id === selectedFiberID, ) || null ); } return null; }, [chartData, selectedFiberID, selectedChartNodeIndex]); const handleElementMouseEnter = useCallback( ({id, name}: $FlowFixMe) => { highlightNativeElement(id); // Highlight last hovered element. setHoveredFiberData({id, name}); // Set hovered fiber data for tooltip }, [highlightNativeElement], ); const handleElementMouseLeave = useCallback(() => { clearHighlightNativeElement(); // clear highlighting of element on mouse leave setHoveredFiberData(null); // clear hovered fiber data for tooltip }, [clearHighlightNativeElement]); const itemData = useMemo<ItemData>( () => ({ chartData, onElementMouseEnter: handleElementMouseEnter, onElementMouseLeave: handleElementMouseLeave, scaleX: scale( 0, selectedChartNode !== null ? selectedChartNode.treeBaseDuration : chartData.baseDuration, 0, width, ), selectedChartNode, selectedChartNodeIndex, selectFiber, width, }), [ chartData, handleElementMouseEnter, handleElementMouseLeave, selectedChartNode, selectedChartNodeIndex, selectFiber, width, ], ); // Tooltip used to show summary of fiber info on hover const tooltipLabel = useMemo( () => hoveredFiberData !== null ? ( <HoveredFiberInfo fiberData={hoveredFiberData} /> ) : null, [hoveredFiberData], ); return ( <Tooltip label={tooltipLabel}> <FixedSizeList height={height} innerElementType={InnerElementType} itemCount={chartData.depth} itemData={itemData} itemSize={lineHeight} width={width}> {CommitFlamegraphListItem} </FixedSizeList> </Tooltip> ); } const InnerElementType = forwardRef(({children, ...rest}, ref) => ( <svg ref={ref} {...rest}> <defs> <pattern id="didNotRenderPattern" patternUnits="userSpaceOnUse" width="4" height="4"> <path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2" className={styles.PatternPath} /> </pattern> </defs> {children} </svg> ));
29.042654
115
0.654465
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 */ /* eslint-disable react-internal/prod-error-codes */ // We expect that our Rollup, Jest, and Flow configurations // always shim this module with the corresponding host config // (either provided by a renderer, or a generic shim for npm). // // We should never resolve to this file, but it exists to make // sure that if we *do* accidentally break the configuration, // the failure isn't silent. throw new Error('This module must be shimmed by a specific renderer.');
31.095238
71
0.728083
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-client/src/ReactFlightClientConfigNode'; export * from 'react-server-dom-esm/src/ReactFlightClientConfigBundlerESM'; export * from 'react-server-dom-esm/src/ReactFlightClientConfigTargetESMServer'; export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export const usedWithSSR = true;
34.4
80
0.771698
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} from './ReactInternalTypes'; import type {CapturedValue} from './ReactCapturedValue'; // This module is forked in different environments. // By default, return `true` to log errors to the console. // Forks can return `false` if this isn't desirable. export function showErrorDialog( boundary: Fiber, errorInfo: CapturedValue<mixed>, ): boolean { return true; }
24.826087
66
0.72344
thieves-tools
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { Thenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; import type {ImportMetadata} from './shared/ReactFlightImportMetadata'; import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig'; import { ID, CHUNKS, NAME, isAsyncImport, } from './shared/ReactFlightImportMetadata'; import {prepareDestinationWithChunks} from 'react-client/src/ReactFlightClientConfig'; export type SSRModuleMap = { [clientId: string]: { [clientExportName: string]: ClientReference<any>, }, }; export type ServerManifest = void; export type ServerReferenceId = string; export opaque type ClientReferenceMetadata = ImportMetadata; // eslint-disable-next-line no-unused-vars export opaque type ClientReference<T> = { specifier: string, name: string, async?: boolean, }; // The reason this function needs to defined here in this file instead of just // being exported directly from the WebpackDestination... file is because the // ClientReferenceMetadata is opaque and we can't unwrap it there. // This should get inlined and we could also just implement an unwrapping function // though that risks it getting used in places it shouldn't be. This is unfortunate // but currently it seems to be the best option we have. export function prepareDestinationForModule( moduleLoading: ModuleLoading, nonce: ?string, metadata: ClientReferenceMetadata, ) { prepareDestinationWithChunks(moduleLoading, metadata[CHUNKS], nonce); } export function resolveClientReference<T>( bundlerConfig: SSRModuleMap, metadata: ClientReferenceMetadata, ): ClientReference<T> { const moduleExports = bundlerConfig[metadata[ID]]; let resolvedModuleData = moduleExports[metadata[NAME]]; let name; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // If we don't have this specific name, we might have the full module. resolvedModuleData = moduleExports['*']; if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + metadata[ID] + '" in the React SSR Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } name = metadata[NAME]; } return { specifier: resolvedModuleData.specifier, name: name, async: isAsyncImport(metadata), }; } export function resolveServerReference<T>( bundlerConfig: ServerManifest, id: ServerReferenceId, ): ClientReference<T> { const idx = id.lastIndexOf('#'); const specifier = id.slice(0, idx); const name = id.slice(idx + 1); return {specifier, name}; } const asyncModuleCache: Map<string, Thenable<any>> = new Map(); export function preloadModule<T>( metadata: ClientReference<T>, ): null | Thenable<any> { const existingPromise = asyncModuleCache.get(metadata.specifier); if (existingPromise) { if (existingPromise.status === 'fulfilled') { return null; } return existingPromise; } else { // $FlowFixMe[unsupported-syntax] let modulePromise: Promise<T> = import(metadata.specifier); if (metadata.async) { // If the module is async, it must have been a CJS module. // CJS modules are accessed through the default export in // Node.js so we have to get the default export to get the // full module exports. modulePromise = modulePromise.then(function (value) { return (value: any).default; }); } modulePromise.then( value => { const fulfilledThenable: FulfilledThenable<mixed> = (modulePromise: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; }, reason => { const rejectedThenable: RejectedThenable<mixed> = (modulePromise: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = reason; }, ); asyncModuleCache.set(metadata.specifier, modulePromise); return modulePromise; } } export function requireModule<T>(metadata: ClientReference<T>): T { let moduleExports; // We assume that preloadModule has been called before, which // should have added something to the module cache. const promise: any = asyncModuleCache.get(metadata.specifier); if (promise.status === 'fulfilled') { moduleExports = promise.value; } else { throw promise.reason; } if (metadata.name === '*') { // This is a placeholder value that represents that the caller imported this // as a CommonJS module as is. return moduleExports; } if (metadata.name === '') { // This is a placeholder value that represents that the caller accessed the // default property of this if it was an ESM interop module. return moduleExports.default; } return moduleExports[metadata.name]; }
29.809816
86
0.700856
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; export * from './src/JestReact';
20.909091
66
0.695833
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. */ import * as parseSourceAndMetadataModule from './parseSourceAndMetadata'; export const parseSourceAndMetadata = parseSourceAndMetadataModule.parseSourceAndMetadata; export const purgeCachedMetadata = parseSourceAndMetadataModule.purgeCachedMetadata;
31
73
0.800895
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 {View} from './View'; import {COLORS} from '../content-views/constants'; /** * View that fills its visible area with a CSS color. */ export class BackgroundColorView extends View { draw(context: CanvasRenderingContext2D) { const {visibleArea} = this; context.fillStyle = COLORS.BACKGROUND; context.fillRect( visibleArea.origin.x, visibleArea.origin.y, visibleArea.size.width, visibleArea.size.height, ); } }
22.034483
66
0.682159
Effective-Python-Penetration-Testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {copy} from 'clipboard-js'; import * as React from 'react'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import KeyValue from './KeyValue'; import {alphaSortEntries, serializeDataForCopy} from '../utils'; import Store from '../../store'; import styles from './InspectedElementSharedStyles.css'; import { ElementTypeClass, ElementTypeFunction, } from 'react-devtools-shared/src/frontend/types'; import type {InspectedElement} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type {Element} from 'react-devtools-shared/src/frontend/types'; type Props = { bridge: FrontendBridge, element: Element, inspectedElement: InspectedElement, store: Store, }; export default function InspectedElementContextTree({ bridge, element, inspectedElement, store, }: Props): React.Node { const {hasLegacyContext, context, type} = inspectedElement; const isReadOnly = type !== ElementTypeClass && type !== ElementTypeFunction; const entries = context != null ? Object.entries(context) : null; if (entries !== null) { entries.sort(alphaSortEntries); } const isEmpty = entries === null || entries.length === 0; const handleCopy = () => copy(serializeDataForCopy(((context: any): Object))); // We add an object with a "value" key as a wrapper around Context data // so that we can use the shared <KeyValue> component to display it. // This wrapper object can't be renamed. // $FlowFixMe[missing-local-annot] const canRenamePathsAtDepth = depth => depth > 1; if (isEmpty) { return null; } else { return ( <div className={styles.InspectedElementTree}> <div className={styles.HeaderRow}> <div className={styles.Header}> {hasLegacyContext ? 'legacy context' : 'context'} </div> {!isEmpty && ( <Button onClick={handleCopy} title="Copy to clipboard"> <ButtonIcon type="copy" /> </Button> )} </div> {isEmpty && <div className={styles.Empty}>None</div>} {!isEmpty && (entries: any).map(([name, value]) => ( <KeyValue key={name} alphaSort={true} bridge={bridge} canDeletePaths={!isReadOnly} canEditValues={!isReadOnly} canRenamePaths={!isReadOnly} canRenamePathsAtDepth={canRenamePathsAtDepth} depth={1} element={element} hidden={false} inspectedElement={inspectedElement} name={name} path={[name]} pathRoot="context" store={store} type="context" value={value} /> ))} </div> ); } }
29.257426
80
0.616694
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 { FlamechartStackFrame, InternalModuleSourceToRanges, } from '../../types'; import { CHROME_WEBSTORE_EXTENSION_ID, INTERNAL_EXTENSION_ID, LOCAL_EXTENSION_ID, } from 'react-devtools-shared/src/constants'; export function isInternalModule( internalModuleSourceToRanges: InternalModuleSourceToRanges, flamechartStackFrame: FlamechartStackFrame, ): boolean { const {locationColumn, locationLine, scriptUrl} = flamechartStackFrame; if (scriptUrl == null || locationColumn == null || locationLine == null) { // This could indicate a browser-internal API like performance.mark(). return false; } // Internal modules are only registered if DevTools was running when the profile was captured, // but DevTools should also hide its own frames to avoid over-emphasizing them. if ( // Handle webpack-internal:// sources scriptUrl.includes('/react-devtools') || scriptUrl.includes('/react_devtools') || // Filter out known extension IDs scriptUrl.includes(CHROME_WEBSTORE_EXTENSION_ID) || scriptUrl.includes(INTERNAL_EXTENSION_ID) || scriptUrl.includes(LOCAL_EXTENSION_ID) // Unfortunately this won't get everything, like relatively loaded chunks or Web Worker files. ) { return true; } // Filter out React internal packages. const ranges = internalModuleSourceToRanges.get(scriptUrl); if (ranges != null) { for (let i = 0; i < ranges.length; i++) { const [startStackFrame, stopStackFrame] = ranges[i]; const isAfterStart = locationLine > startStackFrame.lineNumber || (locationLine === startStackFrame.lineNumber && locationColumn >= startStackFrame.columnNumber); const isBeforeStop = locationLine < stopStackFrame.lineNumber || (locationLine === stopStackFrame.lineNumber && locationColumn <= stopStackFrame.columnNumber); if (isAfterStart && isBeforeStop) { return true; } } } return false; }
30.285714
98
0.70032
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 './ComponentMeasuresView'; export * from './FlamechartView'; export * from './NativeEventsView'; export * from './NetworkMeasuresView'; export * from './ReactMeasuresView'; export * from './SchedulingEventsView'; export * from './SnapshotsView'; export * from './SuspenseEventsView'; export * from './ThrownErrorsView'; export * from './TimeAxisMarkersView'; export * from './UserTimingMarksView';
28.380952
66
0.717532
cybersecurity-penetration-testing
'use strict'; module.exports = require('./static.node');
13.75
42
0.672414
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListItem = ListItem; exports.List = List; var React = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ListItem({ item, removeItem, toggleItem }) { const handleDelete = (0, React.useCallback)(() => { removeItem(item); }, [item, removeItem]); const handleToggle = (0, React.useCallback)(() => { toggleItem(item); }, [item, toggleItem]); return /*#__PURE__*/React.createElement("li", { __source: { fileName: _jsxFileName, lineNumber: 23, columnNumber: 5 } }, /*#__PURE__*/React.createElement("button", { onClick: handleDelete, __source: { fileName: _jsxFileName, lineNumber: 24, columnNumber: 7 } }, "Delete"), /*#__PURE__*/React.createElement("label", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, /*#__PURE__*/React.createElement("input", { checked: item.isComplete, onChange: handleToggle, type: "checkbox", __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 9 } }), ' ', item.text)); } function List(props) { const [newItemText, setNewItemText] = (0, React.useState)(''); const [items, setItems] = (0, React.useState)([{ id: 1, isComplete: true, text: 'First' }, { id: 2, isComplete: true, text: 'Second' }, { id: 3, isComplete: false, text: 'Third' }]); const [uid, setUID] = (0, React.useState)(4); const handleClick = (0, React.useCallback)(() => { if (newItemText !== '') { setItems([...items, { id: uid, isComplete: false, text: newItemText }]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = (0, React.useCallback)(event => { if (event.key === 'Enter') { handleClick(); } }, [handleClick]); const handleChange = (0, React.useCallback)(event => { setNewItemText(event.currentTarget.value); }, [setNewItemText]); const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]); const toggleItem = (0, React.useCallback)(itemToToggle => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); setItems(items.slice(0, index).concat({ ...itemToToggle, isComplete: !itemToToggle.isComplete }).concat(items.slice(index + 1))); }, [items]); return /*#__PURE__*/React.createElement(React.Fragment, { __source: { fileName: _jsxFileName, lineNumber: 102, columnNumber: 5 } }, /*#__PURE__*/React.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 103, columnNumber: 7 } }, "List"), /*#__PURE__*/React.createElement("input", { type: "text", placeholder: "New list item...", value: newItemText, onChange: handleChange, onKeyPress: handleKeyPress, __source: { fileName: _jsxFileName, lineNumber: 104, columnNumber: 7 } }), /*#__PURE__*/React.createElement("button", { disabled: newItemText === '', onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 111, columnNumber: 7 } }, /*#__PURE__*/React.createElement("span", { role: "img", "aria-label": "Add item", __source: { fileName: _jsxFileName, lineNumber: 112, columnNumber: 9 } }, "Add")), /*#__PURE__*/React.createElement("ul", { __source: { fileName: _jsxFileName, lineNumber: 116, columnNumber: 7 } }, items.map(item => /*#__PURE__*/React.createElement(ListItem, { key: item.id, item: item, removeItem: removeItem, toggleItem: toggleItem, __source: { fileName: _jsxFileName, lineNumber: 118, columnNumber: 11 } })))); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlRvRG9MaXN0LmpzIl0sIm5hbWVzIjpbIkxpc3RJdGVtIiwiaXRlbSIsInJlbW92ZUl0ZW0iLCJ0b2dnbGVJdGVtIiwiaGFuZGxlRGVsZXRlIiwiaGFuZGxlVG9nZ2xlIiwiaXNDb21wbGV0ZSIsInRleHQiLCJMaXN0IiwicHJvcHMiLCJuZXdJdGVtVGV4dCIsInNldE5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJzZXRJdGVtcyIsImlkIiwidWlkIiwic2V0VUlEIiwiaGFuZGxlQ2xpY2siLCJoYW5kbGVLZXlQcmVzcyIsImV2ZW50Iiwia2V5IiwiaGFuZGxlQ2hhbmdlIiwiY3VycmVudFRhcmdldCIsInZhbHVlIiwiaXRlbVRvUmVtb3ZlIiwiZmlsdGVyIiwiaXRlbVRvVG9nZ2xlIiwiaW5kZXgiLCJmaW5kSW5kZXgiLCJzbGljZSIsImNvbmNhdCIsIm1hcCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFHTyxTQUFTQSxRQUFULENBQWtCO0FBQUNDLEVBQUFBLElBQUQ7QUFBT0MsRUFBQUEsVUFBUDtBQUFtQkMsRUFBQUE7QUFBbkIsQ0FBbEIsRUFBa0Q7QUFDdkQsUUFBTUMsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0QsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPQyxVQUFQLENBRmtCLENBQXJCO0FBSUEsUUFBTUcsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0YsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPRSxVQUFQLENBRmtCLENBQXJCO0FBSUEsc0JBQ0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0U7QUFBUSxJQUFBLE9BQU8sRUFBRUMsWUFBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQ0UsSUFBQSxPQUFPLEVBQUVILElBQUksQ0FBQ0ssVUFEaEI7QUFFRSxJQUFBLFFBQVEsRUFBRUQsWUFGWjtBQUdFLElBQUEsSUFBSSxFQUFDLFVBSFA7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFERixFQUtLLEdBTEwsRUFNR0osSUFBSSxDQUFDTSxJQU5SLENBRkYsQ0FERjtBQWFEOztBQUVNLFNBQVNDLElBQVQsQ0FBY0MsS0FBZCxFQUFxQjtBQUMxQixRQUFNLENBQUNDLFdBQUQsRUFBY0MsY0FBZCxJQUFnQyxvQkFBUyxFQUFULENBQXRDO0FBQ0EsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0Isb0JBQVMsQ0FDakM7QUFBQ0MsSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FEaUMsRUFFakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FGaUMsRUFHakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLEtBQXBCO0FBQTJCQyxJQUFBQSxJQUFJLEVBQUU7QUFBakMsR0FIaUMsQ0FBVCxDQUExQjtBQUtBLFFBQU0sQ0FBQ1EsR0FBRCxFQUFNQyxNQUFOLElBQWdCLG9CQUFTLENBQVQsQ0FBdEI7QUFFQSxRQUFNQyxXQUFXLEdBQUcsdUJBQVksTUFBTTtBQUNwQyxRQUFJUCxXQUFXLEtBQUssRUFBcEIsRUFBd0I7QUFDdEJHLE1BQUFBLFFBQVEsQ0FBQyxDQUNQLEdBQUdELEtBREksRUFFUDtBQUNFRSxRQUFBQSxFQUFFLEVBQUVDLEdBRE47QUFFRVQsUUFBQUEsVUFBVSxFQUFFLEtBRmQ7QUFHRUMsUUFBQUEsSUFBSSxFQUFFRztBQUhSLE9BRk8sQ0FBRCxDQUFSO0FBUUFNLE1BQUFBLE1BQU0sQ0FBQ0QsR0FBRyxHQUFHLENBQVAsQ0FBTjtBQUNBSixNQUFBQSxjQUFjLENBQUMsRUFBRCxDQUFkO0FBQ0Q7QUFDRixHQWJtQixFQWFqQixDQUFDRCxXQUFELEVBQWNFLEtBQWQsRUFBcUJHLEdBQXJCLENBYmlCLENBQXBCO0FBZUEsUUFBTUcsY0FBYyxHQUFHLHVCQUNyQkMsS0FBSyxJQUFJO0FBQ1AsUUFBSUEsS0FBSyxDQUFDQyxHQUFOLEtBQWMsT0FBbEIsRUFBMkI7QUFDekJILE1BQUFBLFdBQVc7QUFDWjtBQUNGLEdBTG9CLEVBTXJCLENBQUNBLFdBQUQsQ0FOcUIsQ0FBdkI7QUFTQSxRQUFNSSxZQUFZLEdBQUcsdUJBQ25CRixLQUFLLElBQUk7QUFDUFIsSUFBQUEsY0FBYyxDQUFDUSxLQUFLLENBQUNHLGFBQU4sQ0FBb0JDLEtBQXJCLENBQWQ7QUFDRCxHQUhrQixFQUluQixDQUFDWixjQUFELENBSm1CLENBQXJCO0FBT0EsUUFBTVQsVUFBVSxHQUFHLHVCQUNqQnNCLFlBQVksSUFBSVgsUUFBUSxDQUFDRCxLQUFLLENBQUNhLE1BQU4sQ0FBYXhCLElBQUksSUFBSUEsSUFBSSxLQUFLdUIsWUFBOUIsQ0FBRCxDQURQLEVBRWpCLENBQUNaLEtBQUQsQ0FGaUIsQ0FBbkI7QUFLQSxRQUFNVCxVQUFVLEdBQUcsdUJBQ2pCdUIsWUFBWSxJQUFJO0FBQ2Q7QUFDQTtBQUNBLFVBQU1DLEtBQUssR0FBR2YsS0FBSyxDQUFDZ0IsU0FBTixDQUFnQjNCLElBQUksSUFBSUEsSUFBSSxDQUFDYSxFQUFMLEtBQVlZLFlBQVksQ0FBQ1osRUFBakQsQ0FBZDtBQUVBRCxJQUFBQSxRQUFRLENBQ05ELEtBQUssQ0FDRmlCLEtBREgsQ0FDUyxDQURULEVBQ1lGLEtBRFosRUFFR0csTUFGSCxDQUVVLEVBQ04sR0FBR0osWUFERztBQUVOcEIsTUFBQUEsVUFBVSxFQUFFLENBQUNvQixZQUFZLENBQUNwQjtBQUZwQixLQUZWLEVBTUd3QixNQU5ILENBTVVsQixLQUFLLENBQUNpQixLQUFOLENBQVlGLEtBQUssR0FBRyxDQUFwQixDQU5WLENBRE0sQ0FBUjtBQVNELEdBZmdCLEVBZ0JqQixDQUFDZixLQUFELENBaEJpQixDQUFuQjtBQW1CQSxzQkFDRSxvQkFBQyxjQUFEO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLFlBREYsZUFFRTtBQUNFLElBQUEsSUFBSSxFQUFDLE1BRFA7QUFFRSxJQUFBLFdBQVcsRUFBQyxrQkFGZDtBQUdFLElBQUEsS0FBSyxFQUFFRixXQUhUO0FBSUUsSUFBQSxRQUFRLEVBQUVXLFlBSlo7QUFLRSxJQUFBLFVBQVUsRUFBRUgsY0FMZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQUZGLGVBU0U7QUFBUSxJQUFBLFFBQVEsRUFBRVIsV0FBVyxLQUFLLEVBQWxDO0FBQXNDLElBQUEsT0FBTyxFQUFFTyxXQUEvQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDRTtBQUFNLElBQUEsSUFBSSxFQUFDLEtBQVg7QUFBaUIsa0JBQVcsVUFBNUI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsV0FERixDQVRGLGVBY0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDR0wsS0FBSyxDQUFDbUIsR0FBTixDQUFVOUIsSUFBSSxpQkFDYixvQkFBQyxRQUFEO0FBQ0UsSUFBQSxHQUFHLEVBQUVBLElBQUksQ0FBQ2EsRUFEWjtBQUVFLElBQUEsSUFBSSxFQUFFYixJQUZSO0FBR0UsSUFBQSxVQUFVLEVBQUVDLFVBSGQ7QUFJRSxJQUFBLFVBQVUsRUFBRUMsVUFKZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQURELENBREgsQ0FkRixDQURGO0FBMkJEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0JztcbmltcG9ydCB7RnJhZ21lbnQsIHVzZUNhbGxiYWNrLCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gTGlzdEl0ZW0oe2l0ZW0sIHJlbW92ZUl0ZW0sIHRvZ2dsZUl0ZW19KSB7XG4gIGNvbnN0IGhhbmRsZURlbGV0ZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICByZW1vdmVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgcmVtb3ZlSXRlbV0pO1xuXG4gIGNvbnN0IGhhbmRsZVRvZ2dsZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICB0b2dnbGVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgdG9nZ2xlSXRlbV0pO1xuXG4gIHJldHVybiAoXG4gICAgPGxpPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXtoYW5kbGVEZWxldGV9PkRlbGV0ZTwvYnV0dG9uPlxuICAgICAgPGxhYmVsPlxuICAgICAgICA8aW5wdXRcbiAgICAgICAgICBjaGVja2VkPXtpdGVtLmlzQ29tcGxldGV9XG4gICAgICAgICAgb25DaGFuZ2U9e2hhbmRsZVRvZ2dsZX1cbiAgICAgICAgICB0eXBlPVwiY2hlY2tib3hcIlxuICAgICAgICAvPnsnICd9XG4gICAgICAgIHtpdGVtLnRleHR9XG4gICAgICA8L2xhYmVsPlxuICAgIDwvbGk+XG4gICk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBMaXN0KHByb3BzKSB7XG4gIGNvbnN0IFtuZXdJdGVtVGV4dCwgc2V0TmV3SXRlbVRleHRdID0gdXNlU3RhdGUoJycpO1xuICBjb25zdCBbaXRlbXMsIHNldEl0ZW1zXSA9IHVzZVN0YXRlKFtcbiAgICB7aWQ6IDEsIGlzQ29tcGxldGU6IHRydWUsIHRleHQ6ICdGaXJzdCd9LFxuICAgIHtpZDogMiwgaXNDb21wbGV0ZTogdHJ1ZSwgdGV4dDogJ1NlY29uZCd9LFxuICAgIHtpZDogMywgaXNDb21wbGV0ZTogZmFsc2UsIHRleHQ6ICdUaGlyZCd9LFxuICBdKTtcbiAgY29uc3QgW3VpZCwgc2V0VUlEXSA9IHVzZVN0YXRlKDQpO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gdXNlQ2FsbGJhY2soKCkgPT4ge1xuICAgIGlmIChuZXdJdGVtVGV4dCAhPT0gJycpIHtcbiAgICAgIHNldEl0ZW1zKFtcbiAgICAgICAgLi4uaXRlbXMsXG4gICAgICAgIHtcbiAgICAgICAgICBpZDogdWlkLFxuICAgICAgICAgIGlzQ29tcGxldGU6IGZhbHNlLFxuICAgICAgICAgIHRleHQ6IG5ld0l0ZW1UZXh0LFxuICAgICAgICB9LFxuICAgICAgXSk7XG4gICAgICBzZXRVSUQodWlkICsgMSk7XG4gICAgICBzZXROZXdJdGVtVGV4dCgnJyk7XG4gICAgfVxuICB9LCBbbmV3SXRlbVRleHQsIGl0ZW1zLCB1aWRdKTtcblxuICBjb25zdCBoYW5kbGVLZXlQcmVzcyA9IHVzZUNhbGxiYWNrKFxuICAgIGV2ZW50ID0+IHtcbiAgICAgIGlmIChldmVudC5rZXkgPT09ICdFbnRlcicpIHtcbiAgICAgICAgaGFuZGxlQ2xpY2soKTtcbiAgICAgIH1cbiAgICB9LFxuICAgIFtoYW5kbGVDbGlja10sXG4gICk7XG5cbiAgY29uc3QgaGFuZGxlQ2hhbmdlID0gdXNlQ2FsbGJhY2soXG4gICAgZXZlbnQgPT4ge1xuICAgICAgc2V0TmV3SXRlbVRleHQoZXZlbnQuY3VycmVudFRhcmdldC52YWx1ZSk7XG4gICAgfSxcbiAgICBbc2V0TmV3SXRlbVRleHRdLFxuICApO1xuXG4gIGNvbnN0IHJlbW92ZUl0ZW0gPSB1c2VDYWxsYmFjayhcbiAgICBpdGVtVG9SZW1vdmUgPT4gc2V0SXRlbXMoaXRlbXMuZmlsdGVyKGl0ZW0gPT4gaXRlbSAhPT0gaXRlbVRvUmVtb3ZlKSksXG4gICAgW2l0ZW1zXSxcbiAgKTtcblxuICBjb25zdCB0b2dnbGVJdGVtID0gdXNlQ2FsbGJhY2soXG4gICAgaXRlbVRvVG9nZ2xlID0+IHtcbiAgICAgIC8vIERvbnQgdXNlIGluZGV4T2YoKVxuICAgICAgLy8gYmVjYXVzZSBlZGl0aW5nIHByb3BzIGluIERldlRvb2xzIGNyZWF0ZXMgYSBuZXcgT2JqZWN0LlxuICAgICAgY29uc3QgaW5kZXggPSBpdGVtcy5maW5kSW5kZXgoaXRlbSA9PiBpdGVtLmlkID09PSBpdGVtVG9Ub2dnbGUuaWQpO1xuXG4gICAgICBzZXRJdGVtcyhcbiAgICAgICAgaXRlbXNcbiAgICAgICAgICAuc2xpY2UoMCwgaW5kZXgpXG4gICAgICAgICAgLmNvbmNhdCh7XG4gICAgICAgICAgICAuLi5pdGVtVG9Ub2dnbGUsXG4gICAgICAgICAgICBpc0NvbXBsZXRlOiAhaXRlbVRvVG9nZ2xlLmlzQ29tcGxldGUsXG4gICAgICAgICAgfSlcbiAgICAgICAgICAuY29uY2F0KGl0ZW1zLnNsaWNlKGluZGV4ICsgMSkpLFxuICAgICAgKTtcbiAgICB9LFxuICAgIFtpdGVtc10sXG4gICk7XG5cbiAgcmV0dXJuIChcbiAgICA8RnJhZ21lbnQ+XG4gICAgICA8aDE+TGlzdDwvaDE+XG4gICAgICA8aW5wdXRcbiAgICAgICAgdHlwZT1cInRleHRcIlxuICAgICAgICBwbGFjZWhvbGRlcj1cIk5ldyBsaXN0IGl0ZW0uLi5cIlxuICAgICAgICB2YWx1ZT17bmV3SXRlbVRleHR9XG4gICAgICAgIG9uQ2hhbmdlPXtoYW5kbGVDaGFuZ2V9XG4gICAgICAgIG9uS2V5UHJlc3M9e2hhbmRsZUtleVByZXNzfVxuICAgICAgLz5cbiAgICAgIDxidXR0b24gZGlzYWJsZWQ9e25ld0l0ZW1UZXh0ID09PSAnJ30gb25DbGljaz17aGFuZGxlQ2xpY2t9PlxuICAgICAgICA8c3BhbiByb2xlPVwiaW1nXCIgYXJpYS1sYWJlbD1cIkFkZCBpdGVtXCI+XG4gICAgICAgICAgQWRkXG4gICAgICAgIDwvc3Bhbj5cbiAgICAgIDwvYnV0dG9uPlxuICAgICAgPHVsPlxuICAgICAgICB7aXRlbXMubWFwKGl0ZW0gPT4gKFxuICAgICAgICAgIDxMaXN0SXRlbVxuICAgICAgICAgICAga2V5PXtpdGVtLmlkfVxuICAgICAgICAgICAgaXRlbT17aXRlbX1cbiAgICAgICAgICAgIHJlbW92ZUl0ZW09e3JlbW92ZUl0ZW19XG4gICAgICAgICAgICB0b2dnbGVJdGVtPXt0b2dnbGVJdGVtfVxuICAgICAgICAgIC8+XG4gICAgICAgICkpfVxuICAgICAgPC91bD5cbiAgICA8L0ZyYWdtZW50PlxuICApO1xufVxuIl19fV19
85.49375
8,872
0.855398
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); const isDarkMode = useIsDarkMode(); const { foo } = useFoo(); (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 27, columnNumber: 7 } }, "Foo: ", foo), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const [isDarkMode] = (0, _react.useState)(false); (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return isDarkMode; } function useFoo() { (0, _react.useDebugValue)('foo'); return { foo: true }; } //# sourceMappingURL=ComponentWithCustomHook.js.map?foo=bar&param=some_value
36.617647
743
0.636293