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 | /**
* Copyright (c) Meta Platforms, Inc. 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 {REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED} from 'shared/ReactSymbols';
import {isPrimaryRenderer} from './ReactFizzConfig';
let rendererSigil;
if (__DEV__) {
// Use this to detect multiple renderers using the same context
rendererSigil = {};
}
// Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.
type ContextNode<T> = {
parent: null | ContextNode<any>,
depth: number, // Short hand to compute the depth of the tree at this node.
context: ReactContext<T>,
parentValue: T,
value: T,
};
// The structure of a context snapshot is an implementation of this file.
// Currently, it's implemented as tracking the current active node.
export opaque type ContextSnapshot = null | ContextNode<any>;
export const rootContextSnapshot: ContextSnapshot = null;
// We assume that this runtime owns the "current" field on all ReactContext instances.
// This global (actually thread local) state represents what state all those "current",
// fields are currently in.
let currentActiveSnapshot: ContextSnapshot = null;
function popNode(prev: ContextNode<any>): void {
if (isPrimaryRenderer) {
prev.context._currentValue = prev.parentValue;
} else {
prev.context._currentValue2 = prev.parentValue;
}
}
function pushNode(next: ContextNode<any>): void {
if (isPrimaryRenderer) {
next.context._currentValue = next.value;
} else {
next.context._currentValue2 = next.value;
}
}
function popToNearestCommonAncestor(
prev: ContextNode<any>,
next: ContextNode<any>,
): void {
if (prev === next) {
// We've found a shared ancestor. We don't need to pop nor reapply this one or anything above.
} else {
popNode(prev);
const parentPrev = prev.parent;
const parentNext = next.parent;
if (parentPrev === null) {
if (parentNext !== null) {
throw new Error(
'The stacks must reach the root at the same time. This is a bug in React.',
);
}
} else {
if (parentNext === null) {
throw new Error(
'The stacks must reach the root at the same time. This is a bug in React.',
);
}
popToNearestCommonAncestor(parentPrev, parentNext);
}
// On the way back, we push the new ones that weren't common.
pushNode(next);
}
}
function popAllPrevious(prev: ContextNode<any>): void {
popNode(prev);
const parentPrev = prev.parent;
if (parentPrev !== null) {
popAllPrevious(parentPrev);
}
}
function pushAllNext(next: ContextNode<any>): void {
const parentNext = next.parent;
if (parentNext !== null) {
pushAllNext(parentNext);
}
pushNode(next);
}
function popPreviousToCommonLevel(
prev: ContextNode<any>,
next: ContextNode<any>,
): void {
popNode(prev);
const parentPrev = prev.parent;
if (parentPrev === null) {
throw new Error(
'The depth must equal at least at zero before reaching the root. This is a bug in React.',
);
}
if (parentPrev.depth === next.depth) {
// We found the same level. Now we just need to find a shared ancestor.
popToNearestCommonAncestor(parentPrev, next);
} else {
// We must still be deeper.
popPreviousToCommonLevel(parentPrev, next);
}
}
function popNextToCommonLevel(
prev: ContextNode<any>,
next: ContextNode<any>,
): void {
const parentNext = next.parent;
if (parentNext === null) {
throw new Error(
'The depth must equal at least at zero before reaching the root. This is a bug in React.',
);
}
if (prev.depth === parentNext.depth) {
// We found the same level. Now we just need to find a shared ancestor.
popToNearestCommonAncestor(prev, parentNext);
} else {
// We must still be deeper.
popNextToCommonLevel(prev, parentNext);
}
pushNode(next);
}
// Perform context switching to the new snapshot.
// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
// updating all the context's current values. That way reads, always just read the current value.
// At the cost of updating contexts even if they're never read by this subtree.
export function switchContext(newSnapshot: ContextSnapshot): void {
// The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
// We also need to update any new contexts that are now on the stack with the deepest value.
// The easiest way to update new contexts is to just reapply them in reverse order from the
// perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
// for that. Therefore this algorithm is recursive.
// 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
// 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
// 3) Then we reapply new contexts on the way back up the stack.
const prev = currentActiveSnapshot;
const next = newSnapshot;
if (prev !== next) {
if (prev === null) {
// $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev.
pushAllNext(next);
} else if (next === null) {
popAllPrevious(prev);
} else if (prev.depth === next.depth) {
popToNearestCommonAncestor(prev, next);
} else if (prev.depth > next.depth) {
popPreviousToCommonLevel(prev, next);
} else {
popNextToCommonLevel(prev, next);
}
currentActiveSnapshot = next;
}
}
export function pushProvider<T>(
context: ReactContext<T>,
nextValue: T,
): ContextSnapshot {
let prevValue;
if (isPrimaryRenderer) {
prevValue = context._currentValue;
context._currentValue = nextValue;
if (__DEV__) {
if (
context._currentRenderer !== undefined &&
context._currentRenderer !== null &&
context._currentRenderer !== rendererSigil
) {
console.error(
'Detected multiple renderers concurrently rendering the ' +
'same context provider. This is currently unsupported.',
);
}
context._currentRenderer = rendererSigil;
}
} else {
prevValue = context._currentValue2;
context._currentValue2 = nextValue;
if (__DEV__) {
if (
context._currentRenderer2 !== undefined &&
context._currentRenderer2 !== null &&
context._currentRenderer2 !== rendererSigil
) {
console.error(
'Detected multiple renderers concurrently rendering the ' +
'same context provider. This is currently unsupported.',
);
}
context._currentRenderer2 = rendererSigil;
}
}
const prevNode = currentActiveSnapshot;
const newNode: ContextNode<T> = {
parent: prevNode,
depth: prevNode === null ? 0 : prevNode.depth + 1,
context: context,
parentValue: prevValue,
value: nextValue,
};
currentActiveSnapshot = newNode;
return newNode;
}
export function popProvider<T>(context: ReactContext<T>): ContextSnapshot {
const prevSnapshot = currentActiveSnapshot;
if (prevSnapshot === null) {
throw new Error(
'Tried to pop a Context at the root of the app. This is a bug in React.',
);
}
if (__DEV__) {
if (prevSnapshot.context !== context) {
console.error(
'The parent context is not the expected context. This is probably a bug in React.',
);
}
}
if (isPrimaryRenderer) {
const value = prevSnapshot.parentValue;
if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;
} else {
prevSnapshot.context._currentValue = value;
}
if (__DEV__) {
if (
context._currentRenderer !== undefined &&
context._currentRenderer !== null &&
context._currentRenderer !== rendererSigil
) {
console.error(
'Detected multiple renderers concurrently rendering the ' +
'same context provider. This is currently unsupported.',
);
}
context._currentRenderer = rendererSigil;
}
} else {
const value = prevSnapshot.parentValue;
if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue;
} else {
prevSnapshot.context._currentValue2 = value;
}
if (__DEV__) {
if (
context._currentRenderer2 !== undefined &&
context._currentRenderer2 !== null &&
context._currentRenderer2 !== rendererSigil
) {
console.error(
'Detected multiple renderers concurrently rendering the ' +
'same context provider. This is currently unsupported.',
);
}
context._currentRenderer2 = rendererSigil;
}
}
return (currentActiveSnapshot = prevSnapshot.parent);
}
export function getActiveContext(): ContextSnapshot {
return currentActiveSnapshot;
}
export function readContext<T>(context: ReactContext<T>): T {
const value = isPrimaryRenderer
? context._currentValue
: context._currentValue2;
return value;
}
| 30.076412 | 99 | 0.6677 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactNoop;
let act;
describe('ReactIncrementalUpdatesMinimalism', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
act = require('internal-test-utils').act;
});
it('should render a simple component', async () => {
function Child() {
return <div>Hello World</div>;
}
function Parent() {
return <Child />;
}
ReactNoop.startTrackingHostCounters();
await act(() => ReactNoop.render(<Parent />));
expect(ReactNoop.stopTrackingHostCounters()).toEqual({
hostUpdateCounter: 0,
});
ReactNoop.startTrackingHostCounters();
await act(() => ReactNoop.render(<Parent />));
expect(ReactNoop.stopTrackingHostCounters()).toEqual({
hostUpdateCounter: 1,
});
});
it('should not diff referentially equal host elements', async () => {
function Leaf(props) {
return (
<span>
hello
<b />
{props.name}
</span>
);
}
const constEl = (
<div>
<Leaf name="world" />
</div>
);
function Child() {
return constEl;
}
function Parent() {
return <Child />;
}
ReactNoop.startTrackingHostCounters();
await act(() => ReactNoop.render(<Parent />));
expect(ReactNoop.stopTrackingHostCounters()).toEqual({
hostUpdateCounter: 0,
});
ReactNoop.startTrackingHostCounters();
await act(() => ReactNoop.render(<Parent />));
expect(ReactNoop.stopTrackingHostCounters()).toEqual({
hostUpdateCounter: 0,
});
});
it('should not diff parents of setState targets', async () => {
let childInst;
function Leaf(props) {
return (
<span>
hello
<b />
{props.name}
</span>
);
}
class Child extends React.Component {
state = {name: 'Batman'};
render() {
childInst = this;
return (
<div>
<Leaf name={this.state.name} />
</div>
);
}
}
function Parent() {
return (
<section>
<div>
<Leaf name="world" />
<Child />
<hr />
<Leaf name="world" />
</div>
</section>
);
}
ReactNoop.startTrackingHostCounters();
await act(() => ReactNoop.render(<Parent />));
expect(ReactNoop.stopTrackingHostCounters()).toEqual({
hostUpdateCounter: 0,
});
ReactNoop.startTrackingHostCounters();
await act(() => childInst.setState({name: 'Robin'}));
expect(ReactNoop.stopTrackingHostCounters()).toEqual({
// Child > div
// Child > Leaf > span
// Child > Leaf > span > b
// Child > Leaf > span > #text
hostUpdateCounter: 4,
});
ReactNoop.startTrackingHostCounters();
await act(() => ReactNoop.render(<Parent />));
expect(ReactNoop.stopTrackingHostCounters()).toEqual({
// Parent > section
// Parent > section > div
// Parent > section > div > Leaf > span
// Parent > section > div > Leaf > span > b
// Parent > section > div > Child > div
// Parent > section > div > Child > div > Leaf > span
// Parent > section > div > Child > div > Leaf > span > b
// Parent > section > div > hr
// Parent > section > div > Leaf > span
// Parent > section > div > Leaf > span > b
hostUpdateCounter: 10,
});
});
});
| 22.878981 | 71 | 0.554696 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactDOMFizzStatic;
let Suspense;
describe('ReactDOMFizzStaticNode', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
if (__EXPERIMENTAL__) {
ReactDOMFizzStatic = require('react-dom/static');
}
Suspense = React.Suspense;
});
const theError = new Error('This is an error');
function Throw() {
throw theError;
}
const theInfinitePromise = new Promise(() => {});
function InfiniteSuspend() {
throw theInfinitePromise;
}
function readContent(readable) {
return new Promise((resolve, reject) => {
let content = '';
readable.on('data', chunk => {
content += Buffer.from(chunk).toString('utf8');
});
readable.on('error', error => {
reject(error);
});
readable.on('end', () => resolve(content));
});
}
// @gate experimental
it('should call prerenderToNodeStream', async () => {
const result = await ReactDOMFizzStatic.prerenderToNodeStream(
<div>hello world</div>,
);
const prelude = await readContent(result.prelude);
expect(prelude).toMatchInlineSnapshot(`"<div>hello world</div>"`);
});
// @gate experimental
it('should emit DOCTYPE at the root of the document', async () => {
const result = await ReactDOMFizzStatic.prerenderToNodeStream(
<html>
<body>hello world</body>
</html>,
);
const prelude = await readContent(result.prelude);
if (gate(flags => flags.enableFloat)) {
expect(prelude).toMatchInlineSnapshot(
`"<!DOCTYPE html><html><head></head><body>hello world</body></html>"`,
);
} else {
expect(prelude).toMatchInlineSnapshot(
`"<!DOCTYPE html><html><body>hello world</body></html>"`,
);
}
});
// @gate experimental
it('should emit bootstrap script src at the end', async () => {
const result = await ReactDOMFizzStatic.prerenderToNodeStream(
<div>hello world</div>,
{
bootstrapScriptContent: 'INIT();',
bootstrapScripts: ['init.js'],
bootstrapModules: ['init.mjs'],
},
);
const prelude = await readContent(result.prelude);
expect(prelude).toMatchInlineSnapshot(
`"<link rel="preload" as="script" fetchPriority="low" href="init.js"/><link rel="modulepreload" fetchPriority="low" href="init.mjs"/><div>hello world</div><script>INIT();</script><script src="init.js" async=""></script><script type="module" src="init.mjs" async=""></script>"`,
);
});
// @gate experimental
it('emits all HTML as one unit', async () => {
let hasLoaded = false;
let resolve;
const promise = new Promise(r => (resolve = r));
function Wait() {
if (!hasLoaded) {
throw promise;
}
return 'Done';
}
const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<Suspense fallback="Loading">
<Wait />
</Suspense>
</div>,
);
await jest.runAllTimers();
// Resolve the loading.
hasLoaded = true;
await resolve();
const result = await resultPromise;
const prelude = await readContent(result.prelude);
expect(prelude).toMatchInlineSnapshot(
`"<div><!--$-->Done<!-- --><!--/$--></div>"`,
);
});
// @gate experimental
it('should reject the promise when an error is thrown at the root', async () => {
const reportedErrors = [];
let caughtError = null;
try {
await ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<Throw />
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theError);
expect(reportedErrors).toEqual([theError]);
});
// @gate experimental
it('should reject the promise when an error is thrown inside a fallback', async () => {
const reportedErrors = [];
let caughtError = null;
try {
await ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<Suspense fallback={<Throw />}>
<InfiniteSuspend />
</Suspense>
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theError);
expect(reportedErrors).toEqual([theError]);
});
// @gate experimental
it('should not error the stream when an error is thrown inside suspense boundary', async () => {
const reportedErrors = [];
const result = await ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<Suspense fallback={<div>Loading</div>}>
<Throw />
</Suspense>
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
const prelude = await readContent(result.prelude);
expect(prelude).toContain('Loading');
expect(reportedErrors).toEqual([theError]);
});
// @gate experimental
it('should be able to complete by aborting even if the promise never resolves', async () => {
const errors = [];
const controller = new AbortController();
const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
await jest.runAllTimers();
controller.abort();
const result = await resultPromise;
const prelude = await readContent(result.prelude);
expect(prelude).toContain('Loading');
expect(errors).toEqual(['This operation was aborted']);
});
// @gate experimental
it('should reject if aborting before the shell is complete', async () => {
const errors = [];
const controller = new AbortController();
const promise = ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<InfiniteSuspend />
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
await jest.runAllTimers();
const theReason = new Error('aborted for reasons');
controller.abort(theReason);
let caughtError = null;
try {
await promise;
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theReason);
expect(errors).toEqual(['aborted for reasons']);
});
// @gate experimental
it('should be able to abort before something suspends', async () => {
const errors = [];
const controller = new AbortController();
function App() {
controller.abort();
return (
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
);
}
const streamPromise = ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<App />
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
let caughtError = null;
try {
await streamPromise;
} catch (error) {
caughtError = error;
}
expect(caughtError.message).toBe('This operation was aborted');
expect(errors).toEqual(['This operation was aborted']);
});
// @gate experimental
it('should reject if passing an already aborted signal', async () => {
const errors = [];
const controller = new AbortController();
const theReason = new Error('aborted for reasons');
controller.abort(theReason);
const promise = ReactDOMFizzStatic.prerenderToNodeStream(
<div>
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
</div>,
{
signal: controller.signal,
onError(x) {
errors.push(x.message);
},
},
);
// Technically we could still continue rendering the shell but currently the
// semantics mean that we also abort any pending CPU work.
let caughtError = null;
try {
await promise;
} catch (error) {
caughtError = error;
}
expect(caughtError).toBe(theReason);
expect(errors).toEqual(['aborted for reasons']);
});
// @gate experimental
it('supports custom abort reasons with a string', async () => {
const promise = new Promise(r => {});
function Wait() {
throw promise;
}
function App() {
return (
<div>
<p>
<Suspense fallback={'p'}>
<Wait />
</Suspense>
</p>
<span>
<Suspense fallback={'span'}>
<Wait />
</Suspense>
</span>
</div>
);
}
const errors = [];
const controller = new AbortController();
const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream(<App />, {
signal: controller.signal,
onError(x) {
errors.push(x);
return 'a digest';
},
});
await jest.runAllTimers();
controller.abort('foobar');
await resultPromise;
expect(errors).toEqual(['foobar', 'foobar']);
});
// @gate experimental
it('supports custom abort reasons with an Error', async () => {
const promise = new Promise(r => {});
function Wait() {
throw promise;
}
function App() {
return (
<div>
<p>
<Suspense fallback={'p'}>
<Wait />
</Suspense>
</p>
<span>
<Suspense fallback={'span'}>
<Wait />
</Suspense>
</span>
</div>
);
}
const errors = [];
const controller = new AbortController();
const resultPromise = ReactDOMFizzStatic.prerenderToNodeStream(<App />, {
signal: controller.signal,
onError(x) {
errors.push(x.message);
return 'a digest';
},
});
await jest.runAllTimers();
controller.abort(new Error('uh oh'));
await resultPromise;
expect(errors).toEqual(['uh oh', 'uh oh']);
});
});
| 24.695545 | 283 | 0.573603 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const fs = require('fs');
const path = require('path');
const existingErrorMap = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '../error-codes/codes.json'))
);
const messages = new Set();
Object.keys(existingErrorMap).forEach(key =>
messages.add(existingErrorMap[key])
);
/**
* The warning() function takes format strings as its second
* argument.
*/
module.exports = {
meta: {
schema: [],
},
create(context) {
// we also allow literal strings and concatenated literal strings
function getLiteralString(node) {
if (node.type === 'Literal' && typeof node.value === 'string') {
return node.value;
} else if (node.type === 'BinaryExpression' && node.operator === '+') {
const l = getLiteralString(node.left);
const r = getLiteralString(node.right);
if (l !== null && r !== null) {
return l + r;
}
}
return null;
}
return {
CallExpression: function (node) {
// This could be a little smarter by checking context.getScope() to see
// how warning/invariant was defined.
const isWarning =
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'console' &&
node.callee.property.type === 'Identifier' &&
(node.callee.property.name === 'error' ||
node.callee.property.name === 'warn');
if (!isWarning) {
return;
}
const name = 'console.' + node.callee.property.name;
if (node.arguments.length < 1) {
context.report(node, '{{name}} takes at least one argument', {
name,
});
return;
}
const format = getLiteralString(node.arguments[0]);
if (format === null) {
context.report(
node,
'The first argument to {{name}} must be a string literal',
{name}
);
return;
}
if (format.length < 10 || /^[s\W]*$/.test(format)) {
context.report(
node,
'The {{name}} format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: {{format}}',
{name, format}
);
return;
}
// count the number of formatting substitutions, plus the first two args
const expectedNArgs = (format.match(/%s/g) || []).length + 1;
if (node.arguments.length !== expectedNArgs) {
context.report(
node,
'Expected {{expectedNArgs}} arguments in call to {{name}} based on ' +
'the number of "%s" substitutions, but got {{length}}',
{
expectedNArgs: expectedNArgs,
name,
length: node.arguments.length,
}
);
}
},
};
},
};
| 29.601942 | 82 | 0.545858 |
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
*/
/**
* Converts nested hooks paths to the format expected by the backend.
* e.g. [''] => ['']
* e.g. [1, 'value', ...] => [...]
* e.g. [2, 'subhooks', 1, 'value', ...] => [...]
* e.g. [1, 'subhooks', 3, 'subhooks', 2, 'value', ...] => [...]
*/
export function parseHookPathForEdit(
path: Array<string | number>,
): Array<string | number> {
let index = 0;
for (let i = 0; i < path.length; i++) {
if (path[i] === 'value') {
index = i + 1;
break;
}
}
return path.slice(index);
}
| 23.689655 | 69 | 0.54965 |
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 {DOMEventName} from './DOMEventNames';
import type {EventSystemFlags} from './EventSystemFlags';
import type {AnyNativeEvent} from './PluginModuleType';
import type {
KnownReactSyntheticEvent,
ReactSyntheticEvent,
} from './ReactSyntheticEventType';
import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
import {allNativeEvents} from './EventRegistry';
import {
SHOULD_NOT_DEFER_CLICK_FOR_FB_SUPPORT_MODE,
IS_LEGACY_FB_SUPPORT_MODE,
SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS,
IS_CAPTURE_PHASE,
IS_EVENT_HANDLE_NON_MANAGED_NODE,
IS_NON_DELEGATED,
} from './EventSystemFlags';
import {isReplayingEvent} from './CurrentReplayingEvent';
import {
HostRoot,
HostPortal,
HostComponent,
HostHoistable,
HostSingleton,
HostText,
ScopeComponent,
} from 'react-reconciler/src/ReactWorkTags';
import getEventTarget from './getEventTarget';
import {
getClosestInstanceFromNode,
getEventListenerSet,
getEventHandlerListeners,
} from '../client/ReactDOMComponentTree';
import {COMMENT_NODE, DOCUMENT_NODE} from '../client/HTMLNodeType';
import {batchedUpdates} from './ReactDOMUpdateBatching';
import getListener from './getListener';
import {passiveBrowserEventsSupported} from './checkPassiveEvents';
import {
enableLegacyFBSupport,
enableCreateEventHandleAPI,
enableScopeAPI,
enableFloat,
enableFormActions,
} from 'shared/ReactFeatureFlags';
import {
invokeGuardedCallbackAndCatchFirstError,
rethrowCaughtError,
} from 'shared/ReactErrorUtils';
import {createEventListenerWrapperWithPriority} from './ReactDOMEventListener';
import {
removeEventListener,
addEventCaptureListener,
addEventBubbleListener,
addEventBubbleListenerWithPassiveFlag,
addEventCaptureListenerWithPassiveFlag,
} from './EventListener';
import * as BeforeInputEventPlugin from './plugins/BeforeInputEventPlugin';
import * as ChangeEventPlugin from './plugins/ChangeEventPlugin';
import * as EnterLeaveEventPlugin from './plugins/EnterLeaveEventPlugin';
import * as SelectEventPlugin from './plugins/SelectEventPlugin';
import * as SimpleEventPlugin from './plugins/SimpleEventPlugin';
import * as FormActionEventPlugin from './plugins/FormActionEventPlugin';
type DispatchListener = {
instance: null | Fiber,
listener: Function,
currentTarget: EventTarget,
};
type DispatchEntry = {
event: ReactSyntheticEvent,
listeners: Array<DispatchListener>,
};
export type DispatchQueue = Array<DispatchEntry>;
// TODO: remove top-level side effect.
SimpleEventPlugin.registerEvents();
EnterLeaveEventPlugin.registerEvents();
ChangeEventPlugin.registerEvents();
SelectEventPlugin.registerEvents();
BeforeInputEventPlugin.registerEvents();
function extractEvents(
dispatchQueue: DispatchQueue,
domEventName: DOMEventName,
targetInst: null | Fiber,
nativeEvent: AnyNativeEvent,
nativeEventTarget: null | EventTarget,
eventSystemFlags: EventSystemFlags,
targetContainer: EventTarget,
) {
// TODO: we should remove the concept of a "SimpleEventPlugin".
// This is the basic functionality of the event system. All
// the other plugins are essentially polyfills. So the plugin
// should probably be inlined somewhere and have its logic
// be core the to event system. This would potentially allow
// us to ship builds of React without the polyfilled plugins below.
SimpleEventPlugin.extractEvents(
dispatchQueue,
domEventName,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
const shouldProcessPolyfillPlugins =
(eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0;
// We don't process these events unless we are in the
// event's native "bubble" phase, which means that we're
// not in the capture phase. That's because we emulate
// the capture phase here still. This is a trade-off,
// because in an ideal world we would not emulate and use
// the phases properly, like we do with the SimpleEvent
// plugin. However, the plugins below either expect
// emulation (EnterLeave) or use state localized to that
// plugin (BeforeInput, Change, Select). The state in
// these modules complicates things, as you'll essentially
// get the case where the capture phase event might change
// state, only for the following bubble event to come in
// later and not trigger anything as the state now
// invalidates the heuristics of the event plugin. We
// could alter all these plugins to work in such ways, but
// that might cause other unknown side-effects that we
// can't foresee right now.
if (shouldProcessPolyfillPlugins) {
EnterLeaveEventPlugin.extractEvents(
dispatchQueue,
domEventName,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
ChangeEventPlugin.extractEvents(
dispatchQueue,
domEventName,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
SelectEventPlugin.extractEvents(
dispatchQueue,
domEventName,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
BeforeInputEventPlugin.extractEvents(
dispatchQueue,
domEventName,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
if (enableFormActions) {
FormActionEventPlugin.extractEvents(
dispatchQueue,
domEventName,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
}
}
}
// List of events that need to be individually attached to media elements.
export const mediaEventTypes: Array<DOMEventName> = [
'abort',
'canplay',
'canplaythrough',
'durationchange',
'emptied',
'encrypted',
'ended',
'error',
'loadeddata',
'loadedmetadata',
'loadstart',
'pause',
'play',
'playing',
'progress',
'ratechange',
'resize',
'seeked',
'seeking',
'stalled',
'suspend',
'timeupdate',
'volumechange',
'waiting',
];
// We should not delegate these events to the container, but rather
// set them on the actual target element itself. This is primarily
// because these events do not consistently bubble in the DOM.
export const nonDelegatedEvents: Set<DOMEventName> = new Set([
'cancel',
'close',
'invalid',
'load',
'scroll',
'scrollend',
'toggle',
// In order to reduce bytes, we insert the above array of media events
// into this Set. Note: the "error" event isn't an exclusive media event,
// and can occur on other elements too. Rather than duplicate that event,
// we just take it from the media events array.
...mediaEventTypes,
]);
function executeDispatch(
event: ReactSyntheticEvent,
listener: Function,
currentTarget: EventTarget,
): void {
const type = event.type || 'unknown-event';
event.currentTarget = currentTarget;
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
event.currentTarget = null;
}
function processDispatchQueueItemsInOrder(
event: ReactSyntheticEvent,
dispatchListeners: Array<DispatchListener>,
inCapturePhase: boolean,
): void {
let previousInstance;
if (inCapturePhase) {
for (let i = dispatchListeners.length - 1; i >= 0; i--) {
const {instance, currentTarget, listener} = dispatchListeners[i];
if (instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, listener, currentTarget);
previousInstance = instance;
}
} else {
for (let i = 0; i < dispatchListeners.length; i++) {
const {instance, currentTarget, listener} = dispatchListeners[i];
if (instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, listener, currentTarget);
previousInstance = instance;
}
}
}
export function processDispatchQueue(
dispatchQueue: DispatchQueue,
eventSystemFlags: EventSystemFlags,
): void {
const inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
for (let i = 0; i < dispatchQueue.length; i++) {
const {event, listeners} = dispatchQueue[i];
processDispatchQueueItemsInOrder(event, listeners, inCapturePhase);
// event system doesn't use pooling.
}
// This would be a good time to rethrow if any of the event handlers threw.
rethrowCaughtError();
}
function dispatchEventsForPlugins(
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
nativeEvent: AnyNativeEvent,
targetInst: null | Fiber,
targetContainer: EventTarget,
): void {
const nativeEventTarget = getEventTarget(nativeEvent);
const dispatchQueue: DispatchQueue = [];
extractEvents(
dispatchQueue,
domEventName,
targetInst,
nativeEvent,
nativeEventTarget,
eventSystemFlags,
targetContainer,
);
processDispatchQueue(dispatchQueue, eventSystemFlags);
}
export function listenToNonDelegatedEvent(
domEventName: DOMEventName,
targetElement: Element,
): void {
if (__DEV__) {
if (!nonDelegatedEvents.has(domEventName)) {
console.error(
'Did not expect a listenToNonDelegatedEvent() call for "%s". ' +
'This is a bug in React. Please file an issue.',
domEventName,
);
}
}
const isCapturePhaseListener = false;
const listenerSet = getEventListenerSet(targetElement);
const listenerSetKey = getListenerSetKey(
domEventName,
isCapturePhaseListener,
);
if (!listenerSet.has(listenerSetKey)) {
addTrappedEventListener(
targetElement,
domEventName,
IS_NON_DELEGATED,
isCapturePhaseListener,
);
listenerSet.add(listenerSetKey);
}
}
export function listenToNativeEvent(
domEventName: DOMEventName,
isCapturePhaseListener: boolean,
target: EventTarget,
): void {
if (__DEV__) {
if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
console.error(
'Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' +
'This is a bug in React. Please file an issue.',
domEventName,
);
}
}
let eventSystemFlags = 0;
if (isCapturePhaseListener) {
eventSystemFlags |= IS_CAPTURE_PHASE;
}
addTrappedEventListener(
target,
domEventName,
eventSystemFlags,
isCapturePhaseListener,
);
}
// This is only used by createEventHandle when the
// target is not a DOM element. E.g. window.
export function listenToNativeEventForNonManagedEventTarget(
domEventName: DOMEventName,
isCapturePhaseListener: boolean,
target: EventTarget,
): void {
let eventSystemFlags = IS_EVENT_HANDLE_NON_MANAGED_NODE;
const listenerSet = getEventListenerSet(target);
const listenerSetKey = getListenerSetKey(
domEventName,
isCapturePhaseListener,
);
if (!listenerSet.has(listenerSetKey)) {
if (isCapturePhaseListener) {
eventSystemFlags |= IS_CAPTURE_PHASE;
}
addTrappedEventListener(
target,
domEventName,
eventSystemFlags,
isCapturePhaseListener,
);
listenerSet.add(listenerSetKey);
}
}
const listeningMarker = '_reactListening' + Math.random().toString(36).slice(2);
export function listenToAllSupportedEvents(rootContainerElement: EventTarget) {
if (!(rootContainerElement: any)[listeningMarker]) {
(rootContainerElement: any)[listeningMarker] = true;
allNativeEvents.forEach(domEventName => {
// We handle selectionchange separately because it
// doesn't bubble and needs to be on the document.
if (domEventName !== 'selectionchange') {
if (!nonDelegatedEvents.has(domEventName)) {
listenToNativeEvent(domEventName, false, rootContainerElement);
}
listenToNativeEvent(domEventName, true, rootContainerElement);
}
});
const ownerDocument =
(rootContainerElement: any).nodeType === DOCUMENT_NODE
? rootContainerElement
: (rootContainerElement: any).ownerDocument;
if (ownerDocument !== null) {
// The selectionchange event also needs deduplication
// but it is attached to the document.
if (!(ownerDocument: any)[listeningMarker]) {
(ownerDocument: any)[listeningMarker] = true;
listenToNativeEvent('selectionchange', false, ownerDocument);
}
}
}
}
function addTrappedEventListener(
targetContainer: EventTarget,
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
isCapturePhaseListener: boolean,
isDeferredListenerForLegacyFBSupport?: boolean,
) {
let listener = createEventListenerWrapperWithPriority(
targetContainer,
domEventName,
eventSystemFlags,
);
// If passive option is not supported, then the event will be
// active and not passive.
let isPassiveListener: void | boolean = undefined;
if (passiveBrowserEventsSupported) {
// Browsers introduced an intervention, making these events
// passive by default on document. React doesn't bind them
// to document anymore, but changing this now would undo
// the performance wins from the change. So we emulate
// the existing behavior manually on the roots now.
// https://github.com/facebook/react/issues/19651
if (
domEventName === 'touchstart' ||
domEventName === 'touchmove' ||
domEventName === 'wheel'
) {
isPassiveListener = true;
}
}
targetContainer =
enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport
? (targetContainer: any).ownerDocument
: targetContainer;
let unsubscribeListener;
// When legacyFBSupport is enabled, it's for when we
// want to add a one time event listener to a container.
// This should only be used with enableLegacyFBSupport
// due to requirement to provide compatibility with
// internal FB www event tooling. This works by removing
// the event listener as soon as it is invoked. We could
// also attempt to use the {once: true} param on
// addEventListener, but that requires support and some
// browsers do not support this today, and given this is
// to support legacy code patterns, it's likely they'll
// need support for such browsers.
if (enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport) {
const originalListener = listener;
// $FlowFixMe[missing-this-annot]
listener = function (...p) {
removeEventListener(
targetContainer,
domEventName,
unsubscribeListener,
isCapturePhaseListener,
);
return originalListener.apply(this, p);
};
}
// TODO: There are too many combinations here. Consolidate them.
if (isCapturePhaseListener) {
if (isPassiveListener !== undefined) {
unsubscribeListener = addEventCaptureListenerWithPassiveFlag(
targetContainer,
domEventName,
listener,
isPassiveListener,
);
} else {
unsubscribeListener = addEventCaptureListener(
targetContainer,
domEventName,
listener,
);
}
} else {
if (isPassiveListener !== undefined) {
unsubscribeListener = addEventBubbleListenerWithPassiveFlag(
targetContainer,
domEventName,
listener,
isPassiveListener,
);
} else {
unsubscribeListener = addEventBubbleListener(
targetContainer,
domEventName,
listener,
);
}
}
}
function deferClickToDocumentForLegacyFBSupport(
domEventName: DOMEventName,
targetContainer: EventTarget,
): void {
// We defer all click events with legacy FB support mode on.
// This means we add a one time event listener to trigger
// after the FB delegated listeners fire.
const isDeferredListenerForLegacyFBSupport = true;
addTrappedEventListener(
targetContainer,
domEventName,
IS_LEGACY_FB_SUPPORT_MODE,
false,
isDeferredListenerForLegacyFBSupport,
);
}
function isMatchingRootContainer(
grandContainer: Element,
targetContainer: EventTarget,
): boolean {
return (
grandContainer === targetContainer ||
(grandContainer.nodeType === COMMENT_NODE &&
grandContainer.parentNode === targetContainer)
);
}
export function dispatchEventForPluginEventSystem(
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
nativeEvent: AnyNativeEvent,
targetInst: null | Fiber,
targetContainer: EventTarget,
): void {
let ancestorInst = targetInst;
if (
(eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 &&
(eventSystemFlags & IS_NON_DELEGATED) === 0
) {
const targetContainerNode = ((targetContainer: any): Node);
// If we are using the legacy FB support flag, we
// defer the event to the null with a one
// time event listener so we can defer the event.
if (
enableLegacyFBSupport &&
// If our event flags match the required flags for entering
// FB legacy mode and we are processing the "click" event,
// then we can defer the event to the "document", to allow
// for legacy FB support, where the expected behavior was to
// match React < 16 behavior of delegated clicks to the doc.
domEventName === 'click' &&
(eventSystemFlags & SHOULD_NOT_DEFER_CLICK_FOR_FB_SUPPORT_MODE) === 0 &&
!isReplayingEvent(nativeEvent)
) {
deferClickToDocumentForLegacyFBSupport(domEventName, targetContainer);
return;
}
if (targetInst !== null) {
// The below logic attempts to work out if we need to change
// the target fiber to a different ancestor. We had similar logic
// in the legacy event system, except the big difference between
// systems is that the modern event system now has an event listener
// attached to each React Root and React Portal Root. Together,
// the DOM nodes representing these roots are the "rootContainer".
// To figure out which ancestor instance we should use, we traverse
// up the fiber tree from the target instance and attempt to find
// root boundaries that match that of our current "rootContainer".
// If we find that "rootContainer", we find the parent fiber
// sub-tree for that root and make that our ancestor instance.
let node: null | Fiber = targetInst;
mainLoop: while (true) {
if (node === null) {
return;
}
const nodeTag = node.tag;
if (nodeTag === HostRoot || nodeTag === HostPortal) {
let container = node.stateNode.containerInfo;
if (isMatchingRootContainer(container, targetContainerNode)) {
break;
}
if (nodeTag === HostPortal) {
// The target is a portal, but it's not the rootContainer we're looking for.
// Normally portals handle their own events all the way down to the root.
// So we should be able to stop now. However, we don't know if this portal
// was part of *our* root.
let grandNode = node.return;
while (grandNode !== null) {
const grandTag = grandNode.tag;
if (grandTag === HostRoot || grandTag === HostPortal) {
const grandContainer = grandNode.stateNode.containerInfo;
if (
isMatchingRootContainer(grandContainer, targetContainerNode)
) {
// This is the rootContainer we're looking for and we found it as
// a parent of the Portal. That means we can ignore it because the
// Portal will bubble through to us.
return;
}
}
grandNode = grandNode.return;
}
}
// Now we need to find it's corresponding host fiber in the other
// tree. To do this we can use getClosestInstanceFromNode, but we
// need to validate that the fiber is a host instance, otherwise
// we need to traverse up through the DOM till we find the correct
// node that is from the other tree.
while (container !== null) {
const parentNode = getClosestInstanceFromNode(container);
if (parentNode === null) {
return;
}
const parentTag = parentNode.tag;
if (
parentTag === HostComponent ||
parentTag === HostText ||
(enableFloat ? parentTag === HostHoistable : false) ||
parentTag === HostSingleton
) {
node = ancestorInst = parentNode;
continue mainLoop;
}
container = container.parentNode;
}
}
node = node.return;
}
}
}
batchedUpdates(() =>
dispatchEventsForPlugins(
domEventName,
eventSystemFlags,
nativeEvent,
ancestorInst,
targetContainer,
),
);
}
function createDispatchListener(
instance: null | Fiber,
listener: Function,
currentTarget: EventTarget,
): DispatchListener {
return {
instance,
listener,
currentTarget,
};
}
export function accumulateSinglePhaseListeners(
targetFiber: Fiber | null,
reactName: string | null,
nativeEventType: string,
inCapturePhase: boolean,
accumulateTargetOnly: boolean,
nativeEvent: AnyNativeEvent,
): Array<DispatchListener> {
const captureName = reactName !== null ? reactName + 'Capture' : null;
const reactEventName = inCapturePhase ? captureName : reactName;
let listeners: Array<DispatchListener> = [];
let instance = targetFiber;
let lastHostComponent = null;
// Accumulate all instances and listeners via the target -> root path.
while (instance !== null) {
const {stateNode, tag} = instance;
// Handle listeners that are on HostComponents (i.e. <div>)
if (
(tag === HostComponent ||
(enableFloat ? tag === HostHoistable : false) ||
tag === HostSingleton) &&
stateNode !== null
) {
lastHostComponent = stateNode;
// createEventHandle listeners
if (enableCreateEventHandleAPI) {
const eventHandlerListeners =
getEventHandlerListeners(lastHostComponent);
if (eventHandlerListeners !== null) {
eventHandlerListeners.forEach(entry => {
if (
entry.type === nativeEventType &&
entry.capture === inCapturePhase
) {
listeners.push(
createDispatchListener(
instance,
entry.callback,
(lastHostComponent: any),
),
);
}
});
}
}
// Standard React on* listeners, i.e. onClick or onClickCapture
if (reactEventName !== null) {
const listener = getListener(instance, reactEventName);
if (listener != null) {
listeners.push(
createDispatchListener(instance, listener, lastHostComponent),
);
}
}
} else if (
enableCreateEventHandleAPI &&
enableScopeAPI &&
tag === ScopeComponent &&
lastHostComponent !== null &&
stateNode !== null
) {
// Scopes
const reactScopeInstance = stateNode;
const eventHandlerListeners =
getEventHandlerListeners(reactScopeInstance);
if (eventHandlerListeners !== null) {
eventHandlerListeners.forEach(entry => {
if (
entry.type === nativeEventType &&
entry.capture === inCapturePhase
) {
listeners.push(
createDispatchListener(
instance,
entry.callback,
(lastHostComponent: any),
),
);
}
});
}
}
// If we are only accumulating events for the target, then we don't
// continue to propagate through the React fiber tree to find other
// listeners.
if (accumulateTargetOnly) {
break;
}
// If we are processing the onBeforeBlur event, then we need to take
// into consideration that part of the React tree might have been hidden
// or deleted (as we're invoking this event during commit). We can find
// this out by checking if intercept fiber set on the event matches the
// current instance fiber. In which case, we should clear all existing
// listeners.
if (enableCreateEventHandleAPI && nativeEvent.type === 'beforeblur') {
// $FlowFixMe[prop-missing] internal field
const detachedInterceptFiber = nativeEvent._detachedInterceptFiber;
if (
detachedInterceptFiber !== null &&
(detachedInterceptFiber === instance ||
detachedInterceptFiber === instance.alternate)
) {
listeners = [];
}
}
instance = instance.return;
}
return listeners;
}
// We should only use this function for:
// - BeforeInputEventPlugin
// - ChangeEventPlugin
// - SelectEventPlugin
// This is because we only process these plugins
// in the bubble phase, so we need to accumulate two
// phase event listeners (via emulation).
export function accumulateTwoPhaseListeners(
targetFiber: Fiber | null,
reactName: string,
): Array<DispatchListener> {
const captureName = reactName + 'Capture';
const listeners: Array<DispatchListener> = [];
let instance = targetFiber;
// Accumulate all instances and listeners via the target -> root path.
while (instance !== null) {
const {stateNode, tag} = instance;
// Handle listeners that are on HostComponents (i.e. <div>)
if (
(tag === HostComponent ||
(enableFloat ? tag === HostHoistable : false) ||
tag === HostSingleton) &&
stateNode !== null
) {
const currentTarget = stateNode;
const captureListener = getListener(instance, captureName);
if (captureListener != null) {
listeners.unshift(
createDispatchListener(instance, captureListener, currentTarget),
);
}
const bubbleListener = getListener(instance, reactName);
if (bubbleListener != null) {
listeners.push(
createDispatchListener(instance, bubbleListener, currentTarget),
);
}
}
instance = instance.return;
}
return listeners;
}
function getParent(inst: Fiber | null): Fiber | null {
if (inst === null) {
return null;
}
do {
// $FlowFixMe[incompatible-use] found when upgrading Flow
inst = inst.return;
// TODO: If this is a HostRoot we might want to bail out.
// That is depending on if we want nested subtrees (layers) to bubble
// events to their parent. We could also go through parentNode on the
// host node but that wouldn't work for React Native and doesn't let us
// do the portal feature.
} while (inst && inst.tag !== HostComponent && inst.tag !== HostSingleton);
if (inst) {
return inst;
}
return null;
}
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA: Fiber, instB: Fiber): Fiber | null {
let nodeA: null | Fiber = instA;
let nodeB: null | Fiber = instB;
let depthA = 0;
for (let tempA: null | Fiber = nodeA; tempA; tempA = getParent(tempA)) {
depthA++;
}
let depthB = 0;
for (let tempB: null | Fiber = nodeB; tempB; tempB = getParent(tempB)) {
depthB++;
}
// If A is deeper, crawl up.
while (depthA - depthB > 0) {
nodeA = getParent(nodeA);
depthA--;
}
// If B is deeper, crawl up.
while (depthB - depthA > 0) {
nodeB = getParent(nodeB);
depthB--;
}
// Walk in lockstep until we find a match.
let depth = depthA;
while (depth--) {
if (nodeA === nodeB || (nodeB !== null && nodeA === nodeB.alternate)) {
return nodeA;
}
nodeA = getParent(nodeA);
nodeB = getParent(nodeB);
}
return null;
}
function accumulateEnterLeaveListenersForEvent(
dispatchQueue: DispatchQueue,
event: KnownReactSyntheticEvent,
target: Fiber,
common: Fiber | null,
inCapturePhase: boolean,
): void {
const registrationName = event._reactName;
const listeners: Array<DispatchListener> = [];
let instance: null | Fiber = target;
while (instance !== null) {
if (instance === common) {
break;
}
const {alternate, stateNode, tag} = instance;
if (alternate !== null && alternate === common) {
break;
}
if (
(tag === HostComponent ||
(enableFloat ? tag === HostHoistable : false) ||
tag === HostSingleton) &&
stateNode !== null
) {
const currentTarget = stateNode;
if (inCapturePhase) {
const captureListener = getListener(instance, registrationName);
if (captureListener != null) {
listeners.unshift(
createDispatchListener(instance, captureListener, currentTarget),
);
}
} else if (!inCapturePhase) {
const bubbleListener = getListener(instance, registrationName);
if (bubbleListener != null) {
listeners.push(
createDispatchListener(instance, bubbleListener, currentTarget),
);
}
}
}
instance = instance.return;
}
if (listeners.length !== 0) {
dispatchQueue.push({event, listeners});
}
}
// We should only use this function for:
// - EnterLeaveEventPlugin
// This is because we only process this plugin
// in the bubble phase, so we need to accumulate two
// phase event listeners.
export function accumulateEnterLeaveTwoPhaseListeners(
dispatchQueue: DispatchQueue,
leaveEvent: KnownReactSyntheticEvent,
enterEvent: null | KnownReactSyntheticEvent,
from: Fiber | null,
to: Fiber | null,
): void {
const common = from && to ? getLowestCommonAncestor(from, to) : null;
if (from !== null) {
accumulateEnterLeaveListenersForEvent(
dispatchQueue,
leaveEvent,
from,
common,
false,
);
}
if (to !== null && enterEvent !== null) {
accumulateEnterLeaveListenersForEvent(
dispatchQueue,
enterEvent,
to,
common,
true,
);
}
}
export function accumulateEventHandleNonManagedNodeListeners(
reactEventType: DOMEventName,
currentTarget: EventTarget,
inCapturePhase: boolean,
): Array<DispatchListener> {
const listeners: Array<DispatchListener> = [];
const eventListeners = getEventHandlerListeners(currentTarget);
if (eventListeners !== null) {
eventListeners.forEach(entry => {
if (entry.type === reactEventType && entry.capture === inCapturePhase) {
listeners.push(
createDispatchListener(null, entry.callback, currentTarget),
);
}
});
}
return listeners;
}
export function getListenerSetKey(
domEventName: DOMEventName,
capture: boolean,
): string {
return `${domEventName}__${capture ? 'capture' : 'bubble'}`;
}
| 30.081918 | 88 | 0.668102 |
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.
*/
import getComponentNameFromType from 'shared/getComponentNameFromType';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import hasOwnProperty from 'shared/hasOwnProperty';
import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';
import {checkKeyStringCoercion} from 'shared/CheckStringCoercion';
const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
const RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true,
};
let specialPropKeyWarningShown;
let specialPropRefWarningShown;
let didWarnAboutStringRefs;
if (__DEV__) {
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
if (__DEV__) {
if (hasOwnProperty.call(config, 'ref')) {
const getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
if (__DEV__) {
if (hasOwnProperty.call(config, 'key')) {
const getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function warnIfStringRefCannotBeAutoConverted(config, self) {
if (__DEV__) {
if (
typeof config.ref === 'string' &&
ReactCurrentOwner.current &&
self &&
ReactCurrentOwner.current.stateNode !== self
) {
const componentName = getComponentNameFromType(
ReactCurrentOwner.current.type,
);
if (!didWarnAboutStringRefs[componentName]) {
console.error(
'Component "%s" contains the string ref "%s". ' +
'Support for string refs will be removed in a future major release. ' +
'This case cannot be automatically converted to an arrow function. ' +
'We ask you to manually fix this case by using useRef() or createRef() instead. ' +
'Learn more about using refs safely here: ' +
'https://reactjs.org/link/strict-mode-string-ref',
getComponentNameFromType(ReactCurrentOwner.current.type),
config.ref,
);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
function defineKeyPropWarningGetter(props, displayName) {
if (__DEV__) {
const warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
console.error(
'%s: `key` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' +
'prop. (https://reactjs.org/link/special-props)',
displayName,
);
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true,
});
}
}
function defineRefPropWarningGetter(props, displayName) {
if (__DEV__) {
const warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
console.error(
'%s: `ref` is not a prop. Trying to access it will result ' +
'in `undefined` being returned. If you need to access the same ' +
'value within the child component, you should pass it as a different ' +
'prop. (https://reactjs.org/link/special-props)',
displayName,
);
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true,
});
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
function ReactElement(type, key, ref, self, source, owner, props) {
const element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type,
key,
ref,
props,
// Record the component responsible for creating this element.
_owner: owner,
};
if (__DEV__) {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false,
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self,
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source,
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
}
/**
* https://github.com/reactjs/rfcs/pull/107
* @param {*} type
* @param {object} props
* @param {string} key
*/
export function jsx(type, config, maybeKey) {
let propName;
// Reserved names are extracted
const props = {};
let key = null;
let ref = null;
// Currently, key can be spread in as a prop. This causes a potential
// issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
// or <div key="Hi" {...props} /> ). We want to deprecate key spread,
// but as an intermediary step, we will use jsxDEV for everything except
// <div {...props} key="Hi" />, because we aren't currently able to tell if
// key is explicitly declared to be undefined or not.
if (maybeKey !== undefined) {
if (__DEV__) {
checkKeyStringCoercion(maybeKey);
}
key = '' + maybeKey;
}
if (hasValidKey(config)) {
if (__DEV__) {
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
}
if (hasValidRef(config)) {
ref = config.ref;
}
// Remaining properties are added to a new props object
for (propName in config) {
if (
hasOwnProperty.call(config, propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)
) {
props[propName] = config[propName];
}
}
// Resolve default props
if (type && type.defaultProps) {
const defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
return ReactElement(
type,
key,
ref,
undefined,
undefined,
ReactCurrentOwner.current,
props,
);
}
/**
* https://github.com/reactjs/rfcs/pull/107
* @param {*} type
* @param {object} props
* @param {string} key
*/
export function jsxDEV(type, config, maybeKey, source, self) {
if (__DEV__) {
let propName;
// Reserved names are extracted
const props = {};
let key = null;
let ref = null;
// Currently, key can be spread in as a prop. This causes a potential
// issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
// or <div key="Hi" {...props} /> ). We want to deprecate key spread,
// but as an intermediary step, we will use jsxDEV for everything except
// <div {...props} key="Hi" />, because we aren't currently able to tell if
// key is explicitly declared to be undefined or not.
if (maybeKey !== undefined) {
if (__DEV__) {
checkKeyStringCoercion(maybeKey);
}
key = '' + maybeKey;
}
if (hasValidKey(config)) {
if (__DEV__) {
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
}
if (hasValidRef(config)) {
ref = config.ref;
warnIfStringRefCannotBeAutoConverted(config, self);
}
// Remaining properties are added to a new props object
for (propName in config) {
if (
hasOwnProperty.call(config, propName) &&
!RESERVED_PROPS.hasOwnProperty(propName)
) {
props[propName] = config[propName];
}
}
// Resolve default props
if (type && type.defaultProps) {
const defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if (key || ref) {
const displayName =
typeof type === 'function'
? type.displayName || type.name || 'Unknown'
: type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
return ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
}
}
| 27.707521 | 95 | 0.630665 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
'use strict';
export {useSyncExternalStore} from 'use-sync-external-store/src/useSyncExternalStoreShim';
| 22.923077 | 90 | 0.729032 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
const rule = require('../prod-error-codes');
const {RuleTester} = require('eslint');
const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 2017,
},
});
ruleTester.run('eslint-rules/prod-error-codes', rule, {
valid: [
'arbitraryFunction(a, b)',
'Error(`Expected ${foo} target to be an array; got ${bar}`)',
"Error('Expected ' + foo + ' target to be an array; got ' + bar)",
'Error(`Expected ${foo} target to ` + `be an array; got ${bar}`)',
],
invalid: [
{
code: "Error('Not in error map')",
errors: [
{
message:
'Error message does not have a corresponding production error ' +
'code. Add the following message to codes.json so it can be stripped from ' +
'the production builds:\n\n' +
'Not in error map',
},
],
},
{
code: "Error('Not in ' + 'error map')",
errors: [
{
message:
'Error message does not have a corresponding production error ' +
'code. Add the following message to codes.json so it can be stripped from ' +
'the production builds:\n\n' +
'Not in error map',
},
],
},
{
code: 'Error(`Not in ` + `error map`)',
errors: [
{
message:
'Error message does not have a corresponding production error ' +
'code. Add the following message to codes.json so it can be stripped from ' +
'the production builds:\n\n' +
'Not in error map',
},
],
},
{
code: "Error(`Not in ${'error'} map`)",
errors: [
{
message:
'Error message does not have a corresponding production error ' +
'code. Add the following message to codes.json so it can be stripped from ' +
'the production builds:\n\n' +
'Not in %s map',
},
],
},
],
});
| 27.192308 | 89 | 0.535032 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
let ReactDOMClient;
let Scheduler;
let act;
let waitForAll;
let waitFor;
let waitForMicrotasks;
let assertLog;
const setUntrackedInputValue = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
'value',
).set;
describe('ReactDOMFiberAsync', () => {
let container;
beforeEach(() => {
container = document.createElement('div');
React = require('react');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
act = require('internal-test-utils').act;
Scheduler = require('scheduler');
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
waitFor = InternalTestUtils.waitFor;
waitForMicrotasks = InternalTestUtils.waitForMicrotasks;
assertLog = InternalTestUtils.assertLog;
document.body.appendChild(container);
window.event = undefined;
});
afterEach(() => {
document.body.removeChild(container);
});
it('renders synchronously by default', () => {
const ops = [];
ReactDOM.render(<div>Hi</div>, container, () => {
ops.push(container.textContent);
});
ReactDOM.render(<div>Bye</div>, container, () => {
ops.push(container.textContent);
});
expect(ops).toEqual(['Hi', 'Bye']);
});
it('flushSync batches sync updates and flushes them at the end of the batch', () => {
const ops = [];
let instance;
class Component extends React.Component {
state = {text: ''};
push(val) {
this.setState(state => ({text: state.text + val}));
}
componentDidUpdate() {
ops.push(this.state.text);
}
render() {
instance = this;
return <span>{this.state.text}</span>;
}
}
ReactDOM.render(<Component />, container);
instance.push('A');
expect(ops).toEqual(['A']);
expect(container.textContent).toEqual('A');
ReactDOM.flushSync(() => {
instance.push('B');
instance.push('C');
// Not flushed yet
expect(container.textContent).toEqual('A');
expect(ops).toEqual(['A']);
});
expect(container.textContent).toEqual('ABC');
expect(ops).toEqual(['A', 'ABC']);
instance.push('D');
expect(container.textContent).toEqual('ABCD');
expect(ops).toEqual(['A', 'ABC', 'ABCD']);
});
it('flushSync flushes updates even if nested inside another flushSync', () => {
const ops = [];
let instance;
class Component extends React.Component {
state = {text: ''};
push(val) {
this.setState(state => ({text: state.text + val}));
}
componentDidUpdate() {
ops.push(this.state.text);
}
render() {
instance = this;
return <span>{this.state.text}</span>;
}
}
ReactDOM.render(<Component />, container);
instance.push('A');
expect(ops).toEqual(['A']);
expect(container.textContent).toEqual('A');
ReactDOM.flushSync(() => {
instance.push('B');
instance.push('C');
// Not flushed yet
expect(container.textContent).toEqual('A');
expect(ops).toEqual(['A']);
ReactDOM.flushSync(() => {
instance.push('D');
});
// The nested flushSync caused everything to flush.
expect(container.textContent).toEqual('ABCD');
expect(ops).toEqual(['A', 'ABCD']);
});
expect(container.textContent).toEqual('ABCD');
expect(ops).toEqual(['A', 'ABCD']);
});
it('flushSync logs an error if already performing work', () => {
class Component extends React.Component {
componentDidUpdate() {
ReactDOM.flushSync();
}
render() {
return null;
}
}
// Initial mount
ReactDOM.render(<Component />, container);
// Update
expect(() => ReactDOM.render(<Component />, container)).toErrorDev(
'flushSync was called from inside a lifecycle method',
);
});
describe('concurrent mode', () => {
it('does not perform deferred updates synchronously', async () => {
const inputRef = React.createRef();
const asyncValueRef = React.createRef();
const syncValueRef = React.createRef();
class Counter extends React.Component {
state = {asyncValue: '', syncValue: ''};
handleChange = e => {
const nextValue = e.target.value;
React.startTransition(() => {
this.setState({
asyncValue: nextValue,
});
// It should not be flushed yet.
expect(asyncValueRef.current.textContent).toBe('');
});
this.setState({
syncValue: nextValue,
});
};
render() {
return (
<div>
<input
ref={inputRef}
onChange={this.handleChange}
defaultValue=""
/>
<p ref={asyncValueRef}>{this.state.asyncValue}</p>
<p ref={syncValueRef}>{this.state.syncValue}</p>
</div>
);
}
}
const root = ReactDOMClient.createRoot(container);
await act(() => root.render(<Counter />));
expect(asyncValueRef.current.textContent).toBe('');
expect(syncValueRef.current.textContent).toBe('');
await act(() => {
setUntrackedInputValue.call(inputRef.current, 'hello');
inputRef.current.dispatchEvent(
new MouseEvent('input', {bubbles: true}),
);
// Should only flush non-deferred update.
expect(asyncValueRef.current.textContent).toBe('');
expect(syncValueRef.current.textContent).toBe('hello');
});
// Should flush both updates now.
expect(asyncValueRef.current.textContent).toBe('hello');
expect(syncValueRef.current.textContent).toBe('hello');
});
it('top-level updates are concurrent', async () => {
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<div>Hi</div>);
expect(container.textContent).toEqual('');
});
expect(container.textContent).toEqual('Hi');
await act(() => {
root.render(<div>Bye</div>);
expect(container.textContent).toEqual('Hi');
});
expect(container.textContent).toEqual('Bye');
});
it('deep updates (setState) are concurrent', async () => {
let instance;
class Component extends React.Component {
state = {step: 0};
render() {
instance = this;
return <div>{this.state.step}</div>;
}
}
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<Component />);
expect(container.textContent).toEqual('');
});
expect(container.textContent).toEqual('0');
await act(() => {
instance.setState({step: 1});
expect(container.textContent).toEqual('0');
});
expect(container.textContent).toEqual('1');
});
it('flushSync flushes updates before end of the tick', async () => {
let instance;
class Component extends React.Component {
state = {text: ''};
push(val) {
this.setState(state => ({text: state.text + val}));
}
componentDidUpdate() {
Scheduler.log(this.state.text);
}
render() {
instance = this;
return <span>{this.state.text}</span>;
}
}
const root = ReactDOMClient.createRoot(container);
await act(() => root.render(<Component />));
// Updates are async by default
instance.push('A');
assertLog([]);
expect(container.textContent).toEqual('');
ReactDOM.flushSync(() => {
instance.push('B');
instance.push('C');
// Not flushed yet
expect(container.textContent).toEqual('');
assertLog([]);
});
// Only the active updates have flushed
if (gate(flags => flags.enableUnifiedSyncLane)) {
expect(container.textContent).toEqual('ABC');
assertLog(['ABC']);
} else {
expect(container.textContent).toEqual('BC');
assertLog(['BC']);
}
await act(() => {
instance.push('D');
if (gate(flags => flags.enableUnifiedSyncLane)) {
expect(container.textContent).toEqual('ABC');
} else {
expect(container.textContent).toEqual('BC');
}
assertLog([]);
});
assertLog(['ABCD']);
expect(container.textContent).toEqual('ABCD');
});
it('ignores discrete events on a pending removed element', async () => {
const disableButtonRef = React.createRef();
const submitButtonRef = React.createRef();
function Form() {
const [active, setActive] = React.useState(true);
function disableForm() {
setActive(false);
}
return (
<div>
<button onClick={disableForm} ref={disableButtonRef}>
Disable
</button>
{active ? <button ref={submitButtonRef}>Submit</button> : null}
</div>
);
}
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<Form />);
});
const disableButton = disableButtonRef.current;
expect(disableButton.tagName).toBe('BUTTON');
const submitButton = submitButtonRef.current;
expect(submitButton.tagName).toBe('BUTTON');
// Dispatch a click event on the Disable-button.
const firstEvent = document.createEvent('Event');
firstEvent.initEvent('click', true, true);
disableButton.dispatchEvent(firstEvent);
// The click event is flushed synchronously, even in concurrent mode.
expect(submitButton.current).toBe(undefined);
});
it('ignores discrete events on a pending removed event listener', async () => {
const disableButtonRef = React.createRef();
const submitButtonRef = React.createRef();
let formSubmitted = false;
function Form() {
const [active, setActive] = React.useState(true);
function disableForm() {
setActive(false);
}
function submitForm() {
formSubmitted = true; // This should not get invoked
}
function disabledSubmitForm() {
// The form is disabled.
}
return (
<div>
<button onClick={disableForm} ref={disableButtonRef}>
Disable
</button>
<button
onClick={active ? submitForm : disabledSubmitForm}
ref={submitButtonRef}>
Submit
</button>
</div>
);
}
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<Form />);
});
const disableButton = disableButtonRef.current;
expect(disableButton.tagName).toBe('BUTTON');
// Dispatch a click event on the Disable-button.
const firstEvent = document.createEvent('Event');
firstEvent.initEvent('click', true, true);
await act(() => {
disableButton.dispatchEvent(firstEvent);
});
// There should now be a pending update to disable the form.
// This should not have flushed yet since it's in concurrent mode.
const submitButton = submitButtonRef.current;
expect(submitButton.tagName).toBe('BUTTON');
// In the meantime, we can dispatch a new client event on the submit button.
const secondEvent = document.createEvent('Event');
secondEvent.initEvent('click', true, true);
// This should force the pending update to flush which disables the submit button before the event is invoked.
await act(() => {
submitButton.dispatchEvent(secondEvent);
});
// Therefore the form should never have been submitted.
expect(formSubmitted).toBe(false);
});
it('uses the newest discrete events on a pending changed event listener', async () => {
const enableButtonRef = React.createRef();
const submitButtonRef = React.createRef();
let formSubmitted = false;
function Form() {
const [active, setActive] = React.useState(false);
function enableForm() {
setActive(true);
}
function submitForm() {
formSubmitted = true; // This should not get invoked
}
return (
<div>
<button onClick={enableForm} ref={enableButtonRef}>
Enable
</button>
<button onClick={active ? submitForm : null} ref={submitButtonRef}>
Submit
</button>
</div>
);
}
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<Form />);
});
const enableButton = enableButtonRef.current;
expect(enableButton.tagName).toBe('BUTTON');
// Dispatch a click event on the Enable-button.
const firstEvent = document.createEvent('Event');
firstEvent.initEvent('click', true, true);
await act(() => {
enableButton.dispatchEvent(firstEvent);
});
// There should now be a pending update to enable the form.
// This should not have flushed yet since it's in concurrent mode.
const submitButton = submitButtonRef.current;
expect(submitButton.tagName).toBe('BUTTON');
// In the meantime, we can dispatch a new client event on the submit button.
const secondEvent = document.createEvent('Event');
secondEvent.initEvent('click', true, true);
// This should force the pending update to flush which enables the submit button before the event is invoked.
await act(() => {
submitButton.dispatchEvent(secondEvent);
});
// Therefore the form should have been submitted.
expect(formSubmitted).toBe(true);
});
});
it('regression test: does not drop passive effects across roots (#17066)', async () => {
const {useState, useEffect} = React;
function App({label}) {
const [step, setStep] = useState(0);
useEffect(() => {
if (step < 3) {
setStep(step + 1);
}
}, [step]);
// The component should keep re-rendering itself until `step` is 3.
return step === 3 ? 'Finished' : 'Unresolved';
}
const containerA = document.createElement('div');
const containerB = document.createElement('div');
const containerC = document.createElement('div');
await act(() => {
ReactDOM.render(<App label="A" />, containerA);
ReactDOM.render(<App label="B" />, containerB);
ReactDOM.render(<App label="C" />, containerC);
});
expect(containerA.textContent).toEqual('Finished');
expect(containerB.textContent).toEqual('Finished');
expect(containerC.textContent).toEqual('Finished');
});
it('updates flush without yielding in the next event', async () => {
const root = ReactDOMClient.createRoot(container);
function Text(props) {
Scheduler.log(props.text);
return props.text;
}
root.render(
<>
<Text text="A" />
<Text text="B" />
<Text text="C" />
</>,
);
// Nothing should have rendered yet
expect(container.textContent).toEqual('');
// Everything should render immediately in the next event
await waitForAll(['A', 'B', 'C']);
expect(container.textContent).toEqual('ABC');
});
it('unmounted roots should never clear newer root content from a container', async () => {
const ref = React.createRef();
function OldApp() {
const [value, setValue] = React.useState('old');
function hideOnClick() {
// Schedule a discrete update.
setValue('update');
// Synchronously unmount this root.
ReactDOM.flushSync(() => oldRoot.unmount());
}
return (
<button onClick={hideOnClick} ref={ref}>
{value}
</button>
);
}
function NewApp() {
return <button ref={ref}>new</button>;
}
const oldRoot = ReactDOMClient.createRoot(container);
await act(() => {
oldRoot.render(<OldApp />);
});
// Invoke discrete event.
ref.current.click();
// The root should now be unmounted.
expect(container.textContent).toBe('');
// We can now render a new one.
const newRoot = ReactDOMClient.createRoot(container);
ReactDOM.flushSync(() => {
newRoot.render(<NewApp />);
});
ref.current.click();
expect(container.textContent).toBe('new');
});
it('should synchronously render the transition lane scheduled in a popState', async () => {
function App() {
const [syncState, setSyncState] = React.useState(false);
const [hasNavigated, setHasNavigated] = React.useState(false);
function onPopstate() {
Scheduler.log(`popState`);
React.startTransition(() => {
setHasNavigated(true);
});
setSyncState(true);
}
React.useEffect(() => {
window.addEventListener('popstate', onPopstate);
return () => {
window.removeEventListener('popstate', onPopstate);
};
}, []);
Scheduler.log(`render:${hasNavigated}/${syncState}`);
return null;
}
const root = ReactDOMClient.createRoot(container);
await act(async () => {
root.render(<App />);
});
assertLog(['render:false/false']);
await act(async () => {
const popStateEvent = new Event('popstate');
// Jest is not emulating window.event correctly in the microtask
window.event = popStateEvent;
window.dispatchEvent(popStateEvent);
queueMicrotask(() => {
window.event = undefined;
});
});
assertLog(['popState', 'render:true/true']);
await act(() => {
root.unmount();
});
});
it('Should not flush transition lanes if there is no transition scheduled in popState', async () => {
let setHasNavigated;
function App() {
const [syncState, setSyncState] = React.useState(false);
const [hasNavigated, _setHasNavigated] = React.useState(false);
setHasNavigated = _setHasNavigated;
function onPopstate() {
setSyncState(true);
}
React.useEffect(() => {
window.addEventListener('popstate', onPopstate);
return () => {
window.removeEventListener('popstate', onPopstate);
};
}, []);
Scheduler.log(`render:${hasNavigated}/${syncState}`);
return null;
}
const root = ReactDOMClient.createRoot(container);
await act(async () => {
root.render(<App />);
});
assertLog(['render:false/false']);
React.startTransition(() => {
setHasNavigated(true);
});
await act(async () => {
const popStateEvent = new Event('popstate');
// Jest is not emulating window.event correctly in the microtask
window.event = popStateEvent;
window.dispatchEvent(popStateEvent);
queueMicrotask(() => {
window.event = undefined;
});
});
assertLog(['render:false/true', 'render:true/true']);
await act(() => {
root.unmount();
});
});
it('transition lane in popState should be allowed to suspend', async () => {
let resolvePromise;
const promise = new Promise(res => {
resolvePromise = res;
});
function Text({text}) {
Scheduler.log(text);
return text;
}
function App() {
const [pathname, setPathname] = React.useState('/path/a');
if (pathname !== '/path/a') {
try {
React.use(promise);
} catch (e) {
Scheduler.log(`Suspend! [${pathname}]`);
throw e;
}
}
React.useEffect(() => {
function onPopstate() {
React.startTransition(() => {
setPathname('/path/b');
});
}
window.addEventListener('popstate', onPopstate);
return () => window.removeEventListener('popstate', onPopstate);
}, []);
return (
<>
<Text text="Before" />
<div>
<Text text={pathname} />
</div>
<Text text="After" />
</>
);
}
const root = ReactDOMClient.createRoot(container);
await act(async () => {
root.render(<App />);
});
assertLog(['Before', '/path/a', 'After']);
const div = container.getElementsByTagName('div')[0];
expect(div.textContent).toBe('/path/a');
// Simulate a popstate event
await act(async () => {
const popStateEvent = new Event('popstate');
// Simulate a popstate event
window.event = popStateEvent;
window.dispatchEvent(popStateEvent);
await waitForMicrotasks();
window.event = undefined;
// The transition lane should have been attempted synchronously (in
// a microtask)
assertLog(['Suspend! [/path/b]']);
// Because it suspended, it remains on the current path
expect(div.textContent).toBe('/path/a');
});
assertLog(['Suspend! [/path/b]']);
await act(async () => {
resolvePromise();
// Since the transition previously suspended, there's no need for this
// transition to be rendered synchronously on susbequent attempts; if we
// fail to commit synchronously the first time, the scroll restoration
// state won't be restored anyway.
//
// Yield in between each child to prove that it's concurrent.
await waitForMicrotasks();
assertLog([]);
await waitFor(['Before']);
await waitFor(['/path/b']);
await waitFor(['After']);
});
assertLog([]);
expect(div.textContent).toBe('/path/b');
await act(() => {
root.unmount();
});
});
it('regression: infinite deferral loop caused by unstable useDeferredValue input', async () => {
function Text({text}) {
Scheduler.log(text);
return text;
}
let i = 0;
function App() {
const [pathname, setPathname] = React.useState('/path/a');
// This is an unstable input, so it will always cause a deferred render.
const {value: deferredPathname} = React.useDeferredValue({
value: pathname,
});
if (i++ > 100) {
throw new Error('Infinite loop detected');
}
React.useEffect(() => {
function onPopstate() {
React.startTransition(() => {
setPathname('/path/b');
});
}
window.addEventListener('popstate', onPopstate);
return () => window.removeEventListener('popstate', onPopstate);
}, []);
return <Text text={deferredPathname} />;
}
const root = ReactDOMClient.createRoot(container);
await act(() => {
root.render(<App />);
});
assertLog(['/path/a']);
expect(container.textContent).toBe('/path/a');
// Simulate a popstate event
await act(async () => {
const popStateEvent = new Event('popstate');
// Simulate a popstate event
window.event = popStateEvent;
window.dispatchEvent(popStateEvent);
await waitForMicrotasks();
window.event = undefined;
// The transition lane is attempted synchronously (in a microtask).
// Because the input to useDeferredValue is referentially unstable, it
// will spawn a deferred task at transition priority. However, even
// though it was spawned during a transition event, the spawned task
// not also be upgraded to sync.
assertLog(['/path/a']);
});
assertLog(['/path/b']);
expect(container.textContent).toBe('/path/b');
await act(() => {
root.unmount();
});
});
});
| 28.428747 | 116 | 0.584328 |
null | 'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/use-subscription.production.min.js');
} else {
module.exports = require('./cjs/use-subscription.development.js');
}
| 25.625 | 71 | 0.688679 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export * from './src/ReactFlightDOMClientNode';
| 22 | 66 | 0.702381 |
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 './ReactDOMFizzServerNode.js';
export {prerenderToNodeStream} from './ReactDOMFizzStaticNode.js';
| 25.416667 | 66 | 0.724684 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useTheme;
exports.ThemeContext = void 0;
var _react = require("react");
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright');
exports.ThemeContext = ThemeContext;
function useTheme() {
const theme = (0, _react.useContext)(ThemeContext);
(0, _react.useDebugValue)(theme);
return theme;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZW1lIiwidGhlbWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBU0E7O0FBVEE7Ozs7Ozs7O0FBV08sTUFBTUEsWUFBWSxnQkFBRywwQkFBYyxRQUFkLENBQXJCOzs7QUFFUSxTQUFTQyxRQUFULEdBQW9CO0FBQ2pDLFFBQU1DLEtBQUssR0FBRyx1QkFBV0YsWUFBWCxDQUFkO0FBQ0EsNEJBQWNFLEtBQWQ7QUFDQSxTQUFPQSxLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0LCB1c2VEZWJ1Z1ZhbHVlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBjb25zdCBUaGVtZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0KCdicmlnaHQnKTtcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gdXNlVGhlbWUoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlQ29udGV4dChUaGVtZUNvbnRleHQpO1xuICB1c2VEZWJ1Z1ZhbHVlKHRoZW1lKTtcbiAgcmV0dXJuIHRoZW1lO1xufVxuIl19 | 60.703704 | 1,056 | 0.87988 |
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
*/
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
* @param {function} cb Callback invoked with each element or a collection.
* @param {?} [scope] Scope used as `this` in a callback.
*/
function forEachAccumulated<T>(
arr: ?(Array<T> | T),
cb: (elem: T) => void,
scope: ?any,
) {
if (Array.isArray(arr)) {
// $FlowFixMe[incompatible-call] if `T` is an array, `cb` cannot be called
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
}
export default forEachAccumulated;
| 29.212121 | 78 | 0.676707 |
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
*/
// Module provided by RN:
import {UIManager} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
const ReactNativeGlobalResponderHandler = {
onChange: function (from: any, to: any, blockNativeResponder: boolean) {
if (to !== null) {
const tag = to.stateNode._nativeTag;
UIManager.setJSResponder(tag, blockNativeResponder);
} else {
UIManager.clearJSResponder();
}
},
};
export default ReactNativeGlobalResponderHandler;
| 26.24 | 90 | 0.714706 |
PenetrationTestingScripts | #!/usr/bin/env node
'use strict';
const archiver = require('archiver');
const {execSync} = require('child_process');
const {readFileSync, writeFileSync, createWriteStream} = require('fs');
const {copy, ensureDir, move, remove, pathExistsSync} = require('fs-extra');
const {join, resolve} = require('path');
const {getGitCommit} = require('./utils');
// These files are copied along with Webpack-bundled files
// to produce the final web extension
const STATIC_FILES = ['icons', 'popups', 'main.html', 'panel.html'];
/**
* Ensures that a local build of the dependencies exist either by downloading
* or running a local build via one of the `react-build-fordevtools*` scripts.
*/
const ensureLocalBuild = async () => {
const buildDir = resolve(__dirname, '..', '..', 'build');
const nodeModulesDir = join(buildDir, 'node_modules');
// TODO: remove this check whenever the CI pipeline is complete.
// See build-all-release-channels.js
const currentBuildDir = resolve(
__dirname,
'..',
'..',
'build',
'oss-experimental',
);
if (pathExistsSync(buildDir)) {
return; // all good.
}
if (pathExistsSync(currentBuildDir)) {
await ensureDir(buildDir);
await copy(currentBuildDir, nodeModulesDir);
return; // all good.
}
throw Error(
'Could not find build artifacts in repo root. See README for prerequisites.',
);
};
const preProcess = async (destinationPath, tempPath) => {
await remove(destinationPath); // Clean up from previously completed builds
await remove(tempPath); // Clean up from any previously failed builds
await ensureDir(tempPath); // Create temp dir for this new build
};
const build = async (tempPath, manifestPath, envExtension = {}) => {
const binPath = join(tempPath, 'bin');
const zipPath = join(tempPath, 'zip');
const mergedEnv = {...process.env, ...envExtension};
const webpackPath = join(__dirname, 'node_modules', '.bin', 'webpack');
execSync(
`${webpackPath} --config webpack.config.js --output-path ${binPath}`,
{
cwd: __dirname,
env: mergedEnv,
stdio: 'inherit',
},
);
execSync(
`${webpackPath} --config webpack.backend.js --output-path ${binPath}`,
{
cwd: __dirname,
env: mergedEnv,
stdio: 'inherit',
},
);
// Make temp dir
await ensureDir(zipPath);
const copiedManifestPath = join(zipPath, 'manifest.json');
// Copy unbuilt source files to zip dir to be packaged:
await copy(binPath, join(zipPath, 'build'));
await copy(manifestPath, copiedManifestPath);
await Promise.all(
STATIC_FILES.map(file => copy(join(__dirname, file), join(zipPath, file))),
);
const commit = getGitCommit();
const dateString = new Date().toLocaleDateString();
const manifest = JSON.parse(readFileSync(copiedManifestPath).toString());
const versionDateString = `${manifest.version} (${dateString})`;
if (manifest.version_name) {
manifest.version_name = versionDateString;
}
manifest.description += `\n\nCreated from revision ${commit} on ${dateString}.`;
if (process.env.NODE_ENV === 'development') {
// When building the local development version of the
// extension we want to be able to have a stable extension ID
// for the local build (in order to be able to reliably detect
// duplicate installations of DevTools).
// By specifying a key in the built manifest.json file,
// we can make it so the generated extension ID is stable.
// For more details see the docs here: https://developer.chrome.com/docs/extensions/mv2/manifest/key/
manifest.key = 'reactdevtoolslocalbuilduniquekey';
}
writeFileSync(copiedManifestPath, JSON.stringify(manifest, null, 2));
// Pack the extension
const archive = archiver('zip', {zlib: {level: 9}});
const zipStream = createWriteStream(join(tempPath, 'ReactDevTools.zip'));
await new Promise((resolvePromise, rejectPromise) => {
archive
.directory(zipPath, false)
.on('error', err => rejectPromise(err))
.pipe(zipStream);
archive.finalize();
zipStream.on('close', () => resolvePromise());
});
};
const postProcess = async (tempPath, destinationPath) => {
const unpackedSourcePath = join(tempPath, 'zip');
const packedSourcePath = join(tempPath, 'ReactDevTools.zip');
const packedDestPath = join(destinationPath, 'ReactDevTools.zip');
const unpackedDestPath = join(destinationPath, 'unpacked');
await move(unpackedSourcePath, unpackedDestPath); // Copy built files to destination
await move(packedSourcePath, packedDestPath); // Copy built files to destination
await remove(tempPath); // Clean up temp directory and files
};
const SUPPORTED_BUILDS = ['chrome', 'firefox', 'edge'];
const main = async buildId => {
if (!SUPPORTED_BUILDS.includes(buildId)) {
throw new Error(
`Unexpected build id - "${buildId}". Use one of ${JSON.stringify(
SUPPORTED_BUILDS,
)}.`,
);
}
const root = join(__dirname, buildId);
const manifestPath = join(root, 'manifest.json');
const destinationPath = join(root, 'build');
const envExtension = {
IS_CHROME: buildId === 'chrome',
IS_FIREFOX: buildId === 'firefox',
IS_EDGE: buildId === 'edge',
};
try {
const tempPath = join(__dirname, 'build', buildId);
await ensureLocalBuild();
await preProcess(destinationPath, tempPath);
await build(tempPath, manifestPath, envExtension);
const builtUnpackedPath = join(destinationPath, 'unpacked');
await postProcess(tempPath, destinationPath);
return builtUnpackedPath;
} catch (error) {
console.error(error);
process.exit(1);
}
return null;
};
module.exports = main;
| 31.238636 | 105 | 0.679358 |
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 {
importFromChromeTimeline,
Flamechart as SpeedscopeFlamechart,
} from '@elg/speedscope';
import type {TimelineEvent} from '@elg/speedscope';
import type {
ErrorStackFrame,
BatchUID,
Flamechart,
Milliseconds,
NativeEvent,
NetworkMeasure,
Phase,
ReactLane,
ReactComponentMeasure,
ReactComponentMeasureType,
ReactMeasure,
ReactMeasureType,
TimelineData,
SchedulingEvent,
SuspenseEvent,
} from '../types';
import {
REACT_TOTAL_NUM_LANES,
SCHEDULING_PROFILER_VERSION,
SNAPSHOT_MAX_HEIGHT,
} from '../constants';
import InvalidProfileError from './InvalidProfileError';
import {getBatchRange} from '../utils/getBatchRange';
import ErrorStackParser from 'error-stack-parser';
type MeasureStackElement = {
type: ReactMeasureType,
depth: number,
measure: ReactMeasure,
startTime: Milliseconds,
stopTime?: Milliseconds,
};
type ProcessorState = {
asyncProcessingPromises: Promise<any>[],
batchUID: BatchUID,
currentReactComponentMeasure: ReactComponentMeasure | null,
internalModuleCurrentStackFrame: ErrorStackFrame | null,
internalModuleStackStringSet: Set<string>,
measureStack: MeasureStackElement[],
nativeEventStack: NativeEvent[],
nextRenderShouldGenerateNewBatchID: boolean,
potentialLongEvents: Array<[NativeEvent, BatchUID]>,
potentialLongNestedUpdate: SchedulingEvent | null,
potentialLongNestedUpdates: Array<[SchedulingEvent, BatchUID]>,
potentialSuspenseEventsOutsideOfTransition: Array<
[SuspenseEvent, ReactLane[]],
>,
requestIdToNetworkMeasureMap: Map<string, NetworkMeasure>,
uidCounter: BatchUID,
unresolvedSuspenseEvents: Map<string, SuspenseEvent>,
};
const NATIVE_EVENT_DURATION_THRESHOLD = 20;
const NESTED_UPDATE_DURATION_THRESHOLD = 20;
const WARNING_STRINGS = {
LONG_EVENT_HANDLER:
'An event handler scheduled a big update with React. Consider using the Transition API to defer some of this work.',
NESTED_UPDATE:
'A big nested update was scheduled during layout. ' +
'Nested updates require React to re-render synchronously before the browser can paint. ' +
'Consider delaying this update by moving it to a passive effect (useEffect).',
SUSPEND_DURING_UPDATE:
'A component suspended during an update which caused a fallback to be shown. ' +
"Consider using the Transition API to avoid hiding components after they've been mounted.",
};
// Exported for tests
export function getLanesFromTransportDecimalBitmask(
laneBitmaskString: string,
): ReactLane[] {
const laneBitmask = parseInt(laneBitmaskString, 10);
// As negative numbers are stored in two's complement format, our bitmask
// checks will be thrown off by them.
if (laneBitmask < 0) {
return [];
}
const lanes = [];
let powersOfTwo = 0;
while (powersOfTwo <= REACT_TOTAL_NUM_LANES) {
if ((1 << powersOfTwo) & laneBitmask) {
lanes.push(powersOfTwo);
}
powersOfTwo++;
}
return lanes;
}
function updateLaneToLabelMap(
profilerData: TimelineData,
laneLabelTuplesString: string,
): void {
// These marks appear multiple times in the data;
// We only need to extact them once.
if (profilerData.laneToLabelMap.size === 0) {
const laneLabelTuples = laneLabelTuplesString.split(',');
for (let laneIndex = 0; laneIndex < laneLabelTuples.length; laneIndex++) {
// The numeric lane value (e.g. 64) isn't important.
// The profiler parses and stores the lane's position within the bitmap,
// (e.g. lane 1 is index 0, lane 16 is index 4).
profilerData.laneToLabelMap.set(laneIndex, laneLabelTuples[laneIndex]);
}
}
}
let profilerVersion = null;
function getLastType(stack: $PropertyType<ProcessorState, 'measureStack'>) {
if (stack.length > 0) {
const {type} = stack[stack.length - 1];
return type;
}
return null;
}
function getDepth(stack: $PropertyType<ProcessorState, 'measureStack'>) {
if (stack.length > 0) {
const {depth, type} = stack[stack.length - 1];
return type === 'render-idle' ? depth : depth + 1;
}
return 0;
}
function markWorkStarted(
type: ReactMeasureType,
startTime: Milliseconds,
lanes: ReactLane[],
currentProfilerData: TimelineData,
state: ProcessorState,
) {
const {batchUID, measureStack} = state;
const depth = getDepth(measureStack);
const measure: ReactMeasure = {
type,
batchUID,
depth,
lanes,
timestamp: startTime,
duration: 0,
};
state.measureStack.push({depth, measure, startTime, type});
// This array is pre-initialized when the batchUID is generated.
const measures = currentProfilerData.batchUIDToMeasuresMap.get(batchUID);
if (measures != null) {
measures.push(measure);
} else {
currentProfilerData.batchUIDToMeasuresMap.set(state.batchUID, [measure]);
}
// This array is pre-initialized before processing starts.
lanes.forEach(lane => {
((currentProfilerData.laneToReactMeasureMap.get(
lane,
): any): ReactMeasure[]).push(measure);
});
}
function markWorkCompleted(
type: ReactMeasureType,
stopTime: Milliseconds,
currentProfilerData: TimelineData,
stack: $PropertyType<ProcessorState, 'measureStack'>,
) {
if (stack.length === 0) {
console.error(
'Unexpected type "%s" completed at %sms while stack is empty.',
type,
stopTime,
);
// Ignore work "completion" user timing mark that doesn't complete anything
return;
}
const last = stack[stack.length - 1];
if (last.type !== type) {
console.error(
'Unexpected type "%s" completed at %sms before "%s" completed.',
type,
stopTime,
last.type,
);
}
const {measure, startTime} = stack.pop();
if (!measure) {
console.error('Could not find matching measure for type "%s".', type);
}
// $FlowFixMe[cannot-write] This property should not be writable outside of this function.
measure.duration = stopTime - startTime;
}
function throwIfIncomplete(
type: ReactMeasureType,
stack: $PropertyType<ProcessorState, 'measureStack'>,
) {
const lastIndex = stack.length - 1;
if (lastIndex >= 0) {
const last = stack[lastIndex];
if (last.stopTime === undefined && last.type === type) {
throw new InvalidProfileError(
`Unexpected type "${type}" started before "${last.type}" completed.`,
);
}
}
}
function processEventDispatch(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const data = event.args.data;
const type = data.type;
if (type.startsWith('react-')) {
const stackTrace = data.stackTrace;
if (stackTrace) {
const topFrame = stackTrace[stackTrace.length - 1];
if (topFrame.url.includes('/react-dom.')) {
// Filter out fake React events dispatched by invokeGuardedCallbackDev.
return;
}
}
}
// Reduce noise from events like DOMActivate, load/unload, etc. which are usually not relevant
if (
type === 'blur' ||
type === 'click' ||
type === 'input' ||
type.startsWith('focus') ||
type.startsWith('key') ||
type.startsWith('mouse') ||
type.startsWith('pointer')
) {
const duration = event.dur / 1000;
let depth = 0;
while (state.nativeEventStack.length > 0) {
const prevNativeEvent =
state.nativeEventStack[state.nativeEventStack.length - 1];
const prevStopTime = prevNativeEvent.timestamp + prevNativeEvent.duration;
if (timestamp < prevStopTime) {
depth = prevNativeEvent.depth + 1;
break;
} else {
state.nativeEventStack.pop();
}
}
const nativeEvent = {
depth,
duration,
timestamp,
type,
warning: null,
};
profilerData.nativeEvents.push(nativeEvent);
// Keep track of curent event in case future ones overlap.
// We separate them into different vertical lanes in this case.
state.nativeEventStack.push(nativeEvent);
}
}
function processResourceFinish(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const requestId = event.args.data.requestId;
const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId);
if (networkMeasure != null) {
networkMeasure.finishTimestamp = timestamp;
if (networkMeasure.firstReceivedDataTimestamp === 0) {
networkMeasure.firstReceivedDataTimestamp = timestamp;
}
if (networkMeasure.lastReceivedDataTimestamp === 0) {
networkMeasure.lastReceivedDataTimestamp = timestamp;
}
// Clean up now that the resource is done.
state.requestIdToNetworkMeasureMap.delete(event.args.data.requestId);
}
}
function processResourceReceivedData(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const requestId = event.args.data.requestId;
const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId);
if (networkMeasure != null) {
if (networkMeasure.firstReceivedDataTimestamp === 0) {
networkMeasure.firstReceivedDataTimestamp = timestamp;
}
networkMeasure.lastReceivedDataTimestamp = timestamp;
networkMeasure.finishTimestamp = timestamp;
}
}
function processResourceReceiveResponse(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const requestId = event.args.data.requestId;
const networkMeasure = state.requestIdToNetworkMeasureMap.get(requestId);
if (networkMeasure != null) {
networkMeasure.receiveResponseTimestamp = timestamp;
}
}
function processScreenshot(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const encodedSnapshot = event.args.snapshot; // Base 64 encoded
const snapshot = {
height: 0,
image: null,
imageSource: `data:image/png;base64,${encodedSnapshot}`,
timestamp,
width: 0,
};
// Delay processing until we've extracted snapshot dimensions.
let resolveFn = ((null: any): Function);
state.asyncProcessingPromises.push(
new Promise(resolve => {
resolveFn = resolve;
}),
);
// Parse the Base64 image data to determine native size.
// This will be used later to scale for display within the thumbnail strip.
fetch(snapshot.imageSource)
.then(response => response.blob())
.then(blob => {
// $FlowFixMe[cannot-resolve-name] createImageBitmap
createImageBitmap(blob).then(bitmap => {
snapshot.height = bitmap.height;
snapshot.width = bitmap.width;
resolveFn();
});
});
profilerData.snapshots.push(snapshot);
}
function processResourceSendRequest(
event: TimelineEvent,
timestamp: Milliseconds,
profilerData: TimelineData,
state: ProcessorState,
) {
const data = event.args.data;
const requestId = data.requestId;
const availableDepths = new Array<boolean>(
state.requestIdToNetworkMeasureMap.size + 1,
).fill(true);
state.requestIdToNetworkMeasureMap.forEach(({depth}) => {
availableDepths[depth] = false;
});
let depth = 0;
for (let i = 0; i < availableDepths.length; i++) {
if (availableDepths[i]) {
depth = i;
break;
}
}
const networkMeasure: NetworkMeasure = {
depth,
finishTimestamp: 0,
firstReceivedDataTimestamp: 0,
lastReceivedDataTimestamp: 0,
requestId,
requestMethod: data.requestMethod,
priority: data.priority,
sendRequestTimestamp: timestamp,
receiveResponseTimestamp: 0,
url: data.url,
};
state.requestIdToNetworkMeasureMap.set(requestId, networkMeasure);
profilerData.networkMeasures.push(networkMeasure);
networkMeasure.sendRequestTimestamp = timestamp;
}
function processTimelineEvent(
event: TimelineEvent,
/** Finalized profiler data up to `event`. May be mutated. */
currentProfilerData: TimelineData,
/** Intermediate processor state. May be mutated. */
state: ProcessorState,
) {
const {cat, name, ts, ph} = event;
const startTime = (ts - currentProfilerData.startTime) / 1000;
switch (cat) {
case 'disabled-by-default-devtools.screenshot':
processScreenshot(event, startTime, currentProfilerData, state);
break;
case 'devtools.timeline':
switch (name) {
case 'EventDispatch':
processEventDispatch(event, startTime, currentProfilerData, state);
break;
case 'ResourceFinish':
processResourceFinish(event, startTime, currentProfilerData, state);
break;
case 'ResourceReceivedData':
processResourceReceivedData(
event,
startTime,
currentProfilerData,
state,
);
break;
case 'ResourceReceiveResponse':
processResourceReceiveResponse(
event,
startTime,
currentProfilerData,
state,
);
break;
case 'ResourceSendRequest':
processResourceSendRequest(
event,
startTime,
currentProfilerData,
state,
);
break;
}
break;
case 'blink.user_timing':
if (name.startsWith('--react-version-')) {
const [reactVersion] = name.slice(16).split('-');
currentProfilerData.reactVersion = reactVersion;
} else if (name.startsWith('--profiler-version-')) {
const [versionString] = name.slice(19).split('-');
profilerVersion = parseInt(versionString, 10);
if (profilerVersion !== SCHEDULING_PROFILER_VERSION) {
throw new InvalidProfileError(
`This version of profiling data (${versionString}) is not supported by the current profiler.`,
);
}
} else if (name.startsWith('--react-lane-labels-')) {
const [laneLabelTuplesString] = name.slice(20).split('-');
updateLaneToLabelMap(currentProfilerData, laneLabelTuplesString);
} else if (name.startsWith('--component-')) {
processReactComponentMeasure(
name,
startTime,
currentProfilerData,
state,
);
} else if (name.startsWith('--schedule-render-')) {
const [laneBitmaskString] = name.slice(18).split('-');
currentProfilerData.schedulingEvents.push({
type: 'schedule-render',
lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString),
timestamp: startTime,
warning: null,
});
} else if (name.startsWith('--schedule-forced-update-')) {
const [laneBitmaskString, componentName] = name.slice(25).split('-');
const forceUpdateEvent = {
type: 'schedule-force-update',
lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString),
componentName,
timestamp: startTime,
warning: null,
};
// If this is a nested update, make a note of it.
// Once we're done processing events, we'll check to see if it was a long update and warn about it.
if (state.measureStack.find(({type}) => type === 'commit')) {
state.potentialLongNestedUpdate = forceUpdateEvent;
}
currentProfilerData.schedulingEvents.push(forceUpdateEvent);
} else if (name.startsWith('--schedule-state-update-')) {
const [laneBitmaskString, componentName] = name.slice(24).split('-');
const stateUpdateEvent = {
type: 'schedule-state-update',
lanes: getLanesFromTransportDecimalBitmask(laneBitmaskString),
componentName,
timestamp: startTime,
warning: null,
};
// If this is a nested update, make a note of it.
// Once we're done processing events, we'll check to see if it was a long update and warn about it.
if (state.measureStack.find(({type}) => type === 'commit')) {
state.potentialLongNestedUpdate = stateUpdateEvent;
}
currentProfilerData.schedulingEvents.push(stateUpdateEvent);
} else if (name.startsWith('--error-')) {
const [componentName, phase, message] = name.slice(8).split('-');
currentProfilerData.thrownErrors.push({
componentName,
message,
phase: ((phase: any): Phase),
timestamp: startTime,
type: 'thrown-error',
});
} else if (name.startsWith('--suspense-suspend-')) {
const [id, componentName, phase, laneBitmaskString, promiseName] = name
.slice(19)
.split('-');
const lanes = getLanesFromTransportDecimalBitmask(laneBitmaskString);
const availableDepths = new Array<boolean>(
state.unresolvedSuspenseEvents.size + 1,
).fill(true);
state.unresolvedSuspenseEvents.forEach(({depth}) => {
availableDepths[depth] = false;
});
let depth = 0;
for (let i = 0; i < availableDepths.length; i++) {
if (availableDepths[i]) {
depth = i;
break;
}
}
// TODO (timeline) Maybe we should calculate depth in post,
// so unresolved Suspense requests don't take up space.
// We can't know if they'll be resolved or not at this point.
// We'll just give them a default (fake) duration width.
const suspenseEvent = {
componentName,
depth,
duration: null,
id,
phase: ((phase: any): Phase),
promiseName: promiseName || null,
resolution: 'unresolved',
timestamp: startTime,
type: 'suspense',
warning: null,
};
if (phase === 'update') {
// If a component suspended during an update, we should verify that it was during a transition.
// We need the lane metadata to verify this though.
// Since that data is only logged during commit, we may not have it yet.
// Store these events for post-processing then.
state.potentialSuspenseEventsOutsideOfTransition.push([
suspenseEvent,
lanes,
]);
}
currentProfilerData.suspenseEvents.push(suspenseEvent);
state.unresolvedSuspenseEvents.set(id, suspenseEvent);
} else if (name.startsWith('--suspense-resolved-')) {
const [id] = name.slice(20).split('-');
const suspenseEvent = state.unresolvedSuspenseEvents.get(id);
if (suspenseEvent != null) {
state.unresolvedSuspenseEvents.delete(id);
suspenseEvent.duration = startTime - suspenseEvent.timestamp;
suspenseEvent.resolution = 'resolved';
}
} else if (name.startsWith('--suspense-rejected-')) {
const [id] = name.slice(20).split('-');
const suspenseEvent = state.unresolvedSuspenseEvents.get(id);
if (suspenseEvent != null) {
state.unresolvedSuspenseEvents.delete(id);
suspenseEvent.duration = startTime - suspenseEvent.timestamp;
suspenseEvent.resolution = 'rejected';
}
} else if (name.startsWith('--render-start-')) {
if (state.nextRenderShouldGenerateNewBatchID) {
state.nextRenderShouldGenerateNewBatchID = false;
state.batchUID = ((state.uidCounter++: any): BatchUID);
}
// If this render is the result of a nested update, make a note of it.
// Once we're done processing events, we'll check to see if it was a long update and warn about it.
if (state.potentialLongNestedUpdate !== null) {
state.potentialLongNestedUpdates.push([
state.potentialLongNestedUpdate,
state.batchUID,
]);
state.potentialLongNestedUpdate = null;
}
const [laneBitmaskString] = name.slice(15).split('-');
throwIfIncomplete('render', state.measureStack);
if (getLastType(state.measureStack) !== 'render-idle') {
markWorkStarted(
'render-idle',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
}
markWorkStarted(
'render',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
for (let i = 0; i < state.nativeEventStack.length; i++) {
const nativeEvent = state.nativeEventStack[i];
const stopTime = nativeEvent.timestamp + nativeEvent.duration;
// If React work was scheduled during an event handler, and the event had a long duration,
// it might be because the React render was long and stretched the event.
// It might also be that the React work was short and that something else stretched the event.
// Make a note of this event for now and we'll examine the batch of React render work later.
// (We can't know until we're done processing the React update anyway.)
if (stopTime > startTime) {
state.potentialLongEvents.push([nativeEvent, state.batchUID]);
}
}
} else if (
name.startsWith('--render-stop') ||
name.startsWith('--render-yield')
) {
markWorkCompleted(
'render',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--commit-start-')) {
state.nextRenderShouldGenerateNewBatchID = true;
const [laneBitmaskString] = name.slice(15).split('-');
markWorkStarted(
'commit',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
} else if (name.startsWith('--commit-stop')) {
markWorkCompleted(
'commit',
startTime,
currentProfilerData,
state.measureStack,
);
markWorkCompleted(
'render-idle',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--layout-effects-start-')) {
const [laneBitmaskString] = name.slice(23).split('-');
markWorkStarted(
'layout-effects',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
} else if (name.startsWith('--layout-effects-stop')) {
markWorkCompleted(
'layout-effects',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--passive-effects-start-')) {
const [laneBitmaskString] = name.slice(24).split('-');
markWorkStarted(
'passive-effects',
startTime,
getLanesFromTransportDecimalBitmask(laneBitmaskString),
currentProfilerData,
state,
);
} else if (name.startsWith('--passive-effects-stop')) {
markWorkCompleted(
'passive-effects',
startTime,
currentProfilerData,
state.measureStack,
);
} else if (name.startsWith('--react-internal-module-start-')) {
const stackFrameStart = name.slice(30);
if (!state.internalModuleStackStringSet.has(stackFrameStart)) {
state.internalModuleStackStringSet.add(stackFrameStart);
const parsedStackFrameStart = parseStackFrame(stackFrameStart);
state.internalModuleCurrentStackFrame = parsedStackFrameStart;
}
} else if (name.startsWith('--react-internal-module-stop-')) {
const stackFrameStop = name.slice(29);
if (!state.internalModuleStackStringSet.has(stackFrameStop)) {
state.internalModuleStackStringSet.add(stackFrameStop);
const parsedStackFrameStop = parseStackFrame(stackFrameStop);
if (
parsedStackFrameStop !== null &&
state.internalModuleCurrentStackFrame !== null
) {
const parsedStackFrameStart = state.internalModuleCurrentStackFrame;
state.internalModuleCurrentStackFrame = null;
const range = [parsedStackFrameStart, parsedStackFrameStop];
const ranges = currentProfilerData.internalModuleSourceToRanges.get(
parsedStackFrameStart.fileName,
);
if (ranges == null) {
currentProfilerData.internalModuleSourceToRanges.set(
parsedStackFrameStart.fileName,
[range],
);
} else {
ranges.push(range);
}
}
}
} else if (ph === 'R' || ph === 'n') {
// User Timing mark
currentProfilerData.otherUserTimingMarks.push({
name,
timestamp: startTime,
});
} else if (ph === 'b') {
// TODO: Begin user timing measure
} else if (ph === 'e') {
// TODO: End user timing measure
} else if (ph === 'i' || ph === 'I') {
// Instant events.
// Note that the capital "I" is a deprecated value that exists in Chrome Canary traces.
} else {
throw new InvalidProfileError(
`Unrecognized event ${JSON.stringify(
event,
)}! This is likely a bug in this profiler tool.`,
);
}
break;
}
}
function assertNoOverlappingComponentMeasure(state: ProcessorState) {
if (state.currentReactComponentMeasure !== null) {
console.error(
'Component measure started while another measure in progress:',
state.currentReactComponentMeasure,
);
}
}
function assertCurrentComponentMeasureType(
state: ProcessorState,
type: ReactComponentMeasureType,
): void {
if (state.currentReactComponentMeasure === null) {
console.error(
`Component measure type "${type}" stopped while no measure was in progress`,
);
} else if (state.currentReactComponentMeasure.type !== type) {
console.error(
`Component measure type "${type}" stopped while type ${state.currentReactComponentMeasure.type} in progress`,
);
}
}
function processReactComponentMeasure(
name: string,
startTime: Milliseconds,
currentProfilerData: TimelineData,
state: ProcessorState,
): void {
if (name.startsWith('--component-render-start-')) {
const [componentName] = name.slice(25).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'render',
warning: null,
};
} else if (name === '--component-render-stop') {
assertCurrentComponentMeasureType(state, 'render');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-layout-effect-mount-start-')) {
const [componentName] = name.slice(38).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'layout-effect-mount',
warning: null,
};
} else if (name === '--component-layout-effect-mount-stop') {
assertCurrentComponentMeasureType(state, 'layout-effect-mount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-layout-effect-unmount-start-')) {
const [componentName] = name.slice(40).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'layout-effect-unmount',
warning: null,
};
} else if (name === '--component-layout-effect-unmount-stop') {
assertCurrentComponentMeasureType(state, 'layout-effect-unmount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-passive-effect-mount-start-')) {
const [componentName] = name.slice(39).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'passive-effect-mount',
warning: null,
};
} else if (name === '--component-passive-effect-mount-stop') {
assertCurrentComponentMeasureType(state, 'passive-effect-mount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
} else if (name.startsWith('--component-passive-effect-unmount-start-')) {
const [componentName] = name.slice(41).split('-');
assertNoOverlappingComponentMeasure(state);
state.currentReactComponentMeasure = {
componentName,
timestamp: startTime,
duration: 0,
type: 'passive-effect-unmount',
warning: null,
};
} else if (name === '--component-passive-effect-unmount-stop') {
assertCurrentComponentMeasureType(state, 'passive-effect-unmount');
if (state.currentReactComponentMeasure !== null) {
const componentMeasure = state.currentReactComponentMeasure;
componentMeasure.duration = startTime - componentMeasure.timestamp;
state.currentReactComponentMeasure = null;
currentProfilerData.componentMeasures.push(componentMeasure);
}
}
}
function preprocessFlamechart(rawData: TimelineEvent[]): Flamechart {
let parsedData;
try {
parsedData = importFromChromeTimeline(rawData, 'react-devtools');
} catch (error) {
// Assume any Speedscope errors are caused by bad profiles
const errorToRethrow = new InvalidProfileError(error.message);
errorToRethrow.stack = error.stack;
throw errorToRethrow;
}
const profile = parsedData.profiles[0]; // TODO: Choose the main CPU thread only
const speedscopeFlamechart = new SpeedscopeFlamechart({
// $FlowFixMe[method-unbinding]
getTotalWeight: profile.getTotalWeight.bind(profile),
// $FlowFixMe[method-unbinding]
forEachCall: profile.forEachCall.bind(profile),
// $FlowFixMe[method-unbinding]
formatValue: profile.formatValue.bind(profile),
getColorBucketForFrame: () => 0,
});
const flamechart: Flamechart = speedscopeFlamechart.getLayers().map(layer =>
layer.map(
({
start,
end,
node: {
frame: {name, file, line, col},
},
}) => ({
name,
timestamp: start / 1000,
duration: (end - start) / 1000,
scriptUrl: file,
locationLine: line,
locationColumn: col,
}),
),
);
return flamechart;
}
function parseStackFrame(stackFrame: string): ErrorStackFrame | null {
const error = new Error();
error.stack = stackFrame;
const frames = ErrorStackParser.parse(error);
return frames.length === 1 ? frames[0] : null;
}
export default async function preprocessData(
timeline: TimelineEvent[],
): Promise<TimelineData> {
const flamechart = preprocessFlamechart(timeline);
const laneToReactMeasureMap: Map<ReactLane, Array<ReactMeasure>> = new Map();
for (let lane: ReactLane = 0; lane < REACT_TOTAL_NUM_LANES; lane++) {
laneToReactMeasureMap.set(lane, []);
}
const profilerData: TimelineData = {
batchUIDToMeasuresMap: new Map(),
componentMeasures: [],
duration: 0,
flamechart,
internalModuleSourceToRanges: new Map(),
laneToLabelMap: new Map(),
laneToReactMeasureMap,
nativeEvents: [],
networkMeasures: [],
otherUserTimingMarks: [],
reactVersion: null,
schedulingEvents: [],
snapshots: [],
snapshotHeight: 0,
startTime: 0,
suspenseEvents: [],
thrownErrors: [],
};
// Sort `timeline`. JSON Array Format trace events need not be ordered. See:
// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.f2f0yd51wi15
timeline = timeline.filter(Boolean).sort((a, b) => (a.ts > b.ts ? 1 : -1));
// Events displayed in flamechart have timestamps relative to the profile
// event's startTime. Source: https://github.com/v8/v8/blob/44bd8fd7/src/inspector/js_protocol.json#L1486
//
// We'll thus expect there to be a 'Profile' event; if there is not one, we
// can deduce that there are no flame chart events. As we expect React
// scheduling profiling user timing marks to be recorded together with browser
// flame chart events, we can futher deduce that the data is invalid and we
// don't bother finding React events.
const indexOfProfileEvent = timeline.findIndex(
event => event.name === 'Profile',
);
if (indexOfProfileEvent === -1) {
return profilerData;
}
// Use Profile event's `startTime` as the start time to align with flame chart.
// TODO: Remove assumption that there'll only be 1 'Profile' event. If this
// assumption does not hold, the chart may start at the wrong time.
profilerData.startTime = timeline[indexOfProfileEvent].args.data.startTime;
profilerData.duration =
(timeline[timeline.length - 1].ts - profilerData.startTime) / 1000;
const state: ProcessorState = {
asyncProcessingPromises: [],
batchUID: 0,
currentReactComponentMeasure: null,
internalModuleCurrentStackFrame: null,
internalModuleStackStringSet: new Set(),
measureStack: [],
nativeEventStack: [],
nextRenderShouldGenerateNewBatchID: true,
potentialLongEvents: [],
potentialLongNestedUpdate: null,
potentialLongNestedUpdates: [],
potentialSuspenseEventsOutsideOfTransition: [],
requestIdToNetworkMeasureMap: new Map(),
uidCounter: 0,
unresolvedSuspenseEvents: new Map(),
};
timeline.forEach(event => processTimelineEvent(event, profilerData, state));
if (profilerVersion === null) {
if (
profilerData.schedulingEvents.length === 0 &&
profilerData.batchUIDToMeasuresMap.size === 0
) {
// No profiler version could indicate data was logged using an older build of React,
// before an explicitly profiler version was included in the logging data.
// But it could also indicate that the website was either not using React, or using a production build.
// The easiest way to check for this case is to see if the data contains any scheduled updates or render work.
throw new InvalidProfileError(
'No React marks were found in the provided profile.' +
' Please provide profiling data from an React application running in development or profiling mode.',
);
}
throw new InvalidProfileError(
`This version of profiling data is not supported by the current profiler.`,
);
}
// Validate that all events and measures are complete
const {measureStack} = state;
if (measureStack.length > 0) {
console.error('Incomplete events or measures', measureStack);
}
// Check for warnings.
state.potentialLongEvents.forEach(([nativeEvent, batchUID]) => {
// See how long the subsequent batch of React work was.
// Ignore any work that was already started.
const [startTime, stopTime] = getBatchRange(
batchUID,
profilerData,
nativeEvent.timestamp,
);
if (stopTime - startTime > NATIVE_EVENT_DURATION_THRESHOLD) {
nativeEvent.warning = WARNING_STRINGS.LONG_EVENT_HANDLER;
}
});
state.potentialLongNestedUpdates.forEach(([schedulingEvent, batchUID]) => {
// See how long the subsequent batch of React work was.
const [startTime, stopTime] = getBatchRange(batchUID, profilerData);
if (stopTime - startTime > NESTED_UPDATE_DURATION_THRESHOLD) {
// Don't warn about transition updates scheduled during the commit phase.
// e.g. useTransition, useDeferredValue
// These are allowed to be long-running.
if (
!schedulingEvent.lanes.some(
lane => profilerData.laneToLabelMap.get(lane) === 'Transition',
)
) {
// FIXME: This warning doesn't account for "nested updates" that are
// spawned by useDeferredValue. Disabling temporarily until we figure
// out the right way to handle this.
// schedulingEvent.warning = WARNING_STRINGS.NESTED_UPDATE;
}
}
});
state.potentialSuspenseEventsOutsideOfTransition.forEach(
([suspenseEvent, lanes]) => {
// HACK This is a bit gross but the numeric lane value might change between render versions.
if (
!lanes.some(
lane => profilerData.laneToLabelMap.get(lane) === 'Transition',
)
) {
suspenseEvent.warning = WARNING_STRINGS.SUSPEND_DURING_UPDATE;
}
},
);
// Wait for any async processing to complete before returning.
// Since processing is done in a worker, async work must complete before data is serialized and returned.
await Promise.all(state.asyncProcessingPromises);
// Now that all images have been loaded, let's figure out the display size we're going to use for our thumbnails:
// both the ones rendered to the canvas and the ones shown on hover.
if (profilerData.snapshots.length > 0) {
// NOTE We assume a static window size here, which is not necessarily true but should be for most cases.
// Regardless, Chrome also sets a single size/ratio and stick with it- so we'll do the same.
const snapshot = profilerData.snapshots[0];
profilerData.snapshotHeight = Math.min(
snapshot.height,
SNAPSHOT_MAX_HEIGHT,
);
}
return profilerData;
}
| 31.902813 | 120 | 0.660232 |
owtf | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
const defaultTheme = require('tailwindcss/defaultTheme');
const colors = require('./colors');
module.exports = {
content: [
'./src/components/**/*.{js,ts,jsx,tsx}',
'./src/pages/**/*.{js,ts,jsx,tsx}',
'./src/styles/**/*.{js,ts,jsx,tsx}',
],
darkMode: 'class',
theme: {
// Override base screen sizes
screens: {
...defaultTheme.screens,
betterhover: {raw: '(hover: hover)'},
xs: '374px',
'3xl': '1919px',
},
boxShadow: {
sm: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
DEFAULT:
'0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
md: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
lg: '0px 0.8px 2px rgba(0, 0, 0, 0.032), 0px 2.7px 6.7px rgba(0, 0, 0, 0.048), 0px 12px 30px rgba(0, 0, 0, 0.08)',
'lg-dark':
'0 0 0 1px rgba(255,255,255,.15), 0px 0.8px 2px rgba(0, 0, 0, 0.032), 0px 2.7px 6.7px rgba(0, 0, 0, 0.048), 0px 12px 30px rgba(0, 0, 0, 0.08)',
xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
'2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)',
'3xl': '0 35px 60px -15px rgba(0, 0, 0, 0.3)',
nav: '0 16px 32px -16px rgba(0, 0, 0, 0.1), 0 0 0 1px rgba(0,0,0,.10)',
'nav-dark':
'0 16px 32px -16px rgba(0, 0, 0, 0.1), 0 0 0 1px rgba(255,255,255,.05)',
inner: 'inset 0 1px 4px 0 rgba(0, 0, 0, 0.05)',
'inner-border': 'inset 0 0 0 1px rgba(0, 0, 0, 0.08)',
'inner-border-dark': 'inset 0 0 0 1px rgba(255, 255, 255, 0.08)',
'outer-border': '0 0 0 1px rgba(0, 0, 0, 0.1)',
'outer-border-dark': '0 0 0 1px rgba(255, 255, 255, 0.1)',
'secondary-button-stroke': 'inset 0 0 0 1px #D9DBE3',
'secondary-button-stroke-dark': 'inset 0 0 0 1px #404756',
none: 'none',
},
extend: {
backgroundImage: {
'gradient-left-dark':
'conic-gradient(from 90deg at -10% 100%, #2B303B 0deg, #2B303B 90deg, #16181D 360deg)',
'gradient-right-dark':
'conic-gradient(from -90deg at 110% 100%, #2B303B 0deg, #16181D 90deg, #16181D 360deg)',
'gradient-left':
'conic-gradient(from 90deg at -10% 100%, #BCC1CD 0deg, #BCC1CD 90deg, #FFFFFF 360deg)',
'gradient-right':
'conic-gradient(from -90deg at 110% 100%, #FFFFFF 0deg, #EBECF0 90deg, #EBECF0 360deg)',
'meta-gradient': "url('/images/meta-gradient.png')",
'meta-gradient-dark': "url('/images/meta-gradient-dark.png')",
},
maxWidth: {
...defaultTheme.maxWidth,
xs: '21rem',
},
minWidth:{
...defaultTheme.minWidth,
80: '20rem',
},
outline: {
blue: ['1px auto ' + colors.link, '3px'],
},
opacity: {
8: '0.08',
},
fontFamily: {
display: [
'Optimistic Display',
'-apple-system',
...defaultTheme.fontFamily.sans,
],
text: [
'Optimistic Text',
'-apple-system',
...defaultTheme.fontFamily.sans,
],
mono: ['"Source Code Pro"', ...defaultTheme.fontFamily.mono],
},
lineHeight: {
base: '30px',
large: '38px',
xl: '1.15',
},
fontSize: {
'6xl': '52px',
'5xl': '40px',
'4xl': '32px',
'3xl': '28px',
'2xl': '24px',
xl: '20px',
lg: '17px',
base: '15px',
sm: '13px',
xs: '11px',
code: 'calc(1em - 20%)',
},
animation: {
marquee: 'marquee 40s linear infinite',
marquee2: 'marquee2 40s linear infinite',
'large-marquee': 'large-marquee 80s linear infinite',
'large-marquee2': 'large-marquee2 80s linear infinite',
'fade-up': 'fade-up 1s 100ms both',
},
keyframes: {
shimmer: {
'100%': {
transform: 'translateX(100%)',
},
},
rotate: {
from: {transform: 'rotate(0deg)'},
to: {transform: 'rotate(180deg)'},
},
scale: {
from: {transform: 'scale(0.8)'},
'90%': {transform: 'scale(1.05)'},
to: {transform: 'scale(1)'},
},
circle: {
from: {transform: 'scale(0)', strokeWidth: '16px'},
'50%': {transform: 'scale(0.5)', strokeWidth: '16px'},
to: {transform: 'scale(1)', strokeWidth: '0px'},
},
marquee: {
'0%': {transform: 'translateX(0%)'},
'100%': {transform: 'translateX(-400%)'},
},
marquee2: {
'0%': {transform: 'translateX(400%)'},
'100%': {transform: 'translateX(0%)'},
},
'large-marquee': {
'0%': {transform: 'translateX(0%)'},
'100%': {transform: 'translateX(-200%)'},
},
'large-marquee2': {
'0%': {transform: 'translateX(200%)'},
'100%': {transform: 'translateX(0%)'},
},
'fade-up': {
'0%': {
opacity: '0',
transform: 'translateY(2rem)',
},
'100%': {
opacity: '1',
transform: 'translateY(0)',
},
},
},
colors,
gridTemplateColumns: {
'only-content': 'auto',
'sidebar-content': '20rem auto',
'sidebar-content-toc': '20rem auto 20rem',
},
},
},
plugins: [],
};
| 31.52381 | 151 | 0.483983 |
PenetrationTestingScripts | import {printStore} from 'react-devtools-shared/src/devtools/utils';
// test() is part of Jest's serializer API
export function test(maybeStore) {
// It's important to lazy-require the Store rather than imported at the head of the module.
// Because we reset modules between tests, different Store implementations will be used for each test.
// Unfortunately Jest does not reset its own serializer modules.
return (
maybeStore instanceof
require('react-devtools-shared/src/devtools/store').default
);
}
// print() is part of Jest's serializer API
export function print(store, serialize, indent) {
return printStore(store);
}
// Used for Jest snapshot testing.
// May also be useful for visually debugging the tree, so it lives on the Store.
export {printStore};
| 34.727273 | 104 | 0.749045 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useTheme;
exports.ThemeContext = void 0;
var _react = require("react");
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright');
exports.ThemeContext = ThemeContext;
function useTheme() {
const theme = (0, _react.useContext)(ThemeContext);
(0, _react.useDebugValue)(theme);
return theme;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZW1lIiwidGhlbWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBU0E7O0FBVEE7Ozs7Ozs7O0FBV08sTUFBTUEsWUFBWSxnQkFBRywwQkFBYyxRQUFkLENBQXJCOzs7QUFFUSxTQUFTQyxRQUFULEdBQW9CO0FBQ2pDLFFBQU1DLEtBQUssR0FBRyx1QkFBV0YsWUFBWCxDQUFkO0FBQ0EsNEJBQWNFLEtBQWQ7QUFDQSxTQUFPQSxLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0LCB1c2VEZWJ1Z1ZhbHVlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBjb25zdCBUaGVtZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0KCdicmlnaHQnKTtcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gdXNlVGhlbWUoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlQ29udGV4dChUaGVtZUNvbnRleHQpO1xuICB1c2VEZWJ1Z1ZhbHVlKHRoZW1lKTtcbiAgcmV0dXJuIHRoZW1lO1xufVxuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiIsInRoZW1lIl0sIm1hcHBpbmdzIjoiQ0FBRDtlZ0JDQSxBd0JEQSJ9XV19fV19 | 68.111111 | 1,256 | 0.892761 |
owtf | import React from 'react';
import {useContext} from 'react';
import {connect} from 'react-redux';
import ThemeContext from './shared/ThemeContext';
import lazyLegacyRoot from './lazyLegacyRoot';
// Lazy-load a component from the bundle using legacy React.
const Greeting = lazyLegacyRoot(() => import('../legacy/Greeting'));
function AboutPage({counter, dispatch}) {
const theme = useContext(ThemeContext);
return (
<>
<h2>src/modern/AboutPage.js</h2>
<h3 style={{color: theme}}>
This component is rendered by the outer React ({React.version}).
</h3>
<Greeting />
<br />
<p>
Counter: {counter}{' '}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</p>
</>
);
}
function mapStateToProps(state) {
return {counter: state};
}
export default connect(mapStateToProps)(AboutPage);
| 24.852941 | 72 | 0.64123 |
PenetrationTestingScripts | const chromeManifest = require('../react-devtools-extensions/chrome/manifest.json');
const firefoxManifest = require('../react-devtools-extensions/firefox/manifest.json');
const minChromeVersion = parseInt(chromeManifest.minimum_chrome_version, 10);
const minFirefoxVersion = parseInt(
firefoxManifest.applications.gecko.strict_min_version,
10,
);
validateVersion(minChromeVersion);
validateVersion(minFirefoxVersion);
function validateVersion(version) {
if (version > 0 && version < 200) {
return;
}
throw new Error('Suspicious browser version in manifest: ' + version);
}
module.exports = api => {
const isTest = api.env('test');
const targets = {};
if (isTest) {
targets.node = 'current';
} else {
targets.chrome = minChromeVersion.toString();
targets.firefox = minFirefoxVersion.toString();
let additionalTargets = process.env.BABEL_CONFIG_ADDITIONAL_TARGETS;
if (additionalTargets) {
additionalTargets = JSON.parse(additionalTargets);
for (const target in additionalTargets) {
targets[target] = additionalTargets[target];
}
}
}
const plugins = [
['@babel/plugin-transform-flow-strip-types'],
['@babel/plugin-proposal-class-properties', {loose: false}],
];
if (process.env.NODE_ENV !== 'production') {
plugins.push(['@babel/plugin-transform-react-jsx-source']);
}
return {
plugins,
presets: [
['@babel/preset-env', {targets}],
'@babel/preset-react',
'@babel/preset-flow',
],
};
};
| 28.192308 | 86 | 0.681608 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @jest-environment node
*/
'use strict';
describe('ReactIncrementalErrorReplay-test', () => {
const React = require('react');
const ReactTestRenderer = require('react-test-renderer');
it('copies all keys when stashing potentially failing work', () => {
// Note: this test is fragile and relies on internals.
// We almost always try to avoid such tests, but here the cost of
// the list getting out of sync (and causing subtle bugs in rare cases)
// is higher than the cost of maintaining the test.
// This is the method we're going to test.
// If this is no longer used, you can delete this test file.;
const {assignFiberPropertiesInDEV} = require('../ReactFiber');
// Get a real fiber.
const realFiber = ReactTestRenderer.create(<div />).root._currentFiber();
const stash = assignFiberPropertiesInDEV(null, realFiber);
// Verify we get all the same fields.
expect(realFiber).toEqual(stash);
// Mutate the original.
for (const key in realFiber) {
realFiber[key] = key + '_' + Math.random();
}
expect(realFiber).not.toEqual(stash);
// Verify we can still "revert" to the stashed properties.
expect(assignFiberPropertiesInDEV(realFiber, stash)).toBe(realFiber);
expect(realFiber).toEqual(stash);
});
});
| 32.954545 | 77 | 0.683858 |
null | 'use strict';
const baseConfig = require('./config.base');
module.exports = Object.assign({}, baseConfig, {
modulePathIgnorePatterns: [
...baseConfig.modulePathIgnorePatterns,
'packages/react-devtools-extensions',
'packages/react-devtools-shared',
'ReactIncrementalPerf',
'ReactIncrementalUpdatesMinimalism',
'ReactIncrementalTriangle',
'ReactIncrementalReflection',
'forwardRef',
],
setupFiles: [
...baseConfig.setupFiles,
require.resolve('./setupTests.persistent.js'),
require.resolve('./setupHostConfigs.js'),
],
});
| 25.136364 | 50 | 0.702091 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 41