repo_name
stringlengths 4
68
⌀ | text
stringlengths 21
269k
| avg_line_length
float64 9.4
9.51k
| max_line_length
int64 20
28.5k
| alphnanum_fraction
float64 0.3
0.92
|
---|---|---|---|---|
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('SyntheticClipboardEvent', () => {
let container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
// The container has to be attached for events to fire.
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
describe('ClipboardEvent interface', () => {
describe('clipboardData', () => {
describe('when event has clipboardData', () => {
it("returns event's clipboardData", () => {
let expectedCount = 0;
// Mock clipboardData since jsdom implementation doesn't have a constructor
const clipboardData = {
dropEffect: null,
effectAllowed: null,
files: null,
items: null,
types: null,
};
const eventHandler = event => {
expect(event.clipboardData).toBe(clipboardData);
expectedCount++;
};
const div = ReactDOM.render(
<div
onCopy={eventHandler}
onCut={eventHandler}
onPaste={eventHandler}
/>,
container,
);
let event;
event = document.createEvent('Event');
event.initEvent('copy', true, true);
event.clipboardData = clipboardData;
div.dispatchEvent(event);
event = document.createEvent('Event');
event.initEvent('cut', true, true);
event.clipboardData = clipboardData;
div.dispatchEvent(event);
event = document.createEvent('Event');
event.initEvent('paste', true, true);
event.clipboardData = clipboardData;
div.dispatchEvent(event);
expect(expectedCount).toBe(3);
});
});
});
});
describe('EventInterface', () => {
it('is able to `preventDefault` and `stopPropagation`', () => {
let expectedCount = 0;
const eventHandler = event => {
expect(event.isDefaultPrevented()).toBe(false);
event.preventDefault();
expect(event.isDefaultPrevented()).toBe(true);
expect(event.isPropagationStopped()).toBe(false);
event.stopPropagation();
expect(event.isPropagationStopped()).toBe(true);
expectedCount++;
};
const div = ReactDOM.render(
<div
onCopy={eventHandler}
onCut={eventHandler}
onPaste={eventHandler}
/>,
container,
);
let event;
event = document.createEvent('Event');
event.initEvent('copy', true, true);
div.dispatchEvent(event);
event = document.createEvent('Event');
event.initEvent('cut', true, true);
div.dispatchEvent(event);
event = document.createEvent('Event');
event.initEvent('paste', true, true);
div.dispatchEvent(event);
expect(expectedCount).toBe(3);
});
});
});
| 26.057851 | 85 | 0.573174 |
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
*/
const {connectToDevTools} = require('react-devtools-core/backend');
// Connect immediately with default options.
// If you need more control, use `react-devtools-core` directly instead of `react-devtools`.
connectToDevTools();
| 27.866667 | 92 | 0.731481 |
Python-for-Offensive-PenTest | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {CommitDataFrontend} from './types';
import * as React from 'react';
import {useEffect, useMemo, useRef, useState} from 'react';
import AutoSizer from 'react-virtualized-auto-sizer';
import {FixedSizeList} from 'react-window';
import SnapshotCommitListItem from './SnapshotCommitListItem';
import {minBarWidth} from './constants';
import {formatDuration, formatTime} from './utils';
import Tooltip from './Tooltip';
import styles from './SnapshotCommitList.css';
export type ItemData = {
commitTimes: Array<number>,
filteredCommitIndices: Array<number>,
maxDuration: number,
selectedCommitIndex: number | null,
selectedFilteredCommitIndex: number | null,
selectCommitIndex: (index: number) => void,
setHoveredCommitIndex: (index: number) => void,
startCommitDrag: (newDragState: DragState) => void,
totalDurations: Array<number>,
};
type Props = {
commitData: $ReadOnlyArray<CommitDataFrontend>,
commitTimes: Array<number>,
filteredCommitIndices: Array<number>,
selectedCommitIndex: number | null,
selectedFilteredCommitIndex: number | null,
selectCommitIndex: (index: number) => void,
totalDurations: Array<number>,
};
export default function SnapshotCommitList({
commitData,
commitTimes,
filteredCommitIndices,
selectedCommitIndex,
selectedFilteredCommitIndex,
selectCommitIndex,
totalDurations,
}: Props): React.Node {
return (
<AutoSizer>
{({height, width}) => (
<List
commitData={commitData}
commitTimes={commitTimes}
height={height}
filteredCommitIndices={filteredCommitIndices}
selectedCommitIndex={selectedCommitIndex}
selectedFilteredCommitIndex={selectedFilteredCommitIndex}
selectCommitIndex={selectCommitIndex}
totalDurations={totalDurations}
width={width}
/>
)}
</AutoSizer>
);
}
type ListProps = {
commitData: $ReadOnlyArray<CommitDataFrontend>,
commitTimes: Array<number>,
height: number,
filteredCommitIndices: Array<number>,
selectedCommitIndex: number | null,
selectedFilteredCommitIndex: number | null,
selectCommitIndex: (index: number) => void,
totalDurations: Array<number>,
width: number,
};
type DragState = {
commitIndex: number,
left: number,
sizeIncrement: number,
};
function List({
commitData,
selectedCommitIndex,
commitTimes,
height,
filteredCommitIndices,
selectedFilteredCommitIndex,
selectCommitIndex,
totalDurations,
width,
}: ListProps) {
// $FlowFixMe[incompatible-use]
const listRef = useRef<FixedSizeList<ItemData> | null>(null);
const divRef = useRef<HTMLDivElement | null>(null);
const prevCommitIndexRef = useRef<number | null>(null);
// Make sure a newly selected snapshot is fully visible within the list.
useEffect(() => {
if (selectedFilteredCommitIndex !== prevCommitIndexRef.current) {
prevCommitIndexRef.current = selectedFilteredCommitIndex;
if (selectedFilteredCommitIndex !== null && listRef.current !== null) {
listRef.current.scrollToItem(selectedFilteredCommitIndex);
}
}
}, [listRef, selectedFilteredCommitIndex]);
const itemSize = useMemo(
() => Math.max(minBarWidth, width / filteredCommitIndices.length),
[filteredCommitIndices, width],
);
const maxDuration = useMemo(
() => totalDurations.reduce((max, duration) => Math.max(max, duration), 0),
[totalDurations],
);
const maxCommitIndex = filteredCommitIndices.length - 1;
const [dragState, setDragState] = useState<DragState | null>(null);
const handleDragCommit = ({buttons, pageX}: any) => {
if (buttons === 0) {
setDragState(null);
return;
}
if (dragState !== null) {
const {commitIndex, left, sizeIncrement} = dragState;
let newCommitIndex = commitIndex;
let newCommitLeft = left;
if (pageX < newCommitLeft) {
while (pageX < newCommitLeft) {
newCommitLeft -= sizeIncrement;
newCommitIndex -= 1;
}
} else {
let newCommitRectRight = newCommitLeft + sizeIncrement;
while (pageX > newCommitRectRight) {
newCommitRectRight += sizeIncrement;
newCommitIndex += 1;
}
}
if (newCommitIndex < 0) {
newCommitIndex = 0;
} else if (newCommitIndex > maxCommitIndex) {
newCommitIndex = maxCommitIndex;
}
selectCommitIndex(newCommitIndex);
}
};
useEffect(() => {
if (dragState === null) {
return;
}
const element = divRef.current;
if (element !== null) {
const ownerDocument = element.ownerDocument;
ownerDocument.addEventListener('mousemove', handleDragCommit);
return () => {
ownerDocument.removeEventListener('mousemove', handleDragCommit);
};
}
}, [dragState]);
const [hoveredCommitIndex, setHoveredCommitIndex] = useState<number | null>(
null,
);
// Pass required contextual data down to the ListItem renderer.
const itemData = useMemo<ItemData>(
() => ({
commitTimes,
filteredCommitIndices,
maxDuration,
selectedCommitIndex,
selectedFilteredCommitIndex,
selectCommitIndex,
setHoveredCommitIndex,
startCommitDrag: setDragState,
totalDurations,
}),
[
commitTimes,
filteredCommitIndices,
maxDuration,
selectedCommitIndex,
selectedFilteredCommitIndex,
selectCommitIndex,
setHoveredCommitIndex,
totalDurations,
],
);
let tooltipLabel = null;
if (hoveredCommitIndex !== null) {
const {
duration,
effectDuration,
passiveEffectDuration,
priorityLevel,
timestamp,
} = commitData[hoveredCommitIndex];
// Only some React versions include commit durations.
// Show a richer tooltip only for builds that have that info.
if (
effectDuration !== null ||
passiveEffectDuration !== null ||
priorityLevel !== null
) {
tooltipLabel = (
<ul className={styles.TooltipList}>
{priorityLevel !== null && (
<li className={styles.TooltipListItem}>
<label className={styles.TooltipLabel}>Priority</label>
<span className={styles.TooltipValue}>{priorityLevel}</span>
</li>
)}
<li className={styles.TooltipListItem}>
<label className={styles.TooltipLabel}>Committed at</label>
<span className={styles.TooltipValue}>
{formatTime(timestamp)}s
</span>
</li>
<li className={styles.TooltipListItem}>
<div className={styles.DurationsWrapper}>
<label className={styles.TooltipLabel}>Durations</label>
<ul className={styles.DurationsList}>
<li className={styles.DurationsListItem}>
<label className={styles.DurationsLabel}>Render</label>
<span className={styles.DurationsValue}>
{formatDuration(duration)}ms
</span>
</li>
{effectDuration !== null && (
<li className={styles.DurationsListItem}>
<label className={styles.DurationsLabel}>
Layout effects
</label>
<span className={styles.DurationsValue}>
{formatDuration(effectDuration)}ms
</span>
</li>
)}
{passiveEffectDuration !== null && (
<li className={styles.DurationsListItem}>
<label className={styles.DurationsLabel}>
Passive effects
</label>
<span className={styles.DurationsValue}>
{formatDuration(passiveEffectDuration)}ms
</span>
</li>
)}
</ul>
</div>
</li>
</ul>
);
} else {
tooltipLabel = `${formatDuration(duration)}ms at ${formatTime(
timestamp,
)}s`;
}
}
return (
<Tooltip className={styles.Tooltip} label={tooltipLabel}>
<div
ref={divRef}
style={{height, width}}
onMouseLeave={() => setHoveredCommitIndex(null)}>
<FixedSizeList
className={styles.List}
layout="horizontal"
height={height}
itemCount={filteredCommitIndices.length}
itemData={itemData}
itemSize={itemSize}
ref={(listRef: any) /* Flow bug? */}
width={width}>
{SnapshotCommitListItem}
</FixedSizeList>
</div>
</Tooltip>
);
}
| 28.511551 | 79 | 0.619953 |
owtf | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
const path = require('path');
const rimraf = require('rimraf');
const webpack = require('webpack');
const isProduction = process.env.NODE_ENV === 'production';
rimraf.sync(path.resolve(__dirname, '../build'));
webpack(
{
mode: isProduction ? 'production' : 'development',
devtool: isProduction ? 'source-map' : 'cheap-module-source-map',
entry: [path.resolve(__dirname, '../src/index.js')],
output: {
path: path.resolve(__dirname, '../build'),
filename: 'main.js',
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
},
(err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
process.exit(1);
}
const info = stats.toJson();
if (stats.hasErrors()) {
console.log('Finished running webpack with errors.');
info.errors.forEach(e => console.error(e));
process.exit(1);
} else {
console.log('Finished running webpack.');
}
}
);
| 23.388889 | 69 | 0.571429 |
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 {rethrowCaughtError} from 'shared/ReactErrorUtils';
import type {ReactSyntheticEvent} from './ReactSyntheticEventType';
import accumulateInto from './accumulateInto';
import forEachAccumulated from './forEachAccumulated';
import {executeDispatchesInOrder} from './EventPluginUtils';
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
let eventQueue: ?(Array<ReactSyntheticEvent> | ReactSyntheticEvent) = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @private
*/
function executeDispatchesAndRelease(event: ReactSyntheticEvent) {
if (event) {
executeDispatchesInOrder(event);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
}
// $FlowFixMe[missing-local-annot]
function executeDispatchesAndReleaseTopLevel(e) {
return executeDispatchesAndRelease(e);
}
export function runEventsInBatch(
events: Array<ReactSyntheticEvent> | ReactSyntheticEvent | null,
) {
if (events !== null) {
eventQueue = accumulateInto(eventQueue, events);
}
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
const processingEventQueue = eventQueue;
eventQueue = null;
if (!processingEventQueue) {
return;
}
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
if (eventQueue) {
throw new Error(
'processEventQueue(): Additional events were enqueued while processing ' +
'an event queue. Support for this has not yet been implemented.',
);
}
// This would be a good time to rethrow if any of the event handlers threw.
rethrowCaughtError();
}
| 27.742857 | 80 | 0.735455 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ComponentUsingHooksIndirectly", {
enumerable: true,
get: function () {
return _ComponentUsingHooksIndirectly.Component;
}
});
Object.defineProperty(exports, "ComponentWithCustomHook", {
enumerable: true,
get: function () {
return _ComponentWithCustomHook.Component;
}
});
Object.defineProperty(exports, "ComponentWithExternalCustomHooks", {
enumerable: true,
get: function () {
return _ComponentWithExternalCustomHooks.Component;
}
});
Object.defineProperty(exports, "ComponentWithMultipleHooksPerLine", {
enumerable: true,
get: function () {
return _ComponentWithMultipleHooksPerLine.Component;
}
});
Object.defineProperty(exports, "ComponentWithNestedHooks", {
enumerable: true,
get: function () {
return _ComponentWithNestedHooks.Component;
}
});
Object.defineProperty(exports, "ContainingStringSourceMappingURL", {
enumerable: true,
get: function () {
return _ContainingStringSourceMappingURL.Component;
}
});
Object.defineProperty(exports, "Example", {
enumerable: true,
get: function () {
return _Example.Component;
}
});
Object.defineProperty(exports, "InlineRequire", {
enumerable: true,
get: function () {
return _InlineRequire.Component;
}
});
Object.defineProperty(exports, "useTheme", {
enumerable: true,
get: function () {
return _useTheme.default;
}
});
exports.ToDoList = void 0;
var _ComponentUsingHooksIndirectly = require("./ComponentUsingHooksIndirectly");
var _ComponentWithCustomHook = require("./ComponentWithCustomHook");
var _ComponentWithExternalCustomHooks = require("./ComponentWithExternalCustomHooks");
var _ComponentWithMultipleHooksPerLine = require("./ComponentWithMultipleHooksPerLine");
var _ComponentWithNestedHooks = require("./ComponentWithNestedHooks");
var _ContainingStringSourceMappingURL = require("./ContainingStringSourceMappingURL");
var _Example = require("./Example");
var _InlineRequire = require("./InlineRequire");
var ToDoList = _interopRequireWildcard(require("./ToDoList"));
exports.ToDoList = ToDoList;
var _useTheme = _interopRequireDefault(require("./useTheme"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
//# sourceMappingURL=index.js.map?foo=bar¶m=some_value | 36.325843 | 743 | 0.727793 |
null | #!/usr/bin/env node
'use strict';
const {exec} = require('child-process-promise');
const {join} = require('path');
const {logPromise} = require('../utils');
const shell = require('shelljs');
const run = async ({cwd, dry, tempDirectory}) => {
const defaultOptions = {
cwd: tempDirectory,
};
await exec('yarn install', defaultOptions);
await exec('yarn build -- --extract-errors', defaultOptions);
const tempNodeModulesPath = join(tempDirectory, 'build', 'node_modules');
const buildPath = join(cwd, 'build');
shell.cp('-r', tempNodeModulesPath, buildPath);
};
module.exports = async params => {
return logPromise(run(params), 'Building artifacts', 600000);
};
| 24.444444 | 75 | 0.677843 |
owtf | 'use client';
import * as React from 'react';
export default class ErrorBoundary extends React.Component {
state = {error: null};
static getDerivedStateFromError(error) {
return {error};
}
render() {
if (this.state.error) {
return <div>Caught an error: {this.state.error.message}</div>;
}
return this.props.children;
}
}
| 19.941176 | 68 | 0.659155 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import Agent from 'react-devtools-shared/src/backend/agent';
import resolveBoxStyle from './resolveBoxStyle';
import isArray from 'react-devtools-shared/src/isArray';
import type {BackendBridge} from 'react-devtools-shared/src/bridge';
import type {RendererID} from '../types';
import type {StyleAndLayout} from './types';
export type ResolveNativeStyle = (stylesheetID: any) => ?Object;
export type SetupNativeStyleEditor = typeof setupNativeStyleEditor;
export default function setupNativeStyleEditor(
bridge: BackendBridge,
agent: Agent,
resolveNativeStyle: ResolveNativeStyle,
validAttributes?: $ReadOnlyArray<string> | null,
) {
bridge.addListener(
'NativeStyleEditor_measure',
({id, rendererID}: {id: number, rendererID: RendererID}) => {
measureStyle(agent, bridge, resolveNativeStyle, id, rendererID);
},
);
bridge.addListener(
'NativeStyleEditor_renameAttribute',
({
id,
rendererID,
oldName,
newName,
value,
}: {
id: number,
rendererID: RendererID,
oldName: string,
newName: string,
value: string,
}) => {
renameStyle(agent, id, rendererID, oldName, newName, value);
setTimeout(() =>
measureStyle(agent, bridge, resolveNativeStyle, id, rendererID),
);
},
);
bridge.addListener(
'NativeStyleEditor_setValue',
({
id,
rendererID,
name,
value,
}: {
id: number,
rendererID: number,
name: string,
value: string,
}) => {
setStyle(agent, id, rendererID, name, value);
setTimeout(() =>
measureStyle(agent, bridge, resolveNativeStyle, id, rendererID),
);
},
);
bridge.send('isNativeStyleEditorSupported', {
isSupported: true,
validAttributes,
});
}
const EMPTY_BOX_STYLE = {
top: 0,
left: 0,
right: 0,
bottom: 0,
};
const componentIDToStyleOverrides: Map<number, Object> = new Map();
function measureStyle(
agent: Agent,
bridge: BackendBridge,
resolveNativeStyle: ResolveNativeStyle,
id: number,
rendererID: RendererID,
) {
const data = agent.getInstanceAndStyle({id, rendererID});
if (!data || !data.style) {
bridge.send(
'NativeStyleEditor_styleAndLayout',
({
id,
layout: null,
style: null,
}: StyleAndLayout),
);
return;
}
const {instance, style} = data;
let resolvedStyle = resolveNativeStyle(style);
// If it's a host component we edited before, amend styles.
const styleOverrides = componentIDToStyleOverrides.get(id);
if (styleOverrides != null) {
resolvedStyle = Object.assign({}, resolvedStyle, styleOverrides);
}
if (!instance || typeof instance.measure !== 'function') {
bridge.send(
'NativeStyleEditor_styleAndLayout',
({
id,
layout: null,
style: resolvedStyle || null,
}: StyleAndLayout),
);
return;
}
instance.measure((x, y, width, height, left, top) => {
// RN Android sometimes returns undefined here. Don't send measurements in this case.
// https://github.com/jhen0409/react-native-debugger/issues/84#issuecomment-304611817
if (typeof x !== 'number') {
bridge.send(
'NativeStyleEditor_styleAndLayout',
({
id,
layout: null,
style: resolvedStyle || null,
}: StyleAndLayout),
);
return;
}
const margin =
(resolvedStyle != null && resolveBoxStyle('margin', resolvedStyle)) ||
EMPTY_BOX_STYLE;
const padding =
(resolvedStyle != null && resolveBoxStyle('padding', resolvedStyle)) ||
EMPTY_BOX_STYLE;
bridge.send(
'NativeStyleEditor_styleAndLayout',
({
id,
layout: {
x,
y,
width,
height,
left,
top,
margin,
padding,
},
style: resolvedStyle || null,
}: StyleAndLayout),
);
});
}
function shallowClone(object: Object): Object {
const cloned: {[string]: $FlowFixMe} = {};
for (const n in object) {
cloned[n] = object[n];
}
return cloned;
}
function renameStyle(
agent: Agent,
id: number,
rendererID: RendererID,
oldName: string,
newName: string,
value: string,
): void {
const data = agent.getInstanceAndStyle({id, rendererID});
if (!data || !data.style) {
return;
}
const {instance, style} = data;
const newStyle = newName
? {[oldName]: undefined, [newName]: value}
: {[oldName]: undefined};
let customStyle;
// TODO It would be nice if the renderer interface abstracted this away somehow.
if (instance !== null && typeof instance.setNativeProps === 'function') {
// In the case of a host component, we need to use setNativeProps().
// Remember to "correct" resolved styles when we read them next time.
const styleOverrides = componentIDToStyleOverrides.get(id);
if (!styleOverrides) {
componentIDToStyleOverrides.set(id, newStyle);
} else {
Object.assign(styleOverrides, newStyle);
}
// TODO Fabric does not support setNativeProps; chat with Sebastian or Eli
instance.setNativeProps({style: newStyle});
} else if (isArray(style)) {
const lastIndex = style.length - 1;
if (typeof style[lastIndex] === 'object' && !isArray(style[lastIndex])) {
customStyle = shallowClone(style[lastIndex]);
delete customStyle[oldName];
if (newName) {
customStyle[newName] = value;
} else {
customStyle[oldName] = undefined;
}
agent.overrideValueAtPath({
type: 'props',
id,
rendererID,
path: ['style', lastIndex],
value: customStyle,
});
} else {
agent.overrideValueAtPath({
type: 'props',
id,
rendererID,
path: ['style'],
value: style.concat([newStyle]),
});
}
} else if (typeof style === 'object') {
customStyle = shallowClone(style);
delete customStyle[oldName];
if (newName) {
customStyle[newName] = value;
} else {
customStyle[oldName] = undefined;
}
agent.overrideValueAtPath({
type: 'props',
id,
rendererID,
path: ['style'],
value: customStyle,
});
} else {
agent.overrideValueAtPath({
type: 'props',
id,
rendererID,
path: ['style'],
value: [style, newStyle],
});
}
agent.emit('hideNativeHighlight');
}
function setStyle(
agent: Agent,
id: number,
rendererID: RendererID,
name: string,
value: string,
) {
const data = agent.getInstanceAndStyle({id, rendererID});
if (!data || !data.style) {
return;
}
const {instance, style} = data;
const newStyle = {[name]: value};
// TODO It would be nice if the renderer interface abstracted this away somehow.
if (instance !== null && typeof instance.setNativeProps === 'function') {
// In the case of a host component, we need to use setNativeProps().
// Remember to "correct" resolved styles when we read them next time.
const styleOverrides = componentIDToStyleOverrides.get(id);
if (!styleOverrides) {
componentIDToStyleOverrides.set(id, newStyle);
} else {
Object.assign(styleOverrides, newStyle);
}
// TODO Fabric does not support setNativeProps; chat with Sebastian or Eli
instance.setNativeProps({style: newStyle});
} else if (isArray(style)) {
const lastLength = style.length - 1;
if (typeof style[lastLength] === 'object' && !isArray(style[lastLength])) {
agent.overrideValueAtPath({
type: 'props',
id,
rendererID,
path: ['style', lastLength, name],
value,
});
} else {
agent.overrideValueAtPath({
type: 'props',
id,
rendererID,
path: ['style'],
value: style.concat([newStyle]),
});
}
} else {
agent.overrideValueAtPath({
type: 'props',
id,
rendererID,
path: ['style'],
value: [style, newStyle],
});
}
agent.emit('hideNativeHighlight');
}
| 24.295732 | 89 | 0.613187 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('SyntheticWheelEvent', () => {
let container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
// The container has to be attached for events to fire.
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('should normalize properties from the MouseEvent interface', () => {
const events = [];
const onWheel = event => {
event.persist();
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
container.firstChild.dispatchEvent(
new MouseEvent('wheel', {
bubbles: true,
button: 1,
}),
);
expect(events.length).toBe(1);
expect(events[0].button).toBe(1);
});
it('should normalize properties from the WheelEvent interface', () => {
const events = [];
const onWheel = event => {
event.persist();
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
let event = new MouseEvent('wheel', {
bubbles: true,
});
// jsdom doesn't support these so we add them manually.
Object.assign(event, {
deltaX: 10,
deltaY: -50,
});
container.firstChild.dispatchEvent(event);
event = new MouseEvent('wheel', {
bubbles: true,
});
// jsdom doesn't support these so we add them manually.
Object.assign(event, {
wheelDeltaX: -10,
wheelDeltaY: 50,
});
container.firstChild.dispatchEvent(event);
expect(events.length).toBe(2);
expect(events[0].deltaX).toBe(10);
expect(events[0].deltaY).toBe(-50);
expect(events[1].deltaX).toBe(10);
expect(events[1].deltaY).toBe(-50);
});
it('should be able to `preventDefault` and `stopPropagation`', () => {
const events = [];
const onWheel = event => {
expect(event.isDefaultPrevented()).toBe(false);
event.preventDefault();
expect(event.isDefaultPrevented()).toBe(true);
event.persist();
events.push(event);
};
ReactDOM.render(<div onWheel={onWheel} />, container);
container.firstChild.dispatchEvent(
new MouseEvent('wheel', {
bubbles: true,
deltaX: 10,
deltaY: -50,
}),
);
container.firstChild.dispatchEvent(
new MouseEvent('wheel', {
bubbles: true,
deltaX: 10,
deltaY: -50,
}),
);
expect(events.length).toBe(2);
});
});
| 23.086207 | 73 | 0.60222 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function Component() {
const [count, setCount] = (0, _react.useState)(0);
const isDarkMode = useIsDarkMode();
const {
foo
} = useFoo();
(0, _react.useEffect)(() => {// ...
}, []);
const handleClick = () => setCount(count + 1);
return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 25,
columnNumber: 7
}
}, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 26,
columnNumber: 7
}
}, "Count: ", count), /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 27,
columnNumber: 7
}
}, "Foo: ", foo), /*#__PURE__*/_react.default.createElement("button", {
onClick: handleClick,
__source: {
fileName: _jsxFileName,
lineNumber: 28,
columnNumber: 7
}
}, "Update count"));
}
function useIsDarkMode() {
const [isDarkMode] = (0, _react.useState)(false);
(0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event...
}, []);
return isDarkMode;
}
function useFoo() {
(0, _react.useDebugValue)('foo');
return {
foo: true
};
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhDdXN0b21Ib29rLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiLCJpc0RhcmtNb2RlIiwidXNlSXNEYXJrTW9kZSIsImZvbyIsInVzZUZvbyIsImhhbmRsZUNsaWNrIiwidXNlRWZmZWN0Q3JlYXRlIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7Ozs7Ozs7O0FBRU8sU0FBU0EsU0FBVCxHQUFxQjtBQUMxQixRQUFNLENBQUNDLEtBQUQsRUFBUUMsUUFBUixJQUFvQixxQkFBUyxDQUFULENBQTFCO0FBQ0EsUUFBTUMsVUFBVSxHQUFHQyxhQUFhLEVBQWhDO0FBQ0EsUUFBTTtBQUFDQyxJQUFBQTtBQUFELE1BQVFDLE1BQU0sRUFBcEI7QUFFQSx3QkFBVSxNQUFNLENBQ2Q7QUFDRCxHQUZELEVBRUcsRUFGSDs7QUFJQSxRQUFNQyxXQUFXLEdBQUcsTUFBTUwsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUFsQzs7QUFFQSxzQkFDRSx5RUFDRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFBaUJFLFVBQWpCLENBREYsZUFFRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFBYUYsS0FBYixDQUZGLGVBR0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FBV0ksR0FBWCxDQUhGLGVBSUU7QUFBUSxJQUFBLE9BQU8sRUFBRUUsV0FBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsb0JBSkYsQ0FERjtBQVFEOztBQUVELFNBQVNILGFBQVQsR0FBeUI7QUFDdkIsUUFBTSxDQUFDRCxVQUFELElBQWUscUJBQVMsS0FBVCxDQUFyQjtBQUVBLHdCQUFVLFNBQVNLLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU9MLFVBQVA7QUFDRDs7QUFFRCxTQUFTRyxNQUFULEdBQWtCO0FBQ2hCLDRCQUFjLEtBQWQ7QUFDQSxTQUFPO0FBQUNELElBQUFBLEdBQUcsRUFBRTtBQUFOLEdBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QsIHt1c2VEZWJ1Z1ZhbHVlLCB1c2VFZmZlY3QsIHVzZVN0YXRlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IFtjb3VudCwgc2V0Q291bnRdID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGlzRGFya01vZGUgPSB1c2VJc0RhcmtNb2RlKCk7XG4gIGNvbnN0IHtmb299ID0gdXNlRm9vKCk7XG5cbiAgdXNlRWZmZWN0KCgpID0+IHtcbiAgICAvLyAuLi5cbiAgfSwgW10pO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gKCkgPT4gc2V0Q291bnQoY291bnQgKyAxKTtcblxuICByZXR1cm4gKFxuICAgIDw+XG4gICAgICA8ZGl2PkRhcmsgbW9kZT8ge2lzRGFya01vZGV9PC9kaXY+XG4gICAgICA8ZGl2PkNvdW50OiB7Y291bnR9PC9kaXY+XG4gICAgICA8ZGl2PkZvbzoge2Zvb308L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSB1c2VTdGF0ZShmYWxzZSk7XG5cbiAgdXNlRWZmZWN0KGZ1bmN0aW9uIHVzZUVmZmVjdENyZWF0ZSgpIHtcbiAgICAvLyBIZXJlIGlzIHdoZXJlIHdlIG1heSBsaXN0ZW4gdG8gYSBcInRoZW1lXCIgZXZlbnQuLi5cbiAgfSwgW10pO1xuXG4gIHJldHVybiBpc0RhcmtNb2RlO1xufVxuXG5mdW5jdGlvbiB1c2VGb28oKSB7XG4gIHVzZURlYnVnVmFsdWUoJ2ZvbycpO1xuICByZXR1cm4ge2ZvbzogdHJ1ZX07XG59XG4iXSwieF9mYWNlYm9va19zb3VyY2VzIjpbW251bGwsW3sibmFtZXMiOlsiPG5vLWhvb2s+IiwiY291bnQiLCJpc0RhcmtNb2RlIl0sIm1hcHBpbmdzIjoiQ0FBRDthNEJDQSxBV0RBO2NsQkVBLEFlRkE7a0NiRUEifV1dXX19XX0= | 78.676471 | 2,936 | 0.827211 |
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.
*/
/**
* ReactElementValidator provides a wrapper around an element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
import isValidElementType from 'shared/isValidElementType';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import {
getIteratorFn,
REACT_FORWARD_REF_TYPE,
REACT_MEMO_TYPE,
REACT_FRAGMENT_TYPE,
REACT_ELEMENT_TYPE,
} from 'shared/ReactSymbols';
import checkPropTypes from 'shared/checkPropTypes';
import isArray from 'shared/isArray';
import ReactCurrentOwner from './ReactCurrentOwner';
import {
isValidElement,
createElement,
cloneElement,
jsxDEV,
} from './ReactElement';
import {setExtraStackFrame} from './ReactDebugCurrentFrame';
import {describeUnknownElementTypeFrameInDEV} from 'shared/ReactComponentStackFrame';
import hasOwnProperty from 'shared/hasOwnProperty';
const REACT_CLIENT_REFERENCE = Symbol.for('react.client.reference');
function setCurrentlyValidatingElement(element) {
if (__DEV__) {
if (element) {
const owner = element._owner;
const stack = describeUnknownElementTypeFrameInDEV(
element.type,
element._source,
owner ? owner.type : null,
);
setExtraStackFrame(stack);
} else {
setExtraStackFrame(null);
}
}
}
let propTypesMisspellWarningShown;
if (__DEV__) {
propTypesMisspellWarningShown = false;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
const name = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
function getSourceInfoErrorAddendum(source) {
if (source !== undefined) {
const fileName = source.fileName.replace(/^.*[\\\/]/, '');
const lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
function getSourceInfoErrorAddendumForProps(elementProps) {
if (elementProps !== null && elementProps !== undefined) {
return getSourceInfoErrorAddendum(elementProps.__source);
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
const ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
let info = getDeclarationErrorAddendum();
if (!info) {
const parentName = getComponentNameFromType(parentType);
if (parentName) {
info = `\n\nCheck the top-level render call using <${parentName}>.`;
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
const currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
let childOwner = '';
if (
element &&
element._owner &&
element._owner !== ReactCurrentOwner.current
) {
// Give the component that originally created this child.
childOwner = ` It was passed a child from ${getComponentNameFromType(
element._owner.type,
)}.`;
}
if (__DEV__) {
setCurrentlyValidatingElement(element);
console.error(
'Each child in a list should have a unique "key" prop.' +
'%s%s See https://reactjs.org/link/warning-keys for more information.',
currentComponentErrorInfo,
childOwner,
);
setCurrentlyValidatingElement(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object' || !node) {
return;
}
if (node.$$typeof === REACT_CLIENT_REFERENCE) {
// This is a reference to a client component so it's unknown.
} else if (isArray(node)) {
for (let i = 0; i < node.length; i++) {
const child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else {
const iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
const iterator = iteratorFn.call(node);
let step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
if (__DEV__) {
const type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
if (type.$$typeof === REACT_CLIENT_REFERENCE) {
return;
}
let propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (
typeof type === 'object' &&
(type.$$typeof === REACT_FORWARD_REF_TYPE ||
// Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)
) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
const name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true;
// Intentionally inside to avoid triggering lazy initializers:
const name = getComponentNameFromType(type);
console.error(
'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?',
name || 'Unknown',
);
}
if (
typeof type.getDefaultProps === 'function' &&
!type.getDefaultProps.isReactClassApproved
) {
console.error(
'getDefaultProps is only used on classic React.createClass ' +
'definitions. Use a static property named `defaultProps` instead.',
);
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
if (__DEV__) {
const keys = Object.keys(fragment.props);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement(fragment);
console.error(
'Invalid prop `%s` supplied to `React.Fragment`. ' +
'React.Fragment can only have `key` and `children` props.',
key,
);
setCurrentlyValidatingElement(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement(fragment);
console.error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement(null);
}
}
}
const didWarnAboutKeySpread = {};
export function jsxWithValidation(
type,
props,
key,
isStaticChildren,
source,
self,
) {
if (__DEV__) {
const validType = isValidElementType(type);
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
let info = '';
if (
type === undefined ||
(typeof type === 'object' &&
type !== null &&
Object.keys(type).length === 0)
) {
info +=
' You likely forgot to export your component from the file ' +
"it's defined in, or you might have mixed up default and named imports.";
}
const sourceInfo = getSourceInfoErrorAddendum(source);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
let typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = `<${getComponentNameFromType(type.type) || 'Unknown'} />`;
info =
' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
if (__DEV__) {
console.error(
'React.jsx: type is invalid -- expected a string (for ' +
'built-in components) or a class/function (for composite ' +
'components) but got: %s.%s',
typeString,
info,
);
}
}
const element = jsxDEV(type, props, key, source, self);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
const children = props.children;
if (children !== undefined) {
if (isStaticChildren) {
if (isArray(children)) {
for (let i = 0; i < children.length; i++) {
validateChildKeys(children[i], type);
}
if (Object.freeze) {
Object.freeze(children);
}
} else {
console.error(
'React.jsx: Static children should always be an array. ' +
'You are likely explicitly calling React.jsxs or React.jsxDEV. ' +
'Use the Babel transform instead.',
);
}
} else {
validateChildKeys(children, type);
}
}
}
if (hasOwnProperty.call(props, 'key')) {
const componentName = getComponentNameFromType(type);
const keys = Object.keys(props).filter(k => k !== 'key');
const beforeExample =
keys.length > 0
? '{key: someKey, ' + keys.join(': ..., ') + ': ...}'
: '{key: someKey}';
if (!didWarnAboutKeySpread[componentName + beforeExample]) {
const afterExample =
keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
console.error(
'A props object containing a "key" prop is being spread into JSX:\n' +
' let props = %s;\n' +
' <%s {...props} />\n' +
'React keys must be passed directly to JSX without using spread:\n' +
' let props = %s;\n' +
' <%s key={someKey} {...props} />',
beforeExample,
componentName,
afterExample,
componentName,
);
didWarnAboutKeySpread[componentName + beforeExample] = true;
}
}
if (type === REACT_FRAGMENT_TYPE) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
}
// These two functions exist to still get child warnings in dev
// even with the prod transform. This means that jsxDEV is purely
// opt-in behavior for better messages but that we won't stop
// giving you warnings if you use production apis.
export function jsxWithValidationStatic(type, props, key) {
return jsxWithValidation(type, props, key, true);
}
export function jsxWithValidationDynamic(type, props, key) {
return jsxWithValidation(type, props, key, false);
}
export function createElementWithValidation(type, props, children) {
const validType = isValidElementType(type);
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
let info = '';
if (
type === undefined ||
(typeof type === 'object' &&
type !== null &&
Object.keys(type).length === 0)
) {
info +=
' You likely forgot to export your component from the file ' +
"it's defined in, or you might have mixed up default and named imports.";
}
const sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
let typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = `<${getComponentNameFromType(type.type) || 'Unknown'} />`;
info =
' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
if (__DEV__) {
console.error(
'React.createElement: type is invalid -- expected a string (for ' +
'built-in components) or a class/function (for composite ' +
'components) but got: %s.%s',
typeString,
info,
);
}
}
const element = createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (let i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === REACT_FRAGMENT_TYPE) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
let didWarnAboutDeprecatedCreateFactory = false;
export function createFactoryWithValidation(type) {
const validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
if (__DEV__) {
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
console.warn(
'React.createFactory() is deprecated and will be removed in ' +
'a future major release. Consider using JSX ' +
'or use React.createElement() directly instead.',
);
}
// Legacy hook: remove it
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
console.warn(
'Factory.type is deprecated. Access the class directly ' +
'before passing it to createFactory.',
);
Object.defineProperty(this, 'type', {
value: type,
});
return type;
},
});
}
return validatedFactory;
}
export function cloneElementWithValidation(element, props, children) {
const newElement = cloneElement.apply(this, arguments);
for (let i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
| 29.848816 | 110 | 0.63041 |
Python-Penetration-Testing-Cookbook | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
// Note that this test uses React components declared in the "__source__" directory.
// This is done to control if and how the code is transformed at runtime.
// Do not declare test components within this test file as it is very fragile.
function expectHookNamesToEqual(map, expectedNamesArray) {
// Slightly hacky since it relies on the iterable order of values()
expect(Array.from(map.values())).toEqual(expectedNamesArray);
}
function requireText(path, encoding) {
const {existsSync, readFileSync} = require('fs');
if (existsSync(path)) {
return Promise.resolve(readFileSync(path, encoding));
} else {
return Promise.reject(`File not found "${path}"`);
}
}
function initFetchMock() {
const fetchMock = require('jest-fetch-mock');
fetchMock.enableMocks();
fetchMock.mockIf(/.+$/, request => {
const url = request.url;
const isLoadingExternalSourceMap = /external\/.*\.map/.test(url);
if (isLoadingExternalSourceMap) {
// Assert that url contains correct query params
expect(url.includes('?foo=bar¶m=some_value')).toBe(true);
const fileSystemPath = url.split('?')[0];
return requireText(fileSystemPath, 'utf8');
}
return requireText(url, 'utf8');
});
return fetchMock;
}
describe('parseHookNames', () => {
let fetchMock;
let inspectHooks;
let parseHookNames;
beforeEach(() => {
jest.resetModules();
jest.mock('source-map-support', () => {
console.trace('source-map-support');
});
fetchMock = initFetchMock();
inspectHooks =
require('react-debug-tools/src/ReactDebugHooks').inspectHooks;
// Jest can't run the workerized version of this module.
const {
flattenHooksList,
loadSourceAndMetadata,
} = require('../parseHookNames/loadSourceAndMetadata');
const parseSourceAndMetadata =
require('../parseHookNames/parseSourceAndMetadata').parseSourceAndMetadata;
parseHookNames = async hooksTree => {
const hooksList = flattenHooksList(hooksTree);
// Runs in the UI thread so it can share Network cache:
const locationKeyToHookSourceAndMetadata =
await loadSourceAndMetadata(hooksList);
// Runs in a Worker because it's CPU intensive:
return parseSourceAndMetadata(
hooksList,
locationKeyToHookSourceAndMetadata,
);
};
// Jest (jest-runner?) configures Errors to automatically account for source maps.
// This changes behavior between our tests and the browser.
// Ideally we would clear the prepareStackTrace() method on the Error object,
// but Node falls back to looking for it on the main context's Error constructor,
// which may still be patched.
// To ensure we get the default behavior, override prepareStackTrace ourselves.
// NOTE: prepareStackTrace is called from the error.stack getter, but the getter
// has a recursion breaker which falls back to the default behavior.
Error.prepareStackTrace = (error, trace) => {
return error.stack;
};
});
afterEach(() => {
fetch.resetMocks();
});
async function getHookNamesForComponent(Component, props = {}) {
const hooksTree = inspectHooks(Component, props, undefined, true);
const hookNames = await parseHookNames(hooksTree);
return hookNames;
}
it('should parse names for useState()', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithUseState').Component;
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, ['foo', 'bar', 'baz', null]);
});
it('should parse names for useReducer()', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithUseReducer').Component;
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, ['foo', 'bar', 'baz']);
});
it('should skip loading source files for unnamed hooks like useEffect', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithUseEffect').Component;
// Since this component contains only unnamed hooks, the source code should not even be loaded.
fetchMock.mockIf(/.+$/, request => {
throw Error(`Unexpected file request for "${request.url}"`);
});
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, []); // No hooks with names
});
it('should skip loading source files for unnamed hooks like useEffect (alternate)', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithExternalUseEffect').Component;
fetchMock.mockIf(/.+$/, request => {
// Since the custom hook contains only unnamed hooks, the source code should not be loaded.
if (request.url.endsWith('useCustom.js')) {
throw Error(`Unexpected file request for "${request.url}"`);
}
return requireText(request.url, 'utf8');
});
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, ['count', null]); // No hooks with names
});
it('should parse names for custom hooks', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithNamedCustomHooks').Component;
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'foo',
null, // Custom hooks can have names, but not when using destructuring.
'baz',
]);
});
it('should parse names for code using hooks indirectly', async () => {
const Component =
require('./__source__/__untransformed__/ComponentUsingHooksIndirectly').Component;
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, ['count', 'darkMode', 'isDarkMode']);
});
it('should parse names for code using nested hooks', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithNestedHooks').Component;
let InnerComponent;
const hookNames = await getHookNamesForComponent(Component, {
callback: innerComponent => {
InnerComponent = innerComponent;
},
});
const innerHookNames = await getHookNamesForComponent(InnerComponent);
expectHookNamesToEqual(hookNames, ['InnerComponent']);
expectHookNamesToEqual(innerHookNames, ['state']);
});
it('should return null for custom hooks without explicit names', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithUnnamedCustomHooks').Component;
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
null, // Custom hooks can have names, but this one does not even return a value.
null, // Custom hooks can have names, but not when using destructuring.
null, // Custom hooks can have names, but not when using destructuring.
]);
});
// TODO Test that cache purge works
// TODO Test that cached metadata is purged when Fast Refresh scheduled
describe('inline, external and bundle source maps', () => {
it('should work for simple components', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState
]);
}
await test('./__source__/Example'); // original source (uncompiled)
await test('./__source__/__compiled__/inline/Example'); // inline source map
await test('./__source__/__compiled__/external/Example'); // external source map
await test('./__source__/__compiled__/inline/index-map/Example'); // inline index map source map
await test('./__source__/__compiled__/external/index-map/Example'); // external index map source map
await test('./__source__/__compiled__/bundle/index', 'Example'); // bundle source map
await test('./__source__/__compiled__/no-columns/Example'); // simulated Webpack 'cheap-module-source-map'
});
it('should work with more complex files and components', async () => {
async function test(path, name = undefined) {
const components = name != null ? require(path)[name] : require(path);
let hookNames = await getHookNamesForComponent(components.List);
expectHookNamesToEqual(hookNames, [
'newItemText', // useState
'items', // useState
'uid', // useState
'handleClick', // useCallback
'handleKeyPress', // useCallback
'handleChange', // useCallback
'removeItem', // useCallback
'toggleItem', // useCallback
]);
hookNames = await getHookNamesForComponent(components.ListItem, {
item: {},
});
expectHookNamesToEqual(hookNames, [
'handleDelete', // useCallback
'handleToggle', // useCallback
]);
}
await test('./__source__/ToDoList'); // original source (uncompiled)
await test('./__source__/__compiled__/inline/ToDoList'); // inline source map
await test('./__source__/__compiled__/external/ToDoList'); // external source map
await test('./__source__/__compiled__/inline/index-map/ToDoList'); // inline index map source map
await test('./__source__/__compiled__/external/index-map/ToDoList'); // external index map source map
await test('./__source__/__compiled__/bundle', 'ToDoList'); // bundle source map
await test('./__source__/__compiled__/no-columns/ToDoList'); // simulated Webpack 'cheap-module-source-map'
});
it('should work for custom hook', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
'isDarkMode', // useIsDarkMode()
'isDarkMode', // useIsDarkMode -> useState()
null, // useFoo()
]);
}
await test('./__source__/ComponentWithCustomHook'); // original source (uncompiled)
await test('./__source__/__compiled__/inline/ComponentWithCustomHook'); // inline source map
await test('./__source__/__compiled__/external/ComponentWithCustomHook'); // external source map
await test(
'./__source__/__compiled__/inline/index-map/ComponentWithCustomHook',
); // inline index map source map
await test(
'./__source__/__compiled__/external/index-map/ComponentWithCustomHook',
); // external index map source map
await test('./__source__/__compiled__/bundle', 'ComponentWithCustomHook'); // bundle source map
await test(
'./__source__/__compiled__/no-columns/ComponentWithCustomHook',
); // simulated Webpack 'cheap-module-source-map'
});
it('should work when code is using hooks indirectly', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
'darkMode', // useDarkMode()
'isDarkMode', // useState()
]);
}
await test(
'./__source__/__compiled__/inline/ComponentUsingHooksIndirectly',
); // inline source map
await test(
'./__source__/__compiled__/external/ComponentUsingHooksIndirectly',
); // external source map
await test(
'./__source__/__compiled__/inline/index-map/ComponentUsingHooksIndirectly',
); // inline index map source map
await test(
'./__source__/__compiled__/external/index-map/ComponentUsingHooksIndirectly',
); // external index map source map
await test(
'./__source__/__compiled__/bundle',
'ComponentUsingHooksIndirectly',
); // bundle source map
await test(
'./__source__/__compiled__/no-columns/ComponentUsingHooksIndirectly',
); // simulated Webpack 'cheap-module-source-map'
});
it('should work when code is using nested hooks', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
let InnerComponent;
const hookNames = await getHookNamesForComponent(Component, {
callback: innerComponent => {
InnerComponent = innerComponent;
},
});
const innerHookNames = await getHookNamesForComponent(InnerComponent);
expectHookNamesToEqual(hookNames, [
'InnerComponent', // useMemo()
]);
expectHookNamesToEqual(innerHookNames, [
'state', // useState()
]);
}
await test('./__source__/__compiled__/inline/ComponentWithNestedHooks'); // inline source map
await test('./__source__/__compiled__/external/ComponentWithNestedHooks'); // external source map
await test(
'./__source__/__compiled__/inline/index-map/ComponentWithNestedHooks',
); // inline index map source map
await test(
'./__source__/__compiled__/external/index-map/ComponentWithNestedHooks',
); // external index map source map
await test(
'./__source__/__compiled__/bundle',
'ComponentWithNestedHooks',
); // bundle source map
await test(
'./__source__/__compiled__/no-columns/ComponentWithNestedHooks',
); // simulated Webpack 'cheap-module-source-map'
});
it('should work for external hooks', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'theme', // useTheme()
'theme', // useContext()
]);
}
// We can't test the uncompiled source here, because it either needs to get transformed,
// which would break the source mapping, or the import statements will fail.
await test(
'./__source__/__compiled__/inline/ComponentWithExternalCustomHooks',
); // inline source map
await test(
'./__source__/__compiled__/external/ComponentWithExternalCustomHooks',
); // external source map
await test(
'./__source__/__compiled__/inline/index-map/ComponentWithExternalCustomHooks',
); // inline index map source map
await test(
'./__source__/__compiled__/external/index-map/ComponentWithExternalCustomHooks',
); // external index map source map
await test(
'./__source__/__compiled__/bundle',
'ComponentWithExternalCustomHooks',
); // bundle source map
await test(
'./__source__/__compiled__/no-columns/ComponentWithExternalCustomHooks',
); // simulated Webpack 'cheap-module-source-map'
});
it('should work when multiple hooks are on a line', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'a', // useContext()
'b', // useContext()
'c', // useContext()
'd', // useContext()
]);
}
await test(
'./__source__/__compiled__/inline/ComponentWithMultipleHooksPerLine',
); // inline source map
await test(
'./__source__/__compiled__/external/ComponentWithMultipleHooksPerLine',
); // external source map
await test(
'./__source__/__compiled__/inline/index-map/ComponentWithMultipleHooksPerLine',
); // inline index map source map
await test(
'./__source__/__compiled__/external/index-map/ComponentWithMultipleHooksPerLine',
); // external index map source map
await test(
'./__source__/__compiled__/bundle',
'ComponentWithMultipleHooksPerLine',
); // bundle source map
async function noColumnTest(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'a', // useContext()
'b', // useContext()
null, // useContext()
null, // useContext()
]);
}
// Note that this test is expected to only match the first two hooks
// because the 3rd and 4th hook are on the same line,
// and this type of source map doesn't have column numbers.
await noColumnTest(
'./__source__/__compiled__/no-columns/ComponentWithMultipleHooksPerLine',
); // simulated Webpack 'cheap-module-source-map'
});
// TODO Inline require (e.g. require("react").useState()) isn't supported yet.
// Maybe this isn't an important use case to support,
// since inline requires are most likely to exist in compiled source (if at all).
xit('should work for inline requires', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
]);
}
await test('./__source__/InlineRequire'); // original source (uncompiled)
await test('./__source__/__compiled__/inline/InlineRequire'); // inline source map
await test('./__source__/__compiled__/external/InlineRequire'); // external source map
await test('./__source__/__compiled__/inline/index-map/InlineRequire'); // inline index map source map
await test('./__source__/__compiled__/external/index-map/InlineRequire'); // external index map source map
await test('./__source__/__compiled__/bundle', 'InlineRequire'); // bundle source map
await test('./__source__/__compiled__/no-columns/InlineRequire'); // simulated Webpack 'cheap-module-source-map'
});
it('should support sources that contain the string "sourceMappingURL="', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
]);
}
// We expect the inline sourceMappingURL to be invalid in this case; mute the warning.
console.warn = () => {};
await test('./__source__/ContainingStringSourceMappingURL'); // original source (uncompiled)
await test(
'./__source__/__compiled__/inline/ContainingStringSourceMappingURL',
); // inline source map
await test(
'./__source__/__compiled__/external/ContainingStringSourceMappingURL',
); // external source map
await test(
'./__source__/__compiled__/inline/index-map/ContainingStringSourceMappingURL',
); // inline index map source map
await test(
'./__source__/__compiled__/external/index-map/ContainingStringSourceMappingURL',
); // external index map source map
await test(
'./__source__/__compiled__/bundle',
'ContainingStringSourceMappingURL',
); // bundle source map
await test(
'./__source__/__compiled__/no-columns/ContainingStringSourceMappingURL',
); // simulated Webpack 'cheap-module-source-map'
});
});
describe('extended source maps', () => {
beforeEach(() => {
const babelParser = require('@babel/parser');
const generateHookMapModule = require('../generateHookMap');
jest.spyOn(babelParser, 'parse');
jest.spyOn(generateHookMapModule, 'decodeHookMap');
});
it('should work for simple components', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
await test(
'./__source__/__compiled__/inline/fb-sources-extended/Example',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/Example',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/Example',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/Example',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/Example',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/Example',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/Example',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/Example',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
it('should work with more complex files and components', async () => {
async function test(path, name = undefined) {
const components = name != null ? require(path)[name] : require(path);
let hookNames = await getHookNamesForComponent(components.List);
expectHookNamesToEqual(hookNames, [
'newItemText', // useState
'items', // useState
'uid', // useState
'handleClick', // useCallback
'handleKeyPress', // useCallback
'handleChange', // useCallback
'removeItem', // useCallback
'toggleItem', // useCallback
]);
hookNames = await getHookNamesForComponent(components.ListItem, {
item: {},
});
expectHookNamesToEqual(hookNames, [
'handleDelete', // useCallback
'handleToggle', // useCallback
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
await test(
'./__source__/__compiled__/inline/fb-sources-extended/ToDoList',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/ToDoList',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/ToDoList',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/ToDoList',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/ToDoList',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/ToDoList',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/ToDoList',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/ToDoList',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
it('should work for custom hook', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
'isDarkMode', // useIsDarkMode()
'isDarkMode', // useIsDarkMode -> useState()
null, // isFoo()
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
await test(
'./__source__/__compiled__/inline/fb-sources-extended/ComponentWithCustomHook',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/ComponentWithCustomHook',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/ComponentWithCustomHook',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/ComponentWithCustomHook',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/ComponentWithCustomHook',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/ComponentWithCustomHook',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/ComponentWithCustomHook',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/ComponentWithCustomHook',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
it('should work when code is using hooks indirectly', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
'darkMode', // useDarkMode()
'isDarkMode', // useState()
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
await test(
'./__source__/__compiled__/inline/fb-sources-extended/ComponentUsingHooksIndirectly',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/ComponentUsingHooksIndirectly',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/ComponentUsingHooksIndirectly',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/ComponentUsingHooksIndirectly',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/ComponentUsingHooksIndirectly',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/ComponentUsingHooksIndirectly',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/ComponentUsingHooksIndirectly',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/ComponentUsingHooksIndirectly',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
it('should work when code is using nested hooks', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
let InnerComponent;
const hookNames = await getHookNamesForComponent(Component, {
callback: innerComponent => {
InnerComponent = innerComponent;
},
});
const innerHookNames = await getHookNamesForComponent(InnerComponent);
expectHookNamesToEqual(hookNames, [
'InnerComponent', // useMemo()
]);
expectHookNamesToEqual(innerHookNames, [
'state', // useState()
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
await test(
'./__source__/__compiled__/inline/fb-sources-extended/ComponentWithNestedHooks',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/ComponentWithNestedHooks',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/ComponentWithNestedHooks',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/ComponentWithNestedHooks',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/ComponentWithNestedHooks',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/ComponentWithNestedHooks',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/ComponentWithNestedHooks',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/ComponentWithNestedHooks',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
it('should work for external hooks', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'theme', // useTheme()
'theme', // useContext()
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
// We can't test the uncompiled source here, because it either needs to get transformed,
// which would break the source mapping, or the import statements will fail.
await test(
'./__source__/__compiled__/inline/fb-sources-extended/ComponentWithExternalCustomHooks',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/ComponentWithExternalCustomHooks',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/ComponentWithExternalCustomHooks',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/ComponentWithExternalCustomHooks',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/ComponentWithExternalCustomHooks',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/ComponentWithExternalCustomHooks',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/ComponentWithExternalCustomHooks',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/ComponentWithExternalCustomHooks',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
it('should work when multiple hooks are on a line', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'a', // useContext()
'b', // useContext()
'c', // useContext()
'd', // useContext()
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
await test(
'./__source__/__compiled__/inline/fb-sources-extended/ComponentWithMultipleHooksPerLine',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/ComponentWithMultipleHooksPerLine',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/ComponentWithMultipleHooksPerLine',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/ComponentWithMultipleHooksPerLine',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/ComponentWithMultipleHooksPerLine',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/ComponentWithMultipleHooksPerLine',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/ComponentWithMultipleHooksPerLine',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/ComponentWithMultipleHooksPerLine',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
// TODO Inline require (e.g. require("react").useState()) isn't supported yet.
// Maybe this isn't an important use case to support,
// since inline requires are most likely to exist in compiled source (if at all).
xit('should work for inline requires', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
await test(
'./__source__/__compiled__/inline/fb-sources-extended/InlineRequire',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/InlineRequire',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/InlineRequire',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/InlineRequire',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/InlineRequire',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/InlineRequire',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/InlineRequire',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/InlineRequire',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
it('should support sources that contain the string "sourceMappingURL="', async () => {
async function test(path, name = 'Component') {
const Component = require(path)[name];
const hookNames = await getHookNamesForComponent(Component);
expectHookNamesToEqual(hookNames, [
'count', // useState()
]);
expect(require('@babel/parser').parse).toHaveBeenCalledTimes(0);
expect(require('../generateHookMap').decodeHookMap).toHaveBeenCalled();
}
// We expect the inline sourceMappingURL to be invalid in this case; mute the warning.
console.warn = () => {};
await test(
'./__source__/__compiled__/inline/fb-sources-extended/ContainingStringSourceMappingURL',
); // x_facebook_sources extended inline source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/ContainingStringSourceMappingURL',
); // x_facebook_sources extended external source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/ContainingStringSourceMappingURL',
); // x_react_sources extended inline source map
await test(
'./__source__/__compiled__/external/react-sources-extended/ContainingStringSourceMappingURL',
); // x_react_sources extended external source map
// Using index map format for source maps
await test(
'./__source__/__compiled__/inline/fb-sources-extended/index-map/ContainingStringSourceMappingURL',
); // x_facebook_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/fb-sources-extended/index-map/ContainingStringSourceMappingURL',
); // x_facebook_sources extended external index map source map
await test(
'./__source__/__compiled__/inline/react-sources-extended/index-map/ContainingStringSourceMappingURL',
); // x_react_sources extended inline index map source map
await test(
'./__source__/__compiled__/external/react-sources-extended/index-map/ContainingStringSourceMappingURL',
); // x_react_sources extended external index map source map
// TODO test no-columns and bundle cases with extended source maps
});
});
});
describe('parseHookNames worker', () => {
let inspectHooks;
let parseHookNames;
let workerizedParseSourceAndMetadataMock;
beforeEach(() => {
window.Worker = undefined;
workerizedParseSourceAndMetadataMock = jest.fn();
initFetchMock();
jest.mock('../parseHookNames/parseSourceAndMetadata.worker.js', () => {
return {
__esModule: true,
default: () => ({
parseSourceAndMetadata: workerizedParseSourceAndMetadataMock,
}),
};
});
inspectHooks =
require('react-debug-tools/src/ReactDebugHooks').inspectHooks;
parseHookNames = require('../parseHookNames').parseHookNames;
});
async function getHookNamesForComponent(Component, props = {}) {
const hooksTree = inspectHooks(Component, props, undefined, true);
const hookNames = await parseHookNames(hooksTree);
return hookNames;
}
it('should use worker', async () => {
const Component =
require('./__source__/__untransformed__/ComponentWithUseState').Component;
window.Worker = true;
// Reset module so mocked worker instance can be updated.
jest.resetModules();
parseHookNames = require('../parseHookNames').parseHookNames;
await getHookNamesForComponent(Component);
expect(workerizedParseSourceAndMetadataMock).toHaveBeenCalledTimes(1);
});
});
| 42.523158 | 118 | 0.647076 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
const ReactSharedServerInternals =
// $FlowFixMe: It's defined in the one we resolve to.
React.__SECRET_SERVER_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
if (!ReactSharedServerInternals) {
throw new Error(
'The "react" package in this environment is not configured correctly. ' +
'The "react-server" condition must be enabled in any environment that ' +
'runs React Server Components.',
);
}
export default ReactSharedServerInternals;
| 26.96 | 79 | 0.713467 |
null | #!/usr/bin/env node
'use strict';
const clear = require('clear');
const {confirm} = require('../utils');
const theme = require('../theme');
const run = async ({cwd, packages, skipPackages, tags}) => {
if (skipPackages.length === 0) {
return;
}
clear();
console.log(
theme`{spinnerSuccess ✓} The following packages will not be published as part of this release`
);
skipPackages.forEach(packageName => {
console.log(theme`• {package ${packageName}}`);
});
await confirm('Do you want to proceed?');
clear();
};
// Run this directly because it's fast,
// and logPromise would interfere with console prompting.
module.exports = run;
| 19.875 | 98 | 0.656672 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
process.on('unhandledRejection', err => {
throw err;
});
const runFlow = require('../flow/runFlow');
const inlinedHostConfigs = require('../shared/inlinedHostConfigs');
// Parallelize tests across multiple tasks.
const nodeTotal = process.env.CIRCLE_NODE_TOTAL
? parseInt(process.env.CIRCLE_NODE_TOTAL, 10)
: 1;
const nodeIndex = process.env.CIRCLE_NODE_INDEX
? parseInt(process.env.CIRCLE_NODE_INDEX, 10)
: 0;
async function checkAll() {
for (let i = 0; i < inlinedHostConfigs.length; i++) {
if (i % nodeTotal === nodeIndex) {
const rendererInfo = inlinedHostConfigs[i];
if (rendererInfo.isFlowTyped) {
await runFlow(rendererInfo.shortName, ['check']);
console.log();
}
}
}
}
checkAll();
| 24.184211 | 67 | 0.674686 |
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
*/
type ColorSpace = number | {min: number, max: number, count?: number};
// Docstrings from https://www.w3schools.com/css/css_colors_hsl.asp
type HslaColor = $ReadOnly<{
/** Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue. */
h: number,
/** Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color. */
s: number,
/** Lightness is a percentage, 0% is black, 50% is neither light or dark, 100% is white. */
l: number,
/** Alpha is a percentage, 0% is fully transparent, and 100 is not transparent at all. */
a: number,
}>;
export function hslaColorToString({h, s, l, a}: HslaColor): string {
return `hsl(${h}deg ${s}% ${l}% / ${a})`;
}
export function dimmedColor(color: HslaColor, dimDelta: number): HslaColor {
return {
...color,
l: color.l - dimDelta,
};
}
// Source: https://source.chromium.org/chromium/chromium/src/+/master:out/Debug/gen/devtools/platform/utilities.js;l=120
function hashCode(string: string): number {
// Hash algorithm for substrings is described in "Über die Komplexität der Multiplikation in
// eingeschränkten Branchingprogrammmodellen" by Woelfe.
// http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000
const p = (1 << 30) * 4 - 5; // prime: 2^32 - 5
const z = 0x5033d967; // 32 bits from random.org
const z2 = 0x59d2f15d; // random odd 32 bit number
let s = 0;
let zi = 1;
for (let i = 0; i < string.length; i++) {
const xi = string.charCodeAt(i) * z2;
s = (s + zi * xi) % p;
zi = (zi * z) % p;
}
s = (s + zi * (p - 1)) % p;
return Math.abs(s | 0);
}
function indexToValueInSpace(index: number, space: ColorSpace): number {
if (typeof space === 'number') {
return space;
}
const count = space.count || space.max - space.min;
index %= count;
return (
space.min + Math.floor((index / (count - 1)) * (space.max - space.min))
);
}
/**
* Deterministic color generator.
*
* Adapted from: https://source.chromium.org/chromium/chromium/src/+/master:out/Debug/gen/devtools/common/Color.js
*/
export class ColorGenerator {
_hueSpace: ColorSpace;
_satSpace: ColorSpace;
_lightnessSpace: ColorSpace;
_alphaSpace: ColorSpace;
_colors: Map<string, HslaColor>;
constructor(
hueSpace?: ColorSpace,
satSpace?: ColorSpace,
lightnessSpace?: ColorSpace,
alphaSpace?: ColorSpace,
) {
this._hueSpace = hueSpace || {min: 0, max: 360};
this._satSpace = satSpace || 67;
this._lightnessSpace = lightnessSpace || 80;
this._alphaSpace = alphaSpace || 1;
this._colors = new Map();
}
setColorForID(id: string, color: HslaColor) {
this._colors.set(id, color);
}
colorForID(id: string): HslaColor {
const cachedColor = this._colors.get(id);
if (cachedColor) {
return cachedColor;
}
const color = this._generateColorForID(id);
this._colors.set(id, color);
return color;
}
_generateColorForID(id: string): HslaColor {
const hash = hashCode(id);
return {
h: indexToValueInSpace(hash, this._hueSpace),
s: indexToValueInSpace(hash >> 8, this._satSpace),
l: indexToValueInSpace(hash >> 16, this._lightnessSpace),
a: indexToValueInSpace(hash >> 24, this._alphaSpace),
};
}
}
| 29.877193 | 120 | 0.653879 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
*/
import * as Scheduler from './Scheduler';
import type {Callback, Task} from './Scheduler';
import type {PriorityLevel} from '../SchedulerPriorities';
import typeof * as SchedulerExportsType from './Scheduler';
import typeof * as SchedulerNativeExportsType from './SchedulerNative';
// This type is supposed to reflect the actual methods and arguments currently supported by the C++ implementation:
// https://github.com/facebook/react-native/blob/main/packages/react-native/ReactCommon/react/renderer/runtimescheduler/RuntimeSchedulerBinding.cpp
type NativeSchedulerType = {
unstable_ImmediatePriority: PriorityLevel,
unstable_UserBlockingPriority: PriorityLevel,
unstable_NormalPriority: PriorityLevel,
unstable_IdlePriority: PriorityLevel,
unstable_LowPriority: PriorityLevel,
unstable_scheduleCallback: (
priorityLevel: PriorityLevel,
callback: Callback,
) => Task,
unstable_cancelCallback: (task: Task) => void,
unstable_getCurrentPriorityLevel: () => PriorityLevel,
unstable_shouldYield: () => boolean,
unstable_requestPaint: () => void,
unstable_now: () => DOMHighResTimeStamp,
};
declare var nativeRuntimeScheduler: void | NativeSchedulerType;
export const unstable_UserBlockingPriority: PriorityLevel =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_UserBlockingPriority
: Scheduler.unstable_UserBlockingPriority;
export const unstable_NormalPriority: PriorityLevel =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_NormalPriority
: Scheduler.unstable_NormalPriority;
export const unstable_IdlePriority: PriorityLevel =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_IdlePriority
: Scheduler.unstable_IdlePriority;
export const unstable_LowPriority: PriorityLevel =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_LowPriority
: Scheduler.unstable_LowPriority;
export const unstable_ImmediatePriority: PriorityLevel =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_ImmediatePriority
: Scheduler.unstable_ImmediatePriority;
export const unstable_scheduleCallback: (
priorityLevel: PriorityLevel,
callback: Callback,
) => Task =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_scheduleCallback
: Scheduler.unstable_scheduleCallback;
export const unstable_cancelCallback: (task: Task) => void =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_cancelCallback
: Scheduler.unstable_cancelCallback;
export const unstable_getCurrentPriorityLevel: () => PriorityLevel =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_getCurrentPriorityLevel
: Scheduler.unstable_getCurrentPriorityLevel;
export const unstable_shouldYield: () => boolean =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_shouldYield
: Scheduler.unstable_shouldYield;
export const unstable_requestPaint: () => void =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_requestPaint
: Scheduler.unstable_requestPaint;
export const unstable_now: () => number | DOMHighResTimeStamp =
typeof nativeRuntimeScheduler !== 'undefined'
? nativeRuntimeScheduler.unstable_now
: Scheduler.unstable_now;
// These were never implemented on the native scheduler because React never calls them.
// For consistency, let's disable them altogether and make them throw.
export const unstable_next: any = throwNotImplemented;
export const unstable_runWithPriority: any = throwNotImplemented;
export const unstable_wrapCallback: any = throwNotImplemented;
export const unstable_continueExecution: any = throwNotImplemented;
export const unstable_pauseExecution: any = throwNotImplemented;
export const unstable_getFirstCallbackNode: any = throwNotImplemented;
export const unstable_forceFrameRate: any = throwNotImplemented;
export const unstable_Profiling: any = null;
function throwNotImplemented() {
throw Error('Not implemented.');
}
// Flow magic to verify the exports of this file match the original version.
export type {Callback, Task};
((((null: any): SchedulerExportsType): SchedulerNativeExportsType): SchedulerExportsType);
| 39.460177 | 147 | 0.783417 |
owtf | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import * as React from 'react';
// import {renderToString} from 'react-dom/server';
import {renderToPipeableStream} from 'react-dom/server';
import App from '../src/App';
import {DataProvider} from '../src/data';
import {API_DELAY, ABORT_DELAY} from './delays';
// In a real setup, you'd read it from webpack build stats.
let assets = {
'main.js': '/main.js',
'main.css': '/main.css',
};
module.exports = function render(url, res) {
const data = createServerData();
// This is how you would wire it up previously:
//
// res.send(
// '<!DOCTYPE html>' +
// renderToString(
// <DataProvider data={data}>
// <App assets={assets} />
// </DataProvider>,
// )
// );
// The new wiring is a bit more involved.
res.socket.on('error', error => {
console.error('Fatal', error);
});
let didError = false;
const {pipe, abort} = renderToPipeableStream(
<DataProvider data={data}>
<App assets={assets} />
</DataProvider>,
{
bootstrapScripts: [assets['main.js']],
onAllReady() {
// Full completion.
// You can use this for SSG or crawlers.
},
onShellReady() {
// If something errored before we started streaming, we set the error code appropriately.
res.statusCode = didError ? 500 : 200;
res.setHeader('Content-type', 'text/html');
pipe(res);
},
onShellError(x) {
// Something errored before we could complete the shell so we emit an alternative shell.
res.statusCode = 500;
res.send('<!doctype><p>Error</p>');
},
onError(x) {
didError = true;
console.error(x);
},
}
);
// Abandon and switch to client rendering if enough time passes.
// Try lowering this to see the client recover.
setTimeout(abort, ABORT_DELAY);
};
// Simulate a delay caused by data fetching.
// We fake this because the streaming HTML renderer
// is not yet integrated with real data fetching strategies.
function createServerData() {
let done = false;
let promise = null;
return {
read() {
if (done) {
return;
}
if (promise) {
throw promise;
}
promise = new Promise(resolve => {
setTimeout(() => {
done = true;
promise = null;
resolve();
}, API_DELAY);
});
throw promise;
},
};
}
| 25.690722 | 97 | 0.594281 |
AggressorAssessor | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import LoadingAnimation from 'react-devtools-shared/src/devtools/views/Components/LoadingAnimation';
import styles from './shared.css';
export default function SearchingGitHubIssues(): React.Node {
return (
<div className={styles.GitHubLinkRow}>
<LoadingAnimation className={styles.LoadingIcon} />
Searching GitHub for reports of this error...
</div>
);
}
| 27.090909 | 100 | 0.71799 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
describe('ReactDOMFrameScheduling', () => {
beforeEach(() => {
jest.resetModules();
jest.unmock('scheduler');
});
// We're just testing importing, not using it.
// It is important because even isomorphic components may import it.
it('can import findDOMNode in Node environment', () => {
const prevWindow = global.window;
try {
// Simulate the Node environment:
delete global.window;
jest.resetModules();
expect(() => {
require('react-dom');
}).not.toThrow();
} finally {
global.window = prevWindow;
}
});
});
| 22.542857 | 70 | 0.624544 |
Hands-On-Penetration-Testing-with-Python | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
const {useMemo, useState} = require('react');
function Component(props) {
const InnerComponent = useMemo(() => () => {
const [state] = useState(0);
return state;
});
props.callback(InnerComponent);
return null;
}
module.exports = {Component};
| 19.304348 | 66 | 0.66309 |
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 {useLayoutEffect, useRef} from 'react';
const TOOLTIP_OFFSET_BOTTOM = 10;
const TOOLTIP_OFFSET_TOP = 5;
export default function useSmartTooltip({
canvasRef,
mouseX,
mouseY,
}: {
canvasRef: {current: HTMLCanvasElement | null},
mouseX: number,
mouseY: number,
}): {current: HTMLElement | null} {
const ref = useRef<HTMLElement | null>(null);
// HACK: Browser extension reports window.innerHeight of 0,
// so we fallback to using the tooltip target element.
let height = window.innerHeight;
let width = window.innerWidth;
const target = canvasRef.current;
if (target !== null) {
const rect = target.getBoundingClientRect();
height = rect.top + rect.height;
width = rect.left + rect.width;
}
useLayoutEffect(() => {
const element = ref.current;
if (element !== null) {
// Let's check the vertical position.
if (mouseY + TOOLTIP_OFFSET_BOTTOM + element.offsetHeight >= height) {
// The tooltip doesn't fit below the mouse cursor (which is our
// default strategy). Therefore we try to position it either above the
// mouse cursor or finally aligned with the window's top edge.
if (mouseY - TOOLTIP_OFFSET_TOP - element.offsetHeight > 0) {
// We position the tooltip above the mouse cursor if it fits there.
element.style.top = `${
mouseY - element.offsetHeight - TOOLTIP_OFFSET_TOP
}px`;
} else {
// Otherwise we align the tooltip with the window's top edge.
element.style.top = '0px';
}
} else {
element.style.top = `${mouseY + TOOLTIP_OFFSET_BOTTOM}px`;
}
// Now let's check the horizontal position.
if (mouseX + TOOLTIP_OFFSET_BOTTOM + element.offsetWidth >= width) {
// The tooltip doesn't fit at the right of the mouse cursor (which is
// our default strategy). Therefore we try to position it either at the
// left of the mouse cursor or finally aligned with the window's left
// edge.
if (mouseX - TOOLTIP_OFFSET_TOP - element.offsetWidth > 0) {
// We position the tooltip at the left of the mouse cursor if it fits
// there.
element.style.left = `${
mouseX - element.offsetWidth - TOOLTIP_OFFSET_TOP
}px`;
} else {
// Otherwise, align the tooltip with the window's left edge.
element.style.left = '0px';
}
} else {
element.style.left = `${mouseX + TOOLTIP_OFFSET_BOTTOM}px`;
}
}
});
return ref;
}
| 32.878049 | 79 | 0.625855 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {CustomConsole} from '@jest/console';
import type {
BackendBridge,
FrontendBridge,
} from 'react-devtools-shared/src/bridge';
// Argument is serialized when passed from jest-cli script through to setupTests.
const compactConsole = process.env.compactConsole === 'true';
if (compactConsole) {
const formatter = (type, message) => {
switch (type) {
case 'error':
return '\x1b[31m' + message + '\x1b[0m';
case 'warn':
return '\x1b[33m' + message + '\x1b[0m';
case 'log':
default:
return message;
}
};
global.console = new CustomConsole(process.stdout, process.stderr, formatter);
}
beforeEach(() => {
global.mockClipboardCopy = jest.fn();
// Test environment doesn't support document methods like execCommand()
// Also once the backend components below have been required,
// it's too late for a test to mock the clipboard-js modules.
jest.mock('clipboard-js', () => ({copy: global.mockClipboardCopy}));
// These files should be required (and re-required) before each test,
// rather than imported at the head of the module.
// That's because we reset modules between tests,
// which disconnects the DevTool's cache from the current dispatcher ref.
const Agent = require('react-devtools-shared/src/backend/agent').default;
const {initBackend} = require('react-devtools-shared/src/backend');
const Bridge = require('react-devtools-shared/src/bridge').default;
const Store = require('react-devtools-shared/src/devtools/store').default;
const {installHook} = require('react-devtools-shared/src/hook');
const {
getDefaultComponentFilters,
setSavedComponentFilters,
} = require('react-devtools-shared/src/utils');
// Fake timers let us flush Bridge operations between setup and assertions.
jest.useFakeTimers();
// Use utils.js#withErrorsOrWarningsIgnored instead of directly mutating this array.
global._ignoredErrorOrWarningMessages = [];
function shouldIgnoreConsoleErrorOrWarn(args) {
let firstArg = args[0];
if (
firstArg !== null &&
typeof firstArg === 'object' &&
String(firstArg).indexOf('Error: Uncaught [') === 0
) {
firstArg = String(firstArg);
} else if (typeof firstArg !== 'string') {
return false;
}
const shouldFilter = global._ignoredErrorOrWarningMessages.some(
errorOrWarningMessage => {
return firstArg.indexOf(errorOrWarningMessage) !== -1;
},
);
return shouldFilter;
}
const originalConsoleError = console.error;
console.error = (...args) => {
const firstArg = args[0];
if (
firstArg === 'Warning: React instrumentation encountered an error: %s'
) {
// Rethrow errors from React.
throw args[1];
} else if (
typeof firstArg === 'string' &&
(firstArg.startsWith(
"Warning: It looks like you're using the wrong act()",
) ||
firstArg.startsWith(
'Warning: The current testing environment is not configured to support act',
) ||
firstArg.startsWith(
'Warning: You seem to have overlapping act() calls',
))
) {
// DevTools intentionally wraps updates with acts from both DOM and test-renderer,
// since test updates are expected to impact both renderers.
return;
} else if (shouldIgnoreConsoleErrorOrWarn(args)) {
// Allows testing how DevTools behaves when it encounters console.error without cluttering the test output.
// Errors can be ignored by running in a special context provided by utils.js#withErrorsOrWarningsIgnored
return;
}
originalConsoleError.apply(console, args);
};
const originalConsoleWarn = console.warn;
console.warn = (...args) => {
if (shouldIgnoreConsoleErrorOrWarn(args)) {
// Allows testing how DevTools behaves when it encounters console.warn without cluttering the test output.
// Warnings can be ignored by running in a special context provided by utils.js#withErrorsOrWarningsIgnored
return;
}
originalConsoleWarn.apply(console, args);
};
// Initialize filters to a known good state.
setSavedComponentFilters(getDefaultComponentFilters());
global.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = getDefaultComponentFilters();
// Also initialize inline warnings so that we can test them.
global.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = true;
installHook(global);
const bridgeListeners = [];
const bridge = new Bridge({
listen(callback) {
bridgeListeners.push(callback);
return () => {
const index = bridgeListeners.indexOf(callback);
if (index >= 0) {
bridgeListeners.splice(index, 1);
}
};
},
send(event: string, payload: any, transferable?: Array<any>) {
bridgeListeners.forEach(callback => callback({event, payload}));
},
});
const agent = new Agent(((bridge: any): BackendBridge));
const hook = global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
initBackend(hook, agent, global);
const store = new Store(((bridge: any): FrontendBridge));
global.agent = agent;
global.bridge = bridge;
global.store = store;
const readFileSync = require('fs').readFileSync;
async function mockFetch(url) {
return {
ok: true,
status: 200,
text: async () => readFileSync(__dirname + url, 'utf-8'),
};
}
global.fetch = mockFetch;
});
afterEach(() => {
delete global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
// It's important to reset modules between test runs;
// Without this, ReactDOM won't re-inject itself into the new hook.
// It's also important to reset after tests, rather than before,
// so that we don't disconnect the ReactCurrentDispatcher ref.
jest.resetModules();
});
| 32.561798 | 113 | 0.673196 |
owtf | /*!
* Based on 'silvenon/remark-smartypants'
* https://github.com/silvenon/remark-smartypants/pull/80
*/
const visit = require('unist-util-visit');
const retext = require('retext');
const smartypants = require('retext-smartypants');
function check(parent) {
if (parent.tagName === 'script') return false;
if (parent.tagName === 'style') return false;
return true;
}
module.exports = function (options) {
const processor = retext().use(smartypants, {
...options,
// Do not replace ellipses, dashes, backticks because they change string
// length, and we couldn't guarantee right splice of text in second visit of
// tree
ellipses: false,
dashes: false,
backticks: false,
});
const processor2 = retext().use(smartypants, {
...options,
// Do not replace quotes because they are already replaced in the first
// processor
quotes: false,
});
function transformer(tree) {
let allText = '';
let startIndex = 0;
const textOrInlineCodeNodes = [];
visit(tree, ['text', 'inlineCode'], (node, _, parent) => {
if (check(parent)) {
if (node.type === 'text') allText += node.value;
// for the case when inlineCode contains just one part of quote: `foo'bar`
else allText += 'A'.repeat(node.value.length);
textOrInlineCodeNodes.push(node);
}
});
// Concat all text into one string, to properly replace quotes around non-"text" nodes
allText = String(processor.processSync(allText));
for (const node of textOrInlineCodeNodes) {
const endIndex = startIndex + node.value.length;
if (node.type === 'text') {
const processedText = allText.slice(startIndex, endIndex);
node.value = String(processor2.processSync(processedText));
}
startIndex = endIndex;
}
}
return transformer;
};
| 28.444444 | 90 | 0.649407 |
cybersecurity-penetration-testing | /** @flow */
// This test harness mounts each test app as a separate root to test multi-root applications.
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {createRoot} from 'react-dom/client';
const container = document.createElement('div');
((document.body: any): HTMLBodyElement).appendChild(container);
// TODO We may want to parameterize this app
// so that it can load things other than just ToDoList.
const App = require('../e2e-apps/ListApp').default;
const root = createRoot(container);
root.render(<App />);
// ReactDOM Test Selector APIs used by Playwright e2e tests
window.parent.REACT_DOM_APP = ReactDOM;
| 28.772727 | 93 | 0.737003 |
null | #!/usr/bin/env node
'use strict';
const prompt = require('prompt-promise');
const semver = require('semver');
const theme = require('../theme');
const {confirm} = require('../utils');
const run = async ({skipPackages}, versionsMap) => {
const groupedVersionsMap = new Map();
// Group packages with the same source versions.
// We want these to stay lock-synced anyway.
// This will require less redundant input from the user later,
// and reduce the likelihood of human error (entering the wrong version).
versionsMap.forEach((version, packageName) => {
if (!groupedVersionsMap.has(version)) {
groupedVersionsMap.set(version, [packageName]);
} else {
groupedVersionsMap.get(version).push(packageName);
}
});
// Prompt user to confirm or override each version group.
const entries = [...groupedVersionsMap.entries()];
for (let i = 0; i < entries.length; i++) {
const [bestGuessVersion, packages] = entries[i];
const packageNames = packages.map(name => theme.package(name)).join(', ');
let version = bestGuessVersion;
if (
skipPackages.some(skipPackageName =>
packageNames.includes(skipPackageName)
)
) {
await confirm(
theme`{spinnerSuccess ✓} Version for ${packageNames} will remain {version ${bestGuessVersion}}`
);
} else {
const defaultVersion = bestGuessVersion
? theme.version(` (default ${bestGuessVersion})`)
: '';
version =
(await prompt(
theme`{spinnerSuccess ✓} Version for ${packageNames}${defaultVersion}: `
)) || bestGuessVersion;
prompt.done();
}
// Verify a valid version has been supplied.
try {
semver(version);
packages.forEach(packageName => {
versionsMap.set(packageName, version);
});
} catch (error) {
console.log(
theme`{spinnerError ✘} Version {version ${version}} is invalid.`
);
// Prompt again
i--;
}
}
};
// Run this directly because it's fast,
// and logPromise would interfere with console prompting.
module.exports = run;
| 28.333333 | 103 | 0.636191 |
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.
*/
import {invokeGuardedCallbackAndCatchFirstError} from 'shared/ReactErrorUtils';
import isArray from 'shared/isArray';
export let getFiberCurrentPropsFromNode = null;
export let getInstanceFromNode = null;
export let getNodeFromInstance = null;
export function setComponentTree(
getFiberCurrentPropsFromNodeImpl,
getInstanceFromNodeImpl,
getNodeFromInstanceImpl,
) {
getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
getInstanceFromNode = getInstanceFromNodeImpl;
getNodeFromInstance = getNodeFromInstanceImpl;
if (__DEV__) {
if (!getNodeFromInstance || !getInstanceFromNode) {
console.error(
'EventPluginUtils.setComponentTree(...): Injected ' +
'module is missing getNodeFromInstance or getInstanceFromNode.',
);
}
}
}
function validateEventDispatches(event) {
if (__DEV__) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
const listenersIsArr = isArray(dispatchListeners);
const listenersLen = listenersIsArr
? dispatchListeners.length
: dispatchListeners
? 1
: 0;
const instancesIsArr = isArray(dispatchInstances);
const instancesLen = instancesIsArr
? dispatchInstances.length
: dispatchInstances
? 1
: 0;
if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {
console.error('EventPluginUtils: Invalid `event`.');
}
}
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {function} listener Application-level callback
* @param {*} inst Internal component instance
*/
export function executeDispatch(event, listener, inst) {
const type = event.type || 'unknown-event';
event.currentTarget = getNodeFromInstance(inst);
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
export function executeDispatchesInOrder(event) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
if (__DEV__) {
validateEventDispatches(event);
}
if (isArray(dispatchListeners)) {
for (let i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, dispatchListeners, dispatchInstances);
}
event._dispatchListeners = null;
event._dispatchInstances = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
if (__DEV__) {
validateEventDispatches(event);
}
if (isArray(dispatchListeners)) {
for (let i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchInstances[i])) {
return dispatchInstances[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchInstances)) {
return dispatchInstances;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
export function executeDispatchesInOrderStopAtTrue(event) {
const ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchInstances = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
export function executeDirectDispatch(event) {
if (__DEV__) {
validateEventDispatches(event);
}
const dispatchListener = event._dispatchListeners;
const dispatchInstance = event._dispatchInstances;
if (isArray(dispatchListener)) {
throw new Error('executeDirectDispatch(...): Invalid `event`.');
}
event.currentTarget = dispatchListener
? getNodeFromInstance(dispatchInstance)
: null;
const res = dispatchListener ? dispatchListener(event) : null;
event.currentTarget = null;
event._dispatchListeners = null;
event._dispatchInstances = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
export function hasDispatches(event) {
return !!event._dispatchListeners;
}
| 30.364162 | 81 | 0.722396 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function Component() {
const [count, setCount] = (0, _react.useState)(0);
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 5
}
}, /*#__PURE__*/_react.default.createElement("p", {
__source: {
fileName: _jsxFileName,
lineNumber: 17,
columnNumber: 7
}
}, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", {
onClick: () => setCount(count + 1),
__source: {
fileName: _jsxFileName,
lineNumber: 18,
columnNumber: 7
}
}, "Click me"));
}
//# sourceMappingURL=Example.js.map?foo=bar¶m=some_value | 45.641026 | 743 | 0.648515 |
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;
const ChildComponent = ({id, eventHandler}) => (
<div
id={id + '__DIV'}
onClickCapture={e => eventHandler(e.currentTarget.id, 'captured', e.type)}
onClick={e => eventHandler(e.currentTarget.id, 'bubbled', e.type)}
onMouseEnter={e => eventHandler(e.currentTarget.id, e.type)}
onMouseLeave={e => eventHandler(e.currentTarget.id, e.type)}>
<div
id={id + '__DIV_1'}
onClickCapture={e => eventHandler(e.currentTarget.id, 'captured', e.type)}
onClick={e => eventHandler(e.currentTarget.id, 'bubbled', e.type)}
onMouseEnter={e => eventHandler(e.currentTarget.id, e.type)}
onMouseLeave={e => eventHandler(e.currentTarget.id, e.type)}
/>
<div
id={id + '__DIV_2'}
onClickCapture={e => eventHandler(e.currentTarget.id, 'captured', e.type)}
onClick={e => eventHandler(e.currentTarget.id, 'bubbled', e.type)}
onMouseEnter={e => eventHandler(e.currentTarget.id, e.type)}
onMouseLeave={e => eventHandler(e.currentTarget.id, e.type)}
/>
</div>
);
const ParentComponent = ({eventHandler}) => (
<div
id="P"
onClickCapture={e => eventHandler(e.currentTarget.id, 'captured', e.type)}
onClick={e => eventHandler(e.currentTarget.id, 'bubbled', e.type)}
onMouseEnter={e => eventHandler(e.currentTarget.id, e.type)}
onMouseLeave={e => eventHandler(e.currentTarget.id, e.type)}>
<div
id="P_P1"
onClickCapture={e => eventHandler(e.currentTarget.id, 'captured', e.type)}
onClick={e => eventHandler(e.currentTarget.id, 'bubbled', e.type)}
onMouseEnter={e => eventHandler(e.currentTarget.id, e.type)}
onMouseLeave={e => eventHandler(e.currentTarget.id, e.type)}>
<ChildComponent id="P_P1_C1" eventHandler={eventHandler} />
<ChildComponent id="P_P1_C2" eventHandler={eventHandler} />
</div>
<div
id="P_OneOff"
onClickCapture={e => eventHandler(e.currentTarget.id, 'captured', e.type)}
onClick={e => eventHandler(e.currentTarget.id, 'bubbled', e.type)}
onMouseEnter={e => eventHandler(e.currentTarget.id, e.type)}
onMouseLeave={e => eventHandler(e.currentTarget.id, e.type)}
/>
</div>
);
describe('ReactTreeTraversal', () => {
const mockFn = jest.fn();
let container;
let outerNode1;
let outerNode2;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
mockFn.mockReset();
container = document.createElement('div');
outerNode1 = document.createElement('div');
outerNode2 = document.createElement('div');
document.body.appendChild(container);
document.body.appendChild(outerNode1);
document.body.appendChild(outerNode2);
ReactDOM.render(<ParentComponent eventHandler={mockFn} />, container);
});
afterEach(() => {
document.body.removeChild(container);
document.body.removeChild(outerNode1);
document.body.removeChild(outerNode2);
container = null;
outerNode1 = null;
outerNode2 = null;
});
describe('Two phase traversal', () => {
it('should not traverse when target is outside component boundary', () => {
outerNode1.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
expect(mockFn).not.toHaveBeenCalled();
});
it('should traverse two phase across component boundary', () => {
const expectedCalls = [
['P', 'captured', 'click'],
['P_P1', 'captured', 'click'],
['P_P1_C1__DIV', 'captured', 'click'],
['P_P1_C1__DIV_1', 'captured', 'click'],
['P_P1_C1__DIV_1', 'bubbled', 'click'],
['P_P1_C1__DIV', 'bubbled', 'click'],
['P_P1', 'bubbled', 'click'],
['P', 'bubbled', 'click'],
];
const node = document.getElementById('P_P1_C1__DIV_1');
node.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
it('should traverse two phase at shallowest node', () => {
const node = document.getElementById('P');
node.dispatchEvent(
new MouseEvent('click', {bubbles: true, cancelable: true}),
);
const expectedCalls = [
['P', 'captured', 'click'],
['P', 'bubbled', 'click'],
];
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
});
describe('Enter leave traversal', () => {
it('should not traverse when enter/leaving outside DOM', () => {
outerNode1.dispatchEvent(
new MouseEvent('mouseout', {
bubbles: true,
cancelable: true,
relatedTarget: outerNode2,
}),
);
expect(mockFn).not.toHaveBeenCalled();
});
it('should not traverse if enter/leave the same node', () => {
const leaveNode = document.getElementById('P_P1_C1__DIV_1');
const enterNode = document.getElementById('P_P1_C1__DIV_1');
leaveNode.dispatchEvent(
new MouseEvent('mouseout', {
bubbles: true,
cancelable: true,
relatedTarget: enterNode,
}),
);
expect(mockFn).not.toHaveBeenCalled();
});
it('should traverse enter/leave to sibling - avoids parent', () => {
const leaveNode = document.getElementById('P_P1_C1__DIV_1');
const enterNode = document.getElementById('P_P1_C1__DIV_2');
const expectedCalls = [
['P_P1_C1__DIV_1', 'mouseleave'],
// enter/leave shouldn't fire anything on the parent
['P_P1_C1__DIV_2', 'mouseenter'],
];
leaveNode.dispatchEvent(
new MouseEvent('mouseout', {
bubbles: true,
cancelable: true,
relatedTarget: enterNode,
}),
);
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
it('should traverse enter/leave to parent - avoids parent', () => {
const leaveNode = document.getElementById('P_P1_C1__DIV_1');
const enterNode = document.getElementById('P_P1_C1__DIV');
const expectedCalls = [['P_P1_C1__DIV_1', 'mouseleave']];
leaveNode.dispatchEvent(
new MouseEvent('mouseout', {
bubbles: true,
cancelable: true,
relatedTarget: enterNode,
}),
);
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
// The modern event system attaches event listeners to roots so the
// event below is being triggered on a node that React does not listen
// to any more. Instead we should fire mouseover.
it('should enter from the window', () => {
const enterNode = document.getElementById('P_P1_C1__DIV');
const expectedCalls = [
['P', 'mouseenter'],
['P_P1', 'mouseenter'],
['P_P1_C1__DIV', 'mouseenter'],
];
enterNode.dispatchEvent(
new MouseEvent('mouseover', {
bubbles: true,
cancelable: true,
relatedTarget: outerNode1,
}),
);
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
it('should enter from the window to the shallowest', () => {
const enterNode = document.getElementById('P');
const expectedCalls = [['P', 'mouseenter']];
enterNode.dispatchEvent(
new MouseEvent('mouseover', {
bubbles: true,
cancelable: true,
relatedTarget: outerNode1,
}),
);
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
it('should leave to the window', () => {
const leaveNode = document.getElementById('P_P1_C1__DIV');
const expectedCalls = [
['P_P1_C1__DIV', 'mouseleave'],
['P_P1', 'mouseleave'],
['P', 'mouseleave'],
];
leaveNode.dispatchEvent(
new MouseEvent('mouseout', {
bubbles: true,
cancelable: true,
relatedTarget: outerNode1,
}),
);
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
it('should leave to the window from the shallowest', () => {
const leaveNode = document.getElementById('P');
const expectedCalls = [['P', 'mouseleave']];
leaveNode.dispatchEvent(
new MouseEvent('mouseout', {
bubbles: true,
cancelable: true,
relatedTarget: outerNode1,
}),
);
expect(mockFn.mock.calls).toEqual(expectedCalls);
});
});
});
| 29.429078 | 80 | 0.598252 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment
*/
'use strict';
const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils');
// Set by `yarn test-fire`.
const {disableInputAttributeSyncing} = require('shared/ReactFeatureFlags');
let React;
let ReactDOM;
let ReactDOMServer;
let ReactTestUtils;
function initModules() {
// Reset warning cache.
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactTestUtils = require('react-dom/test-utils');
// Make them available to the helpers.
return {
ReactDOM,
ReactDOMServer,
ReactTestUtils,
};
}
const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules);
// TODO: Run this in React Fire mode after we figure out the SSR behavior.
const desc = disableInputAttributeSyncing ? xdescribe : describe;
desc('ReactDOMServerIntegrationInput', () => {
beforeEach(() => {
resetModules();
});
itRenders('an input with a value and an onChange', async render => {
const e = await render(<input value="foo" onChange={() => {}} />);
expect(e.value).toBe('foo');
});
itRenders('an input with a value and readOnly', async render => {
const e = await render(<input value="foo" readOnly={true} />);
expect(e.value).toBe('foo');
});
itRenders('an input with a value and no onChange/readOnly', async render => {
// this configuration should raise a dev warning that value without
// onChange or readOnly is a mistake.
const e = await render(<input value="foo" />, 1);
expect(e.value).toBe('foo');
expect(e.getAttribute('value')).toBe('foo');
});
itRenders('an input with a defaultValue', async render => {
const e = await render(<input defaultValue="foo" />);
expect(e.value).toBe('foo');
expect(e.getAttribute('value')).toBe('foo');
expect(e.getAttribute('defaultValue')).toBe(null);
});
itRenders('an input value overriding defaultValue', async render => {
const e = await render(
<input value="foo" defaultValue="bar" readOnly={true} />,
1,
);
expect(e.value).toBe('foo');
expect(e.getAttribute('value')).toBe('foo');
expect(e.getAttribute('defaultValue')).toBe(null);
});
itRenders(
'an input value overriding defaultValue no matter the prop order',
async render => {
const e = await render(
<input defaultValue="bar" value="foo" readOnly={true} />,
1,
);
expect(e.value).toBe('foo');
expect(e.getAttribute('value')).toBe('foo');
expect(e.getAttribute('defaultValue')).toBe(null);
},
);
});
| 29.547368 | 93 | 0.667011 |
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 invokeGuardedCallbackImpl from './invokeGuardedCallbackImpl';
// Used by Fiber to simulate a try-catch.
let hasError: boolean = false;
let caughtError: mixed = null;
// Used by event system to capture/rethrow the first error.
let hasRethrowError: boolean = false;
let rethrowError: mixed = null;
const reporter = {
onError(error: mixed) {
hasError = true;
caughtError = error;
},
};
/**
* Call a function while guarding against errors that happens within it.
* Returns an error if it throws, otherwise null.
*
* In production, this is implemented using a try-catch. The reason we don't
* use a try-catch directly is so that we can swap out a different
* implementation in DEV mode.
*
* @param {String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} context The context to use when calling the function
* @param {...*} args Arguments for function
*/
export function invokeGuardedCallback<A, B, C, D, E, F, Context>(
name: string | null,
func: (a: A, b: B, c: C, d: D, e: E, f: F) => mixed,
context: Context,
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
): void {
hasError = false;
caughtError = null;
invokeGuardedCallbackImpl.apply(reporter, arguments);
}
/**
* Same as invokeGuardedCallback, but instead of returning an error, it stores
* it in a global so it can be rethrown by `rethrowCaughtError` later.
* TODO: See if caughtError and rethrowError can be unified.
*
* @param {String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} context The context to use when calling the function
* @param {...*} args Arguments for function
*/
export function invokeGuardedCallbackAndCatchFirstError<
A,
B,
C,
D,
E,
F,
Context,
>(
this: mixed,
name: string | null,
func: (a: A, b: B, c: C, d: D, e: E, f: F) => void,
context: Context,
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
): void {
invokeGuardedCallback.apply(this, arguments);
if (hasError) {
const error = clearCaughtError();
if (!hasRethrowError) {
hasRethrowError = true;
rethrowError = error;
}
}
}
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
export function rethrowCaughtError() {
if (hasRethrowError) {
const error = rethrowError;
hasRethrowError = false;
rethrowError = null;
throw error;
}
}
export function hasCaughtError(): boolean {
return hasError;
}
export function clearCaughtError(): mixed {
if (hasError) {
const error = caughtError;
hasError = false;
caughtError = null;
return error;
} else {
throw new Error(
'clearCaughtError was called but no error was captured. This error ' +
'is likely caused by a bug in React. Please file an issue.',
);
}
}
| 23.936508 | 78 | 0.671124 |
Mastering-Machine-Learning-for-Penetration-Testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {ReactContext} from 'shared/ReactTypes';
import {createContext} from 'react';
import type {ViewUrlSource} from 'react-devtools-shared/src/devtools/views/DevTools';
export type Context = {
viewUrlSourceFunction: ViewUrlSource | null,
};
const ViewSourceContext: ReactContext<Context> = createContext<Context>(
((null: any): Context),
);
ViewSourceContext.displayName = 'ViewSourceContext';
export default ViewSourceContext;
| 23.961538 | 85 | 0.748457 |
Python-Penetration-Testing-for-Developers | let React;
let ReactNoop;
let Scheduler;
let act;
let useState;
let useEffect;
let startTransition;
let assertLog;
let waitForPaint;
// TODO: Migrate tests to React DOM instead of React Noop
describe('ReactFlushSync', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
useState = React.useState;
useEffect = React.useEffect;
startTransition = React.startTransition;
const InternalTestUtils = require('internal-test-utils');
assertLog = InternalTestUtils.assertLog;
waitForPaint = InternalTestUtils.waitForPaint;
});
function Text({text}) {
Scheduler.log(text);
return text;
}
test('changes priority of updates in useEffect', async () => {
spyOnDev(console, 'error').mockImplementation(() => {});
function App() {
const [syncState, setSyncState] = useState(0);
const [state, setState] = useState(0);
useEffect(() => {
if (syncState !== 1) {
setState(1);
ReactNoop.flushSync(() => setSyncState(1));
}
}, [syncState, state]);
return <Text text={`${syncState}, ${state}`} />;
}
const root = ReactNoop.createRoot();
await act(async () => {
React.startTransition(() => {
root.render(<App />);
});
// This will yield right before the passive effect fires
await waitForPaint(['0, 0']);
// The passive effect will schedule a sync update and a normal update.
// They should commit in two separate batches. First the sync one.
await waitForPaint(
gate(flags => flags.enableUnifiedSyncLane) ? ['1, 1'] : ['1, 0'],
);
// The remaining update is not sync
ReactNoop.flushSync();
assertLog([]);
if (gate(flags => flags.enableUnifiedSyncLane)) {
await waitForPaint([]);
} else {
// Now flush it.
await waitForPaint(['1, 1']);
}
});
expect(root).toMatchRenderedOutput('1, 1');
if (__DEV__) {
expect(console.error.mock.calls[0][0]).toContain(
'flushSync was called from inside a lifecycle method. React ' +
'cannot flush when React is already rendering. Consider moving this ' +
'call to a scheduler task or micro task.%s',
);
}
});
test('nested with startTransition', async () => {
let setSyncState;
let setState;
function App() {
const [syncState, _setSyncState] = useState(0);
const [state, _setState] = useState(0);
setSyncState = _setSyncState;
setState = _setState;
return <Text text={`${syncState}, ${state}`} />;
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['0, 0']);
expect(root).toMatchRenderedOutput('0, 0');
await act(() => {
ReactNoop.flushSync(() => {
startTransition(() => {
// This should be async even though flushSync is on the stack, because
// startTransition is closer.
setState(1);
ReactNoop.flushSync(() => {
// This should be async even though startTransition is on the stack,
// because flushSync is closer.
setSyncState(1);
});
});
});
// Only the sync update should have flushed
assertLog(['1, 0']);
expect(root).toMatchRenderedOutput('1, 0');
});
// Now the async update has flushed, too.
assertLog(['1, 1']);
expect(root).toMatchRenderedOutput('1, 1');
});
test('flushes passive effects synchronously when they are the result of a sync render', async () => {
function App() {
useEffect(() => {
Scheduler.log('Effect');
}, []);
return <Text text="Child" />;
}
const root = ReactNoop.createRoot();
await act(() => {
ReactNoop.flushSync(() => {
root.render(<App />);
});
assertLog([
'Child',
// Because the pending effect was the result of a sync update, calling
// flushSync should flush it.
'Effect',
]);
expect(root).toMatchRenderedOutput('Child');
});
});
test('do not flush passive effects synchronously after render in legacy mode', async () => {
function App() {
useEffect(() => {
Scheduler.log('Effect');
}, []);
return <Text text="Child" />;
}
const root = ReactNoop.createLegacyRoot();
await act(() => {
ReactNoop.flushSync(() => {
root.render(<App />);
});
assertLog([
'Child',
// Because we're in legacy mode, we shouldn't have flushed the passive
// effects yet.
]);
expect(root).toMatchRenderedOutput('Child');
});
// Effect flushes after paint.
assertLog(['Effect']);
});
test('flush pending passive effects before scope is called in legacy mode', async () => {
let currentStep = 0;
function App({step}) {
useEffect(() => {
currentStep = step;
Scheduler.log('Effect: ' + step);
}, [step]);
return <Text text={step} />;
}
const root = ReactNoop.createLegacyRoot();
await act(() => {
ReactNoop.flushSync(() => {
root.render(<App step={1} />);
});
assertLog([
1,
// Because we're in legacy mode, we shouldn't have flushed the passive
// effects yet.
]);
expect(root).toMatchRenderedOutput('1');
ReactNoop.flushSync(() => {
// This should render step 2 because the passive effect has already
// fired, before the scope function is called.
root.render(<App step={currentStep + 1} />);
});
assertLog(['Effect: 1', 2]);
expect(root).toMatchRenderedOutput('2');
});
assertLog(['Effect: 2']);
});
test("do not flush passive effects synchronously when they aren't the result of a sync render", async () => {
function App() {
useEffect(() => {
Scheduler.log('Effect');
}, []);
return <Text text="Child" />;
}
const root = ReactNoop.createRoot();
await act(async () => {
root.render(<App />);
await waitForPaint([
'Child',
// Because the passive effect was not the result of a sync update, it
// should not flush before paint.
]);
expect(root).toMatchRenderedOutput('Child');
});
// Effect flushes after paint.
assertLog(['Effect']);
});
test('does not flush pending passive effects', async () => {
function App() {
useEffect(() => {
Scheduler.log('Effect');
}, []);
return <Text text="Child" />;
}
const root = ReactNoop.createRoot();
await act(async () => {
root.render(<App />);
await waitForPaint(['Child']);
expect(root).toMatchRenderedOutput('Child');
// Passive effects are pending. Calling flushSync should not affect them.
ReactNoop.flushSync();
// Effects still haven't fired.
assertLog([]);
});
// Now the effects have fired.
assertLog(['Effect']);
});
test('completely exhausts synchronous work queue even if something throws', async () => {
function Throws({error}) {
throw error;
}
const root1 = ReactNoop.createRoot();
const root2 = ReactNoop.createRoot();
const root3 = ReactNoop.createRoot();
await act(async () => {
root1.render(<Text text="Hi" />);
root2.render(<Text text="Andrew" />);
root3.render(<Text text="!" />);
});
assertLog(['Hi', 'Andrew', '!']);
const aahh = new Error('AAHH!');
const nooo = new Error('Noooooooooo!');
let error;
try {
ReactNoop.flushSync(() => {
root1.render(<Throws error={aahh} />);
root2.render(<Throws error={nooo} />);
root3.render(<Text text="aww" />);
});
} catch (e) {
error = e;
}
// The update to root 3 should have finished synchronously, even though the
// earlier updates errored.
assertLog(['aww']);
// Roots 1 and 2 were unmounted.
expect(root1).toMatchRenderedOutput(null);
expect(root2).toMatchRenderedOutput(null);
expect(root3).toMatchRenderedOutput('aww');
// Because there were multiple errors, React threw an AggregateError.
// eslint-disable-next-line no-undef
expect(error).toBeInstanceOf(AggregateError);
expect(error.errors.length).toBe(2);
expect(error.errors[0]).toBe(aahh);
expect(error.errors[1]).toBe(nooo);
});
});
| 27.832215 | 111 | 0.578047 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let PropTypes;
let React;
let ReactDOM;
let ReactTestUtils;
describe('ReactElementClone', () => {
let ComponentClass;
beforeEach(() => {
PropTypes = require('prop-types');
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-dom/test-utils');
// NOTE: We're explicitly not using JSX here. This is intended to test
// classic JS without JSX.
ComponentClass = class extends React.Component {
render() {
return React.createElement('div');
}
};
});
it('should clone a DOM component with new props', () => {
class Grandparent extends React.Component {
render() {
return <Parent child={<div className="child" />} />;
}
}
class Parent extends React.Component {
render() {
return (
<div className="parent">
{React.cloneElement(this.props.child, {className: 'xyz'})}
</div>
);
}
}
const component = ReactTestUtils.renderIntoDocument(<Grandparent />);
expect(ReactDOM.findDOMNode(component).childNodes[0].className).toBe('xyz');
});
it('should clone a composite component with new props', () => {
class Child extends React.Component {
render() {
return <div className={this.props.className} />;
}
}
class Grandparent extends React.Component {
render() {
return <Parent child={<Child className="child" />} />;
}
}
class Parent extends React.Component {
render() {
return (
<div className="parent">
{React.cloneElement(this.props.child, {className: 'xyz'})}
</div>
);
}
}
const component = ReactTestUtils.renderIntoDocument(<Grandparent />);
expect(ReactDOM.findDOMNode(component).childNodes[0].className).toBe('xyz');
});
it('does not fail if config has no prototype', () => {
const config = Object.create(null, {foo: {value: 1, enumerable: true}});
React.cloneElement(<div />, config);
});
it('should keep the original ref if it is not overridden', () => {
class Grandparent extends React.Component {
yoloRef = React.createRef();
render() {
return <Parent child={<div ref={this.yoloRef} />} />;
}
}
class Parent extends React.Component {
render() {
return (
<div>{React.cloneElement(this.props.child, {className: 'xyz'})}</div>
);
}
}
const component = ReactTestUtils.renderIntoDocument(<Grandparent />);
expect(component.yoloRef.current.tagName).toBe('DIV');
});
it('should transfer the key property', () => {
class Component extends React.Component {
render() {
return null;
}
}
const clone = React.cloneElement(<Component />, {key: 'xyz'});
expect(clone.key).toBe('xyz');
});
it('should transfer children', () => {
class Component extends React.Component {
render() {
expect(this.props.children).toBe('xyz');
return <div />;
}
}
ReactTestUtils.renderIntoDocument(
React.cloneElement(<Component />, {children: 'xyz'}),
);
});
it('should shallow clone children', () => {
class Component extends React.Component {
render() {
expect(this.props.children).toBe('xyz');
return <div />;
}
}
ReactTestUtils.renderIntoDocument(
React.cloneElement(<Component>xyz</Component>, {}),
);
});
it('should accept children as rest arguments', () => {
class Component extends React.Component {
render() {
return null;
}
}
const clone = React.cloneElement(
<Component>xyz</Component>,
{children: <Component />},
<div />,
<span />,
);
expect(clone.props.children).toEqual([<div />, <span />]);
});
it('should override children if undefined is provided as an argument', () => {
const element = React.createElement(
ComponentClass,
{
children: 'text',
},
undefined,
);
expect(element.props.children).toBe(undefined);
const element2 = React.cloneElement(
React.createElement(ComponentClass, {
children: 'text',
}),
{},
undefined,
);
expect(element2.props.children).toBe(undefined);
});
it('should support keys and refs', () => {
class Parent extends React.Component {
xyzRef = React.createRef();
render() {
const clone = React.cloneElement(this.props.children, {
key: 'xyz',
ref: this.xyzRef,
});
expect(clone.key).toBe('xyz');
expect(clone.ref).toBe(this.xyzRef);
return <div>{clone}</div>;
}
}
class Grandparent extends React.Component {
parentRef = React.createRef();
render() {
return (
<Parent ref={this.parentRef}>
<span key="abc" />
</Parent>
);
}
}
const component = ReactTestUtils.renderIntoDocument(<Grandparent />);
expect(component.parentRef.current.xyzRef.current.tagName).toBe('SPAN');
});
it('should steal the ref if a new ref is specified', () => {
class Parent extends React.Component {
xyzRef = React.createRef();
render() {
const clone = React.cloneElement(this.props.children, {
ref: this.xyzRef,
});
return <div>{clone}</div>;
}
}
class Grandparent extends React.Component {
parentRef = React.createRef();
childRef = React.createRef();
render() {
return (
<Parent ref={this.parentRef}>
<span ref={this.childRef} />
</Parent>
);
}
}
const component = ReactTestUtils.renderIntoDocument(<Grandparent />);
expect(component.childRef).toEqual({current: null});
expect(component.parentRef.current.xyzRef.current.tagName).toBe('SPAN');
});
it('should overwrite props', () => {
class Component extends React.Component {
render() {
expect(this.props.myprop).toBe('xyz');
return <div />;
}
}
ReactTestUtils.renderIntoDocument(
React.cloneElement(<Component myprop="abc" />, {myprop: 'xyz'}),
);
});
it('should normalize props with default values', () => {
class Component extends React.Component {
render() {
return <span />;
}
}
Component.defaultProps = {prop: 'testKey'};
const instance = React.createElement(Component);
const clonedInstance = React.cloneElement(instance, {prop: undefined});
expect(clonedInstance.props.prop).toBe('testKey');
const clonedInstance2 = React.cloneElement(instance, {prop: null});
expect(clonedInstance2.props.prop).toBe(null);
const instance2 = React.createElement(Component, {prop: 'newTestKey'});
const cloneInstance3 = React.cloneElement(instance2, {prop: undefined});
expect(cloneInstance3.props.prop).toBe('testKey');
const cloneInstance4 = React.cloneElement(instance2, {});
expect(cloneInstance4.props.prop).toBe('newTestKey');
});
it('warns for keys for arrays of elements in rest args', () => {
expect(() =>
React.cloneElement(<div />, null, [<div />, <div />]),
).toErrorDev('Each child in a list should have a unique "key" prop.');
});
it('does not warns for arrays of elements with keys', () => {
React.cloneElement(<div />, null, [<div key="#1" />, <div key="#2" />]);
});
it('does not warn when the element is directly in rest args', () => {
React.cloneElement(<div />, null, <div />, <div />);
});
it('does not warn when the array contains a non-element', () => {
React.cloneElement(<div />, null, [{}, {}]);
});
it('should check declared prop types after clone', () => {
class Component extends React.Component {
static propTypes = {
color: PropTypes.string.isRequired,
};
render() {
return React.createElement('div', null, 'My color is ' + this.color);
}
}
class Parent extends React.Component {
render() {
return React.cloneElement(this.props.child, {color: 123});
}
}
class GrandParent extends React.Component {
render() {
return React.createElement(Parent, {
child: React.createElement(Component, {color: 'red'}),
});
}
}
expect(() =>
ReactTestUtils.renderIntoDocument(React.createElement(GrandParent)),
).toErrorDev(
'Warning: Failed prop type: ' +
'Invalid prop `color` of type `number` supplied to `Component`, ' +
'expected `string`.\n' +
' in Component (at **)\n' +
' in Parent (at **)\n' +
' in GrandParent',
);
});
it('should ignore key and ref warning getters', () => {
const elementA = React.createElement('div');
const elementB = React.cloneElement(elementA, elementA.props);
expect(elementB.key).toBe(null);
expect(elementB.ref).toBe(null);
});
it('should ignore undefined key and ref', () => {
const element = React.createElement(ComponentClass, {
key: '12',
ref: '34',
foo: '56',
});
const props = {
key: undefined,
ref: undefined,
foo: 'ef',
};
const clone = React.cloneElement(element, props);
expect(clone.type).toBe(ComponentClass);
expect(clone.key).toBe('12');
expect(clone.ref).toBe('34');
if (__DEV__) {
expect(Object.isFrozen(element)).toBe(true);
expect(Object.isFrozen(element.props)).toBe(true);
}
expect(clone.props).toEqual({foo: 'ef'});
});
it('should extract null key and ref', () => {
const element = React.createElement(ComponentClass, {
key: '12',
ref: '34',
foo: '56',
});
const props = {
key: null,
ref: null,
foo: 'ef',
};
const clone = React.cloneElement(element, props);
expect(clone.type).toBe(ComponentClass);
expect(clone.key).toBe('null');
expect(clone.ref).toBe(null);
if (__DEV__) {
expect(Object.isFrozen(element)).toBe(true);
expect(Object.isFrozen(element.props)).toBe(true);
}
expect(clone.props).toEqual({foo: 'ef'});
});
it('throws an error if passed null', () => {
const element = null;
expect(() => React.cloneElement(element)).toThrow(
'React.cloneElement(...): The argument must be a React element, but you passed null.',
);
});
it('throws an error if passed undefined', () => {
let element;
expect(() => React.cloneElement(element)).toThrow(
'React.cloneElement(...): The argument must be a React element, but you passed undefined.',
);
});
});
| 27.134021 | 97 | 0.59038 |
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';
let React;
let ReactDOM;
describe('ReactError', () => {
let globalErrorMock;
beforeEach(() => {
if (!__DEV__) {
// In production, our Jest environment overrides the global Error
// class in order to decode error messages automatically. However
// this is a single test where we actually *don't* want to decode
// them. So we assert that the OriginalError exists, and temporarily
// set the global Error object back to it.
globalErrorMock = global.Error;
global.Error = globalErrorMock.OriginalError;
expect(typeof global.Error).toBe('function');
}
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
});
afterEach(() => {
if (!__DEV__) {
global.Error = globalErrorMock;
}
});
// @gate build === "production"
// @gate !source
it('should error with minified error code', () => {
expect(() => ReactDOM.render('Hi', null)).toThrowError(
'Minified React error #200; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=200' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.',
);
});
it('should serialize arguments', () => {
function Oops() {
return;
}
Oops.displayName = '#wtf';
const container = document.createElement('div');
expect(() => ReactDOM.render(<Oops />, container)).not.toThrowError();
});
});
| 28.084746 | 74 | 0.628571 |
SNAP_R | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import styles from './shared.css';
type Props = {
callStack: string | null,
children: React$Node,
componentStack: string | null,
errorMessage: string | null,
};
export default function UnsupportedBridgeOperationView({
callStack,
children,
componentStack,
errorMessage,
}: Props): React.Node {
return (
<div className={styles.ErrorBoundary}>
{children}
<div className={styles.ErrorInfo}>
<div className={styles.HeaderRow}>
<div className={styles.ErrorHeader}>
{errorMessage || 'Bridge protocol mismatch'}
</div>
</div>
<div className={styles.InfoBox}>
An incompatible version of <code>react-devtools-core</code> has been
embedded in a renderer like React Native. To fix this, update the{' '}
<code>react-devtools-core</code> package within the React Native
application, or downgrade the <code>react-devtools</code> package you
use to open the DevTools UI.
</div>
{!!callStack && (
<div className={styles.ErrorStack}>
The error was thrown {callStack.trim()}
</div>
)}
</div>
</div>
);
}
| 27.078431 | 80 | 0.625437 |
Penetration-Testing-Study-Notes | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @typechecks
*
* Example usage:
* <Rectangle
* width={50}
* height={50}
* stroke="green"
* fill="blue"
* />
*
* Additional optional properties:
* (Number) radius
* (Number) radiusTopLeft
* (Number) radiusTopRight
* (Number) radiusBottomLeft
* (Number) radiusBottomRight
*
*/
'use strict';
var assign = Object.assign;
var PropTypes = require('prop-types');
var React = require('react');
var ReactART = require('react-art');
var createReactClass = require('create-react-class');
var Shape = ReactART.Shape;
var Path = ReactART.Path;
/**
* Rectangle is a React component for drawing rectangles. Like other ReactART
* components, it must be used in a <Surface>.
*/
var Rectangle = createReactClass({
displayName: 'Rectangle',
propTypes: {
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
radius: PropTypes.number,
radiusTopLeft: PropTypes.number,
radiusTopRight: PropTypes.number,
radiusBottomRight: PropTypes.number,
radiusBottomLeft: PropTypes.number,
},
render: function render() {
var width = this.props.width;
var height = this.props.height;
var radius = this.props.radius ? this.props.radius : 0;
// if unspecified, radius(Top|Bottom)(Left|Right) defaults to the radius
// property
var tl = this.props.radiusTopLeft ? this.props.radiusTopLeft : radius;
var tr = this.props.radiusTopRight ? this.props.radiusTopRight : radius;
var br = this.props.radiusBottomRight
? this.props.radiusBottomRight
: radius;
var bl = this.props.radiusBottomLeft ? this.props.radiusBottomLeft : radius;
var path = Path();
// for negative width/height, offset the rectangle in the negative x/y
// direction. for negative radius, just default to 0.
if (width < 0) {
path.move(width, 0);
width = -width;
}
if (height < 0) {
path.move(0, height);
height = -height;
}
if (tl < 0) {
tl = 0;
}
if (tr < 0) {
tr = 0;
}
if (br < 0) {
br = 0;
}
if (bl < 0) {
bl = 0;
}
// disable border radius if it doesn't fit within the specified
// width/height
if (tl + tr > width) {
tl = 0;
tr = 0;
}
if (bl + br > width) {
bl = 0;
br = 0;
}
if (tl + bl > height) {
tl = 0;
bl = 0;
}
if (tr + br > height) {
tr = 0;
br = 0;
}
path.move(0, tl);
if (tl > 0) {
path.arc(tl, -tl);
}
path.line(width - (tr + tl), 0);
if (tr > 0) {
path.arc(tr, tr);
}
path.line(0, height - (tr + br));
if (br > 0) {
path.arc(-br, br);
}
path.line(-width + (br + bl), 0);
if (bl > 0) {
path.arc(-bl, -bl);
}
path.line(0, -height + (bl + tl));
return React.createElement(Shape, assign({}, this.props, {d: path}));
},
});
module.exports = Rectangle;
| 21.42446 | 80 | 0.58665 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useTheme;
exports.ThemeContext = void 0;
var _react = require("react");
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright');
exports.ThemeContext = ThemeContext;
function useTheme() {
const theme = (0, _react.useContext)(ThemeContext);
(0, _react.useDebugValue)(theme);
return theme;
}
//# sourceMappingURL=useTheme.js.map?foo=bar¶m=some_value | 23.851852 | 70 | 0.701493 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const helperModuleImports = require('@babel/helper-module-imports');
module.exports = function autoImporter(babel) {
function getAssignIdent(path, file, state) {
if (state.id) {
return state.id;
}
state.id = helperModuleImports.addDefault(path, 'shared/assign', {
nameHint: 'assign',
});
return state.id;
}
return {
pre: function () {
// map from module to generated identifier
this.id = null;
},
visitor: {
CallExpression: function (path, file) {
if (/shared(\/|\\)assign/.test(file.filename)) {
// Don't replace Object.assign if we're transforming shared/assign
return;
}
if (path.get('callee').matchesPattern('Object.assign')) {
// generate identifier and require if it hasn't been already
const id = getAssignIdent(path, file, this);
path.node.callee = id;
}
},
MemberExpression: function (path, file) {
if (/shared(\/|\\)assign/.test(file.filename)) {
// Don't replace Object.assign if we're transforming shared/assign
return;
}
if (path.matchesPattern('Object.assign')) {
const id = getAssignIdent(path, file, this);
path.replaceWith(id);
}
},
},
};
};
| 26.581818 | 76 | 0.594987 |
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 {CrossOriginString} from 'react-dom-bindings/src/shared/crossOriginStrings';
export type PrefetchDNSOptions = {};
export type PreconnectOptions = {crossOrigin?: string};
export type PreloadOptions = {
as: string,
crossOrigin?: string,
integrity?: string,
type?: string,
nonce?: string,
fetchPriority?: FetchPriorityEnum,
imageSrcSet?: string,
imageSizes?: string,
referrerPolicy?: string,
};
export type PreloadModuleOptions = {
as?: string,
crossOrigin?: string,
integrity?: string,
nonce?: string,
};
export type PreinitOptions = {
as: string,
precedence?: string,
crossOrigin?: string,
integrity?: string,
nonce?: string,
fetchPriority?: FetchPriorityEnum,
};
export type PreinitModuleOptions = {
as?: string,
crossOrigin?: string,
integrity?: string,
nonce?: string,
};
export type CrossOriginEnum = '' | 'use-credentials' | CrossOriginString;
export type FetchPriorityEnum = 'high' | 'low' | 'auto';
export type PreloadImplOptions = {
crossOrigin?: ?CrossOriginEnum,
integrity?: ?string,
nonce?: ?string,
type?: ?string,
fetchPriority?: ?string,
referrerPolicy?: ?string,
imageSrcSet?: ?string,
imageSizes?: ?string,
media?: ?string,
};
export type PreloadModuleImplOptions = {
as?: ?string,
crossOrigin?: ?CrossOriginEnum,
integrity?: ?string,
nonce?: ?string,
};
export type PreinitStyleOptions = {
crossOrigin?: ?CrossOriginEnum,
integrity?: ?string,
fetchPriority?: ?string,
};
export type PreinitScriptOptions = {
crossOrigin?: ?CrossOriginEnum,
integrity?: ?string,
fetchPriority?: ?string,
nonce?: ?string,
};
export type PreinitModuleScriptOptions = {
crossOrigin?: ?CrossOriginEnum,
integrity?: ?string,
nonce?: ?string,
};
export type HostDispatcher = {
prefetchDNS: (href: string) => void,
preconnect: (href: string, crossOrigin?: ?CrossOriginEnum) => void,
preload: (href: string, as: string, options?: ?PreloadImplOptions) => void,
preloadModule: (href: string, options?: ?PreloadModuleImplOptions) => void,
preinitStyle: (
href: string,
precedence: ?string,
options?: ?PreinitStyleOptions,
) => void,
preinitScript: (src: string, options?: PreinitScriptOptions) => void,
preinitModuleScript: (
src: string,
options?: ?PreinitModuleScriptOptions,
) => void,
};
export type ImportMap = {
imports?: {
[specifier: string]: string,
},
scopes?: {
[scope: string]: {
[specifier: string]: string,
},
},
};
| 23.5 | 88 | 0.689681 |
Hands-On-Penetration-Testing-with-Python | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {PROFILER_EXPORT_VERSION} from 'react-devtools-shared/src/constants';
import {backendToFrontendSerializedElementMapper} from 'react-devtools-shared/src/utils';
import type {ProfilingDataBackend} from 'react-devtools-shared/src/backend/types';
import type {
ProfilingDataExport,
ProfilingDataForRootExport,
ProfilingDataForRootFrontend,
ProfilingDataFrontend,
SnapshotNode,
} from './types';
import type {
TimelineData,
TimelineDataExport,
} from 'react-devtools-timeline/src/types';
const commitGradient = [
'var(--color-commit-gradient-0)',
'var(--color-commit-gradient-1)',
'var(--color-commit-gradient-2)',
'var(--color-commit-gradient-3)',
'var(--color-commit-gradient-4)',
'var(--color-commit-gradient-5)',
'var(--color-commit-gradient-6)',
'var(--color-commit-gradient-7)',
'var(--color-commit-gradient-8)',
'var(--color-commit-gradient-9)',
];
// Combines info from the Store (frontend) and renderer interfaces (backend) into the format required by the Profiler UI.
// This format can then be quickly exported (and re-imported).
export function prepareProfilingDataFrontendFromBackendAndStore(
dataBackends: Array<ProfilingDataBackend>,
operationsByRootID: Map<number, Array<Array<number>>>,
snapshotsByRootID: Map<number, Map<number, SnapshotNode>>,
): ProfilingDataFrontend {
const dataForRoots: Map<number, ProfilingDataForRootFrontend> = new Map();
const timelineDataArray = [];
dataBackends.forEach(dataBackend => {
const {timelineData} = dataBackend;
if (timelineData != null) {
const {
batchUIDToMeasuresKeyValueArray,
internalModuleSourceToRanges,
laneToLabelKeyValueArray,
laneToReactMeasureKeyValueArray,
...rest
} = timelineData;
timelineDataArray.push({
...rest,
// Most of the data is safe to parse as-is,
// but we need to convert the nested Arrays back to Maps.
batchUIDToMeasuresMap: new Map(batchUIDToMeasuresKeyValueArray),
internalModuleSourceToRanges: new Map(internalModuleSourceToRanges),
laneToLabelMap: new Map(laneToLabelKeyValueArray),
laneToReactMeasureMap: new Map(laneToReactMeasureKeyValueArray),
});
}
dataBackend.dataForRoots.forEach(
({commitData, displayName, initialTreeBaseDurations, rootID}) => {
const operations = operationsByRootID.get(rootID);
if (operations == null) {
throw Error(
`Could not find profiling operations for root "${rootID}"`,
);
}
const snapshots = snapshotsByRootID.get(rootID);
if (snapshots == null) {
throw Error(
`Could not find profiling snapshots for root "${rootID}"`,
);
}
// Do not filter empty commits from the profiler data!
// Hiding "empty" commits might cause confusion too.
// A commit *did happen* even if none of the components the Profiler is showing were involved.
const convertedCommitData = commitData.map(
(commitDataBackend, commitIndex) => ({
changeDescriptions:
commitDataBackend.changeDescriptions != null
? new Map(commitDataBackend.changeDescriptions)
: null,
duration: commitDataBackend.duration,
effectDuration: commitDataBackend.effectDuration,
fiberActualDurations: new Map(
commitDataBackend.fiberActualDurations,
),
fiberSelfDurations: new Map(commitDataBackend.fiberSelfDurations),
passiveEffectDuration: commitDataBackend.passiveEffectDuration,
priorityLevel: commitDataBackend.priorityLevel,
timestamp: commitDataBackend.timestamp,
updaters:
commitDataBackend.updaters !== null
? commitDataBackend.updaters.map(
backendToFrontendSerializedElementMapper,
)
: null,
}),
);
dataForRoots.set(rootID, {
commitData: convertedCommitData,
displayName,
initialTreeBaseDurations: new Map(initialTreeBaseDurations),
operations,
rootID,
snapshots,
});
},
);
});
return {dataForRoots, imported: false, timelineData: timelineDataArray};
}
// Converts a Profiling data export into the format required by the Store.
export function prepareProfilingDataFrontendFromExport(
profilingDataExport: ProfilingDataExport,
): ProfilingDataFrontend {
const {version} = profilingDataExport;
if (version !== PROFILER_EXPORT_VERSION) {
throw Error(
`Unsupported profile export version "${version}". Supported version is "${PROFILER_EXPORT_VERSION}".`,
);
}
const timelineData: Array<TimelineData> = profilingDataExport.timelineData
? profilingDataExport.timelineData.map(
({
batchUIDToMeasuresKeyValueArray,
componentMeasures,
duration,
flamechart,
internalModuleSourceToRanges,
laneToLabelKeyValueArray,
laneToReactMeasureKeyValueArray,
nativeEvents,
networkMeasures,
otherUserTimingMarks,
reactVersion,
schedulingEvents,
snapshots,
snapshotHeight,
startTime,
suspenseEvents,
thrownErrors,
}) => ({
// Most of the data is safe to parse as-is,
// but we need to convert the nested Arrays back to Maps.
batchUIDToMeasuresMap: new Map(batchUIDToMeasuresKeyValueArray),
componentMeasures,
duration,
flamechart,
internalModuleSourceToRanges: new Map(internalModuleSourceToRanges),
laneToLabelMap: new Map(laneToLabelKeyValueArray),
laneToReactMeasureMap: new Map(laneToReactMeasureKeyValueArray),
nativeEvents,
networkMeasures,
otherUserTimingMarks,
reactVersion,
schedulingEvents,
snapshots,
snapshotHeight,
startTime,
suspenseEvents,
thrownErrors,
}),
)
: [];
const dataForRoots: Map<number, ProfilingDataForRootFrontend> = new Map();
profilingDataExport.dataForRoots.forEach(
({
commitData,
displayName,
initialTreeBaseDurations,
operations,
rootID,
snapshots,
}) => {
dataForRoots.set(rootID, {
commitData: commitData.map(
({
changeDescriptions,
duration,
effectDuration,
fiberActualDurations,
fiberSelfDurations,
passiveEffectDuration,
priorityLevel,
timestamp,
updaters,
}) => ({
changeDescriptions:
changeDescriptions != null ? new Map(changeDescriptions) : null,
duration,
effectDuration,
fiberActualDurations: new Map(fiberActualDurations),
fiberSelfDurations: new Map(fiberSelfDurations),
passiveEffectDuration,
priorityLevel,
timestamp,
updaters,
}),
),
displayName,
initialTreeBaseDurations: new Map(initialTreeBaseDurations),
operations,
rootID,
snapshots: new Map(snapshots),
});
},
);
return {
dataForRoots,
imported: true,
timelineData,
};
}
// Converts a Store Profiling data into a format that can be safely (JSON) serialized for export.
export function prepareProfilingDataExport(
profilingDataFrontend: ProfilingDataFrontend,
): ProfilingDataExport {
const timelineData: Array<TimelineDataExport> =
profilingDataFrontend.timelineData.map(
({
batchUIDToMeasuresMap,
componentMeasures,
duration,
flamechart,
internalModuleSourceToRanges,
laneToLabelMap,
laneToReactMeasureMap,
nativeEvents,
networkMeasures,
otherUserTimingMarks,
reactVersion,
schedulingEvents,
snapshots,
snapshotHeight,
startTime,
suspenseEvents,
thrownErrors,
}) => ({
// Most of the data is safe to serialize as-is,
// but we need to convert the Maps to nested Arrays.
batchUIDToMeasuresKeyValueArray: Array.from(
batchUIDToMeasuresMap.entries(),
),
componentMeasures: componentMeasures,
duration,
flamechart,
internalModuleSourceToRanges: Array.from(
internalModuleSourceToRanges.entries(),
),
laneToLabelKeyValueArray: Array.from(laneToLabelMap.entries()),
laneToReactMeasureKeyValueArray: Array.from(
laneToReactMeasureMap.entries(),
),
nativeEvents,
networkMeasures,
otherUserTimingMarks,
reactVersion,
schedulingEvents,
snapshots,
snapshotHeight,
startTime,
suspenseEvents,
thrownErrors,
}),
);
const dataForRoots: Array<ProfilingDataForRootExport> = [];
profilingDataFrontend.dataForRoots.forEach(
({
commitData,
displayName,
initialTreeBaseDurations,
operations,
rootID,
snapshots,
}) => {
dataForRoots.push({
commitData: commitData.map(
({
changeDescriptions,
duration,
effectDuration,
fiberActualDurations,
fiberSelfDurations,
passiveEffectDuration,
priorityLevel,
timestamp,
updaters,
}) => ({
changeDescriptions:
changeDescriptions != null
? Array.from(changeDescriptions.entries())
: null,
duration,
effectDuration,
fiberActualDurations: Array.from(fiberActualDurations.entries()),
fiberSelfDurations: Array.from(fiberSelfDurations.entries()),
passiveEffectDuration,
priorityLevel,
timestamp,
updaters,
}),
),
displayName,
initialTreeBaseDurations: Array.from(
initialTreeBaseDurations.entries(),
),
operations,
rootID,
snapshots: Array.from(snapshots.entries()),
});
},
);
return {
version: PROFILER_EXPORT_VERSION,
dataForRoots,
timelineData,
};
}
export const getGradientColor = (value: number): string => {
const maxIndex = commitGradient.length - 1;
let index;
if (Number.isNaN(value)) {
index = 0;
} else if (!Number.isFinite(value)) {
index = maxIndex;
} else {
index = Math.max(0, Math.min(maxIndex, value)) * maxIndex;
}
return commitGradient[Math.round(index)];
};
export const formatDuration = (duration: number): number | string =>
Math.round(duration * 10) / 10 || '<0.1';
export const formatPercentage = (percentage: number): number =>
Math.round(percentage * 100);
export const formatTime = (timestamp: number): number =>
Math.round(Math.round(timestamp) / 100) / 10;
export const scale =
(
minValue: number,
maxValue: number,
minRange: number,
maxRange: number,
): ((value: number, fallbackValue: number) => number) =>
(value: number, fallbackValue: number) =>
maxValue - minValue === 0
? fallbackValue
: ((value - minValue) / (maxValue - minValue)) * (maxRange - minRange);
| 30.090186 | 121 | 0.627901 |
Effective-Python-Penetration-Testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import {useContext} from 'react';
import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
import SearchInput from '../SearchInput';
type Props = {};
export default function ComponentSearchInput(props: Props): React.Node {
const {searchIndex, searchResults, searchText} = useContext(TreeStateContext);
const dispatch = useContext(TreeDispatcherContext);
const search = (text: string) =>
dispatch({type: 'SET_SEARCH_TEXT', payload: text});
const goToNextResult = () => dispatch({type: 'GO_TO_NEXT_SEARCH_RESULT'});
const goToPreviousResult = () =>
dispatch({type: 'GO_TO_PREVIOUS_SEARCH_RESULT'});
return (
<SearchInput
goToNextResult={goToNextResult}
goToPreviousResult={goToPreviousResult}
placeholder="Search (text or /regex/)"
search={search}
searchIndex={searchIndex}
searchResultsCount={searchResults.length}
searchText={searchText}
testName="ComponentSearchInput"
/>
);
}
| 28.560976 | 80 | 0.701899 |
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 {Point} from './view-base';
import type {
FlamechartStackFrame,
NativeEvent,
NetworkMeasure,
ReactComponentMeasure,
ReactEventInfo,
ReactMeasure,
ReactMeasureType,
SchedulingEvent,
Snapshot,
SuspenseEvent,
ThrownError,
TimelineData,
UserTimingMark,
} from './types';
import * as React from 'react';
import {
formatDuration,
formatTimestamp,
trimString,
getSchedulingEventLabel,
} from './utils/formatting';
import {getBatchRange} from './utils/getBatchRange';
import useSmartTooltip from './utils/useSmartTooltip';
import styles from './EventTooltip.css';
const MAX_TOOLTIP_TEXT_LENGTH = 60;
type Props = {
canvasRef: {current: HTMLCanvasElement | null},
data: TimelineData,
height: number,
hoveredEvent: ReactEventInfo | null,
origin: Point,
width: number,
};
function getReactMeasureLabel(type: ReactMeasureType): string | null {
switch (type) {
case 'commit':
return 'react commit';
case 'render-idle':
return 'react idle';
case 'render':
return 'react render';
case 'layout-effects':
return 'react layout effects';
case 'passive-effects':
return 'react passive effects';
default:
return null;
}
}
export default function EventTooltip({
canvasRef,
data,
height,
hoveredEvent,
origin,
width,
}: Props): React.Node {
const ref = useSmartTooltip({
canvasRef,
mouseX: origin.x,
mouseY: origin.y,
});
if (hoveredEvent === null) {
return null;
}
const {
componentMeasure,
flamechartStackFrame,
measure,
nativeEvent,
networkMeasure,
schedulingEvent,
snapshot,
suspenseEvent,
thrownError,
userTimingMark,
} = hoveredEvent;
let content = null;
if (componentMeasure !== null) {
content = (
<TooltipReactComponentMeasure componentMeasure={componentMeasure} />
);
} else if (nativeEvent !== null) {
content = <TooltipNativeEvent nativeEvent={nativeEvent} />;
} else if (networkMeasure !== null) {
content = <TooltipNetworkMeasure networkMeasure={networkMeasure} />;
} else if (schedulingEvent !== null) {
content = (
<TooltipSchedulingEvent data={data} schedulingEvent={schedulingEvent} />
);
} else if (snapshot !== null) {
content = (
<TooltipSnapshot height={height} snapshot={snapshot} width={width} />
);
} else if (suspenseEvent !== null) {
content = <TooltipSuspenseEvent suspenseEvent={suspenseEvent} />;
} else if (measure !== null) {
content = <TooltipReactMeasure data={data} measure={measure} />;
} else if (flamechartStackFrame !== null) {
content = <TooltipFlamechartNode stackFrame={flamechartStackFrame} />;
} else if (userTimingMark !== null) {
content = <TooltipUserTimingMark mark={userTimingMark} />;
} else if (thrownError !== null) {
content = <TooltipThrownError thrownError={thrownError} />;
}
if (content !== null) {
return (
<div className={styles.Tooltip} ref={ref}>
{content}
</div>
);
} else {
return null;
}
}
const TooltipReactComponentMeasure = ({
componentMeasure,
}: {
componentMeasure: ReactComponentMeasure,
}) => {
const {componentName, duration, timestamp, type, warning} = componentMeasure;
let label = componentName;
switch (type) {
case 'render':
label += ' rendered';
break;
case 'layout-effect-mount':
label += ' mounted layout effect';
break;
case 'layout-effect-unmount':
label += ' unmounted layout effect';
break;
case 'passive-effect-mount':
label += ' mounted passive effect';
break;
case 'passive-effect-unmount':
label += ' unmounted passive effect';
break;
}
return (
<>
<div className={styles.TooltipSection}>
{trimString(label, 768)}
<div className={styles.Divider} />
<div className={styles.DetailsGrid}>
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
<div className={styles.DetailsGridLabel}>Duration:</div>
<div>{formatDuration(duration)}</div>
</div>
</div>
{warning !== null && (
<div className={styles.TooltipWarningSection}>
<div className={styles.WarningText}>{warning}</div>
</div>
)}
</>
);
};
const TooltipFlamechartNode = ({
stackFrame,
}: {
stackFrame: FlamechartStackFrame,
}) => {
const {name, timestamp, duration, locationLine, locationColumn} = stackFrame;
return (
<div className={styles.TooltipSection}>
<span className={styles.FlamechartStackFrameName}>{name}</span>
<div className={styles.DetailsGrid}>
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
<div className={styles.DetailsGridLabel}>Duration:</div>
<div>{formatDuration(duration)}</div>
{(locationLine !== undefined || locationColumn !== undefined) && (
<>
<div className={styles.DetailsGridLabel}>Location:</div>
<div>
line {locationLine}, column {locationColumn}
</div>
</>
)}
</div>
</div>
);
};
const TooltipNativeEvent = ({nativeEvent}: {nativeEvent: NativeEvent}) => {
const {duration, timestamp, type, warning} = nativeEvent;
return (
<>
<div className={styles.TooltipSection}>
<span className={styles.NativeEventName}>{trimString(type, 768)}</span>
event
<div className={styles.Divider} />
<div className={styles.DetailsGrid}>
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
<div className={styles.DetailsGridLabel}>Duration:</div>
<div>{formatDuration(duration)}</div>
</div>
</div>
{warning !== null && (
<div className={styles.TooltipWarningSection}>
<div className={styles.WarningText}>{warning}</div>
</div>
)}
</>
);
};
const TooltipNetworkMeasure = ({
networkMeasure,
}: {
networkMeasure: NetworkMeasure,
}) => {
const {
finishTimestamp,
lastReceivedDataTimestamp,
priority,
sendRequestTimestamp,
url,
} = networkMeasure;
let urlToDisplay = url;
if (urlToDisplay.length > MAX_TOOLTIP_TEXT_LENGTH) {
const half = Math.floor(MAX_TOOLTIP_TEXT_LENGTH / 2);
urlToDisplay = url.slice(0, half) + '…' + url.slice(url.length - half);
}
const timestampBegin = sendRequestTimestamp;
const timestampEnd = finishTimestamp || lastReceivedDataTimestamp;
const duration =
timestampEnd > 0
? formatDuration(finishTimestamp - timestampBegin)
: '(incomplete)';
return (
<div className={styles.SingleLineTextSection}>
{duration} <span className={styles.DimText}>{priority}</span>{' '}
{urlToDisplay}
</div>
);
};
const TooltipSchedulingEvent = ({
data,
schedulingEvent,
}: {
data: TimelineData,
schedulingEvent: SchedulingEvent,
}) => {
const label = getSchedulingEventLabel(schedulingEvent);
if (!label) {
if (__DEV__) {
console.warn(
'Unexpected schedulingEvent type "%s"',
schedulingEvent.type,
);
}
return null;
}
let laneLabels = null;
let lanes = null;
switch (schedulingEvent.type) {
case 'schedule-render':
case 'schedule-state-update':
case 'schedule-force-update':
lanes = schedulingEvent.lanes;
laneLabels = lanes.map(
lane => ((data.laneToLabelMap.get(lane): any): string),
);
break;
}
const {componentName, timestamp, warning} = schedulingEvent;
return (
<>
<div className={styles.TooltipSection}>
{componentName && (
<span className={styles.ComponentName}>
{trimString(componentName, 100)}
</span>
)}
{label}
<div className={styles.Divider} />
<div className={styles.DetailsGrid}>
{laneLabels !== null && lanes !== null && (
<>
<div className={styles.DetailsGridLabel}>Lanes:</div>
<div>
{laneLabels.join(', ')} ({lanes.join(', ')})
</div>
</>
)}
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
</div>
</div>
{warning !== null && (
<div className={styles.TooltipWarningSection}>
<div className={styles.WarningText}>{warning}</div>
</div>
)}
</>
);
};
const TooltipSnapshot = ({
height,
snapshot,
width,
}: {
height: number,
snapshot: Snapshot,
width: number,
}) => {
const aspectRatio = snapshot.width / snapshot.height;
// Zoomed in view should not be any bigger than the DevTools viewport.
let safeWidth = snapshot.width;
let safeHeight = snapshot.height;
if (safeWidth > width) {
safeWidth = width;
safeHeight = safeWidth / aspectRatio;
}
if (safeHeight > height) {
safeHeight = height;
safeWidth = safeHeight * aspectRatio;
}
return (
<img
className={styles.Image}
src={snapshot.imageSource}
style={{height: safeHeight, width: safeWidth}}
/>
);
};
const TooltipSuspenseEvent = ({
suspenseEvent,
}: {
suspenseEvent: SuspenseEvent,
}) => {
const {
componentName,
duration,
phase,
promiseName,
resolution,
timestamp,
warning,
} = suspenseEvent;
let label = 'suspended';
if (phase !== null) {
label += ` during ${phase}`;
}
return (
<>
<div className={styles.TooltipSection}>
{componentName && (
<span className={styles.ComponentName}>
{trimString(componentName, 100)}
</span>
)}
{label}
<div className={styles.Divider} />
<div className={styles.DetailsGrid}>
{promiseName !== null && (
<>
<div className={styles.DetailsGridLabel}>Resource:</div>
<div className={styles.DetailsGridLongValue}>{promiseName}</div>
</>
)}
<div className={styles.DetailsGridLabel}>Status:</div>
<div>{resolution}</div>
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
{duration !== null && (
<>
<div className={styles.DetailsGridLabel}>Duration:</div>
<div>{formatDuration(duration)}</div>
</>
)}
</div>
</div>
{warning !== null && (
<div className={styles.TooltipWarningSection}>
<div className={styles.WarningText}>{warning}</div>
</div>
)}
</>
);
};
const TooltipReactMeasure = ({
data,
measure,
}: {
data: TimelineData,
measure: ReactMeasure,
}) => {
const label = getReactMeasureLabel(measure.type);
if (!label) {
if (__DEV__) {
console.warn('Unexpected measure type "%s"', measure.type);
}
return null;
}
const {batchUID, duration, timestamp, lanes} = measure;
const [startTime, stopTime] = getBatchRange(batchUID, data);
const laneLabels = lanes.map(
lane => ((data.laneToLabelMap.get(lane): any): string),
);
return (
<div className={styles.TooltipSection}>
<span className={styles.ReactMeasureLabel}>{label}</span>
<div className={styles.Divider} />
<div className={styles.DetailsGrid}>
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
{measure.type !== 'render-idle' && (
<>
<div className={styles.DetailsGridLabel}>Duration:</div>
<div>{formatDuration(duration)}</div>
</>
)}
<div className={styles.DetailsGridLabel}>Batch duration:</div>
<div>{formatDuration(stopTime - startTime)}</div>
<div className={styles.DetailsGridLabel}>
Lane{lanes.length === 1 ? '' : 's'}:
</div>
<div>
{laneLabels.length > 0
? `${laneLabels.join(', ')} (${lanes.join(', ')})`
: lanes.join(', ')}
</div>
</div>
</div>
);
};
const TooltipUserTimingMark = ({mark}: {mark: UserTimingMark}) => {
const {name, timestamp} = mark;
return (
<div className={styles.TooltipSection}>
<span className={styles.UserTimingLabel}>{name}</span>
<div className={styles.Divider} />
<div className={styles.DetailsGrid}>
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
</div>
</div>
);
};
const TooltipThrownError = ({thrownError}: {thrownError: ThrownError}) => {
const {componentName, message, phase, timestamp} = thrownError;
const label = `threw an error during ${phase}`;
return (
<div className={styles.TooltipSection}>
{componentName && (
<span className={styles.ComponentName}>
{trimString(componentName, 100)}
</span>
)}
<span className={styles.UserTimingLabel}>{label}</span>
<div className={styles.Divider} />
<div className={styles.DetailsGrid}>
<div className={styles.DetailsGridLabel}>Timestamp:</div>
<div>{formatTimestamp(timestamp)}</div>
{message !== '' && (
<>
<div className={styles.DetailsGridLabel}>Error:</div>
<div>{message}</div>
</>
)}
</div>
</div>
);
};
| 25.793774 | 79 | 0.604822 |
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/ReactFlightDOMServerBrowser';
| 22.272727 | 66 | 0.705882 |
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 {useSyncExternalStoreWithSelector} from 'use-sync-external-store/src/useSyncExternalStoreWithSelector';
| 24.461538 | 110 | 0.745455 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('SelectEventPlugin', () => {
let container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
// See https://github.com/facebook/react/pull/3639 for details.
it('does not get confused when dependent events are registered independently', () => {
const select = jest.fn();
const onSelect = event => {
expect(typeof event).toBe('object');
expect(event.type).toBe('select');
expect(event.target).toBe(node);
select(event.currentTarget);
};
// Pass `onMouseDown` so React registers a top-level listener.
const node = ReactDOM.render(
<input type="text" onMouseDown={function () {}} />,
container,
);
// Trigger `mousedown` and `mouseup`. Note that
// React is not currently listening to `mouseup`.
node.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
}),
);
node.dispatchEvent(
new MouseEvent('mouseup', {
bubbles: true,
cancelable: true,
}),
);
// Now subscribe to `onSelect`.
ReactDOM.render(<input type="text" onSelect={onSelect} />, container);
node.focus();
// This triggers a `select` event in our polyfill.
node.dispatchEvent(
new KeyboardEvent('keydown', {bubbles: true, cancelable: true}),
);
// Verify that it doesn't get "stuck" waiting for
// a `mouseup` event that it has "missed" because
// a top-level listener didn't exist yet.
expect(select).toHaveBeenCalledTimes(1);
});
it('should fire `onSelect` when a listener is present', () => {
const select = jest.fn();
const onSelect = event => {
expect(typeof event).toBe('object');
expect(event.type).toBe('select');
expect(event.target).toBe(node);
select(event.currentTarget);
};
const node = ReactDOM.render(
<input type="text" onSelect={onSelect} />,
container,
);
node.focus();
let nativeEvent = new MouseEvent('focus', {
bubbles: true,
cancelable: true,
});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(0);
nativeEvent = new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(0);
nativeEvent = new MouseEvent('mouseup', {bubbles: true, cancelable: true});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(1);
});
it('should fire `onSelectCapture` when a listener is present', () => {
const select = jest.fn();
const onSelectCapture = event => {
expect(typeof event).toBe('object');
expect(event.type).toBe('select');
expect(event.target).toBe(node);
select(event.currentTarget);
};
const node = ReactDOM.render(
<input type="text" onSelectCapture={onSelectCapture} />,
container,
);
node.focus();
let nativeEvent = new MouseEvent('focus', {
bubbles: true,
cancelable: true,
});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(0);
nativeEvent = new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(0);
nativeEvent = new MouseEvent('mouseup', {bubbles: true, cancelable: true});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(1);
});
// Regression test for https://github.com/facebook/react/issues/11379
it('should not wait for `mouseup` after receiving `dragend`', () => {
const select = jest.fn();
const onSelect = event => {
expect(typeof event).toBe('object');
expect(event.type).toBe('select');
expect(event.target).toBe(node);
select(event.currentTarget);
};
const node = ReactDOM.render(
<input type="text" onSelect={onSelect} />,
container,
);
node.focus();
let nativeEvent = new MouseEvent('focus', {
bubbles: true,
cancelable: true,
});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(0);
nativeEvent = new MouseEvent('mousedown', {
bubbles: true,
cancelable: true,
});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(0);
nativeEvent = new MouseEvent('dragend', {bubbles: true, cancelable: true});
node.dispatchEvent(nativeEvent);
expect(select).toHaveBeenCalledTimes(1);
});
it('should handle selectionchange events', function () {
const onSelect = jest.fn();
const node = ReactDOM.render(
<input type="text" onSelect={onSelect} />,
container,
);
node.focus();
// Make sure the event was not called before we emit the selection change event
expect(onSelect).toHaveBeenCalledTimes(0);
// This is dispatched e.g. when using CMD+a on macOS
document.dispatchEvent(
new Event('selectionchange', {bubbles: false, cancelable: false}),
);
expect(onSelect).toHaveBeenCalledTimes(1);
});
});
| 26.929648 | 88 | 0.637214 |
owtf | 'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-jsx-runtime.production.min.js');
} else {
module.exports = require('./cjs/react-jsx-runtime.development.js');
}
| 25.875 | 72 | 0.682243 |
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.
*/
const ariaProperties = {
'aria-current': 0, // state
'aria-description': 0,
'aria-details': 0,
'aria-disabled': 0, // state
'aria-hidden': 0, // state
'aria-invalid': 0, // state
'aria-keyshortcuts': 0,
'aria-label': 0,
'aria-roledescription': 0,
// Widget Attributes
'aria-autocomplete': 0,
'aria-checked': 0,
'aria-expanded': 0,
'aria-haspopup': 0,
'aria-level': 0,
'aria-modal': 0,
'aria-multiline': 0,
'aria-multiselectable': 0,
'aria-orientation': 0,
'aria-placeholder': 0,
'aria-pressed': 0,
'aria-readonly': 0,
'aria-required': 0,
'aria-selected': 0,
'aria-sort': 0,
'aria-valuemax': 0,
'aria-valuemin': 0,
'aria-valuenow': 0,
'aria-valuetext': 0,
// Live Region Attributes
'aria-atomic': 0,
'aria-busy': 0,
'aria-live': 0,
'aria-relevant': 0,
// Drag-and-Drop Attributes
'aria-dropeffect': 0,
'aria-grabbed': 0,
// Relationship Attributes
'aria-activedescendant': 0,
'aria-colcount': 0,
'aria-colindex': 0,
'aria-colspan': 0,
'aria-controls': 0,
'aria-describedby': 0,
'aria-errormessage': 0,
'aria-flowto': 0,
'aria-labelledby': 0,
'aria-owns': 0,
'aria-posinset': 0,
'aria-rowcount': 0,
'aria-rowindex': 0,
'aria-rowspan': 0,
'aria-setsize': 0,
};
export default ariaProperties;
| 21.907692 | 66 | 0.625 |
hackipy | /**
* Copyright (c) Meta Platforms, Inc. 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/ReactFlightDOMServerEdge';
| 22 | 66 | 0.702381 |
owtf | /** @license React v16.14.0
* react-jsx-runtime.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
if (process.env.NODE_ENV !== "production") {
(function() {
'use strict';
var React = require('react');
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = 0xeac7;
var REACT_PORTAL_TYPE = 0xeaca;
exports.Fragment = 0xeacb;
var REACT_STRICT_MODE_TYPE = 0xeacc;
var REACT_PROFILER_TYPE = 0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
var REACT_SUSPENSE_TYPE = 0xead1;
var REACT_SUSPENSE_LIST_TYPE = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_BLOCK_TYPE = 0xead9;
var REACT_SERVER_BLOCK_TYPE = 0xeada;
var REACT_FUNDAMENTAL_TYPE = 0xead5;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symbolFor('react.fragment');
REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
REACT_PROFILER_TYPE = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
REACT_MEMO_TYPE = symbolFor('react.memo');
REACT_LAZY_TYPE = symbolFor('react.lazy');
REACT_BLOCK_TYPE = symbolFor('react.block');
REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
REACT_SCOPE_TYPE = symbolFor('react.scope');
REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
function error(format) {
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = '';
if (currentlyValidatingElement) {
var name = getComponentName(currentlyValidatingElement.type);
var owner = currentlyValidatingElement._owner;
stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
}
stack += ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
}
var argsWithFormat = args.map(function (item) {
return '' + item;
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableScopeAPI = false; // Experimental Create Event Handle API.
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) {
return true;
}
}
return false;
}
var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
function describeComponentFrame (name, source, ownerName) {
var sourceInfo = '';
if (source) {
var path = source.fileName;
var fileName = path.replace(BEFORE_SLASH_RE, '');
{
// In DEV, include code for a common special case:
// prefer "folder/index.js" instead of just "index.js".
if (/^index\./.test(fileName)) {
var match = path.match(BEFORE_SLASH_RE);
if (match) {
var pathBeforeSlash = match[1];
if (pathBeforeSlash) {
var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
fileName = folderName + '/' + fileName;
}
}
}
}
sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
} else if (ownerName) {
sourceInfo = ' (created by ' + ownerName + ')';
}
return '\n in ' + (name || 'Unknown') + sourceInfo;
}
var Resolved = 1;
function refineResolvedLazyComponent(lazyComponent) {
return lazyComponent._status === Resolved ? lazyComponent._result : null;
}
function getWrappedName(outerType, innerType, wrapperName) {
var functionName = innerType.displayName || innerType.name || '';
return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
}
function getComponentName(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case exports.Fragment:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case REACT_PROFILER_TYPE:
return "Profiler";
case REACT_STRICT_MODE_TYPE:
return 'StrictMode';
case REACT_SUSPENSE_TYPE:
return 'Suspense';
case REACT_SUSPENSE_LIST_TYPE:
return 'SuspenseList';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
return 'Context.Consumer';
case REACT_PROVIDER_TYPE:
return 'Context.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
return getComponentName(type.type);
case REACT_BLOCK_TYPE:
return getComponentName(type.render);
case REACT_LAZY_TYPE:
{
var thenable = type;
var resolvedThenable = refineResolvedLazyComponent(thenable);
if (resolvedThenable) {
return getComponentName(resolvedThenable);
}
break;
}
}
}
return null;
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var currentlyValidatingElement = null;
function setCurrentlyValidatingElement(element) {
{
currentlyValidatingElement = element;
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(Object.prototype.hasOwnProperty);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown;
var specialPropRefWarningShown;
var didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
{
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function warnIfStringRefCannotBeAutoConverted(config, self) {
{
if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
var componentName = getComponentName(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
function defineKeyPropWarningGetter(props, displayName) {
{
var warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
}
function defineRefPropWarningGetter(props, displayName) {
{
var warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
{
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* https://github.com/reactjs/rfcs/pull/107
* @param {*} type
* @param {object} props
* @param {string} key
*/
function jsxDEV(type, config, maybeKey, source, self) {
{
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null; // Currently, key can be spread in as a prop. This causes a potential
// issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
// or <div key="Hi" {...props} /> ). We want to deprecate key spread,
// but as an intermediary step, we will use jsxDEV for everything except
// <div {...props} key="Hi" />, because we aren't currently able to tell if
// key is explicitly declared to be undefined or not.
if (maybeKey !== undefined) {
key = '' + maybeKey;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
if (hasValidRef(config)) {
ref = config.ref;
warnIfStringRefCannotBeAutoConverted(config, self);
} // Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
}
var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement$1(element) {
currentlyValidatingElement = element;
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
{
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
}
function getDeclarationErrorAddendum() {
{
if (ReactCurrentOwner$1.current) {
var name = getComponentName(ReactCurrentOwner$1.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
}
function getSourceInfoErrorAddendum(source) {
{
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
{
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
{
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
// Give the component that originally created this child.
childOwner = " It was passed a child from " + getComponentName(element._owner.type) + ".";
}
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
{
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentName(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentName(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
{
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendum(source);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (Array.isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
var children = props.children;
if (children !== undefined) {
if (isStaticChildren) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
validateChildKeys(children[i], type);
}
if (Object.freeze) {
Object.freeze(children);
}
} else {
error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
}
} else {
validateChildKeys(children, type);
}
}
}
if (type === exports.Fragment) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
} // These two functions exist to still get child warnings in dev
// even with the prod transform. This means that jsxDEV is purely
// opt-in behavior for better messages but that we won't stop
// giving you warnings if you use production apis.
function jsxWithValidationStatic(type, props, key) {
{
return jsxWithValidation(type, props, key, true);
}
}
function jsxWithValidationDynamic(type, props, key) {
{
return jsxWithValidation(type, props, key, false);
}
}
var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
// for now we can ship identical prod functions
var jsxs = jsxWithValidationStatic ;
exports.jsx = jsx;
exports.jsxs = jsxs;
})();
}
| 31.149123 | 450 | 0.654422 |
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 {requestPostPaintCallback} from './ReactFiberConfig';
let postPaintCallbackScheduled = false;
let callbacks: Array<any | ((endTime: number) => void)> = [];
export function schedulePostPaintCallback(callback: (endTime: number) => void) {
callbacks.push(callback);
if (!postPaintCallbackScheduled) {
postPaintCallbackScheduled = true;
requestPostPaintCallback(endTime => {
for (let i = 0; i < callbacks.length; i++) {
callbacks[i](endTime);
}
postPaintCallbackScheduled = false;
callbacks = [];
});
}
}
| 27.296296 | 80 | 0.677588 |
owtf | const remark = require('remark');
const externalLinks = require('remark-external-links'); // Add _target and rel to external links
const customHeaders = require('./remark-header-custom-ids'); // Custom header id's for i18n
const images = require('remark-images'); // Improved image syntax
const unrwapImages = require('remark-unwrap-images'); // Removes <p> wrapper around images
const smartyPants = require('./remark-smartypants'); // Cleans up typography
const html = require('remark-html');
module.exports = {
remarkPlugins: [
externalLinks,
customHeaders,
images,
unrwapImages,
smartyPants,
],
markdownToHtml,
};
async function markdownToHtml(markdown) {
const result = await remark()
.use(externalLinks)
.use(customHeaders)
.use(images)
.use(unrwapImages)
.use(smartyPants)
.use(html)
.process(markdown);
return result.toString();
}
| 28 | 96 | 0.703786 |
Effective-Python-Penetration-Testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import {Fragment, useContext, useMemo, useState} from 'react';
import Store from 'react-devtools-shared/src/devtools/store';
import ButtonIcon from '../ButtonIcon';
import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
import {SettingsContext} from '../Settings/SettingsContext';
import {StoreContext} from '../context';
import {useSubscription} from '../hooks';
import {logEvent} from 'react-devtools-shared/src/Logger';
import IndexableElementBadges from './IndexableElementBadges';
import IndexableDisplayName from './IndexableDisplayName';
import type {ItemData} from './Tree';
import type {Element as ElementType} from 'react-devtools-shared/src/frontend/types';
import styles from './Element.css';
import Icon from '../Icon';
type Props = {
data: ItemData,
index: number,
style: Object,
...
};
export default function Element({data, index, style}: Props): React.Node {
const store = useContext(StoreContext);
const {ownerFlatTree, ownerID, selectedElementID} =
useContext(TreeStateContext);
const dispatch = useContext(TreeDispatcherContext);
const {showInlineWarningsAndErrors} = React.useContext(SettingsContext);
const element =
ownerFlatTree !== null
? ownerFlatTree[index]
: store.getElementAtIndex(index);
const [isHovered, setIsHovered] = useState(false);
const {isNavigatingWithKeyboard, onElementMouseEnter, treeFocused} = data;
const id = element === null ? null : element.id;
const isSelected = selectedElementID === id;
const errorsAndWarningsSubscription = useMemo(
() => ({
getCurrentValue: () =>
element === null
? {errorCount: 0, warningCount: 0}
: store.getErrorAndWarningCountForElementID(element.id),
subscribe: (callback: Function) => {
store.addListener('mutated', callback);
return () => store.removeListener('mutated', callback);
},
}),
[store, element],
);
const {errorCount, warningCount} = useSubscription<{
errorCount: number,
warningCount: number,
}>(errorsAndWarningsSubscription);
const handleDoubleClick = () => {
if (id !== null) {
dispatch({type: 'SELECT_OWNER', payload: id});
}
};
// $FlowFixMe[missing-local-annot]
const handleClick = ({metaKey}) => {
if (id !== null) {
logEvent({
event_name: 'select-element',
metadata: {source: 'click-element'},
});
dispatch({
type: 'SELECT_ELEMENT_BY_ID',
payload: metaKey ? null : id,
});
}
};
const handleMouseEnter = () => {
setIsHovered(true);
if (id !== null) {
onElementMouseEnter(id);
}
};
const handleMouseLeave = () => {
setIsHovered(false);
};
// $FlowFixMe[missing-local-annot]
const handleKeyDoubleClick = event => {
// Double clicks on key value are used for text selection (if the text has been truncated).
// They should not enter the owners tree view.
event.stopPropagation();
event.preventDefault();
};
// Handle elements that are removed from the tree while an async render is in progress.
if (element == null) {
console.warn(`<Element> Could not find element at index ${index}`);
// This return needs to happen after hooks, since hooks can't be conditional.
return null;
}
const {
depth,
displayName,
hocDisplayNames,
isStrictModeNonCompliant,
key,
compiledWithForget,
} = element;
// Only show strict mode non-compliance badges for top level elements.
// Showing an inline badge for every element in the tree would be noisy.
const showStrictModeBadge = isStrictModeNonCompliant && depth === 0;
let className = styles.Element;
if (isSelected) {
className = treeFocused
? styles.SelectedElement
: styles.InactiveSelectedElement;
} else if (isHovered && !isNavigatingWithKeyboard) {
className = styles.HoveredElement;
}
return (
<div
className={className}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onClick={handleClick}
onDoubleClick={handleDoubleClick}
style={style}
data-testname="ComponentTreeListItem"
data-depth={depth}>
{/* This wrapper is used by Tree for measurement purposes. */}
<div
className={styles.Wrapper}
style={{
// Left offset presents the appearance of a nested tree structure.
// We must use padding rather than margin/left because of the selected background color.
transform: `translateX(calc(${depth} * var(--indentation-size)))`,
}}>
{ownerID === null && (
<ExpandCollapseToggle element={element} store={store} />
)}
<IndexableDisplayName displayName={displayName} id={id} />
{key && (
<Fragment>
<span className={styles.KeyName}>key</span>="
<span
className={styles.KeyValue}
title={key}
onDoubleClick={handleKeyDoubleClick}>
{key}
</span>
"
</Fragment>
)}
<IndexableElementBadges
hocDisplayNames={hocDisplayNames}
compiledWithForget={compiledWithForget}
elementID={id}
className={styles.BadgesBlock}
/>
{showInlineWarningsAndErrors && errorCount > 0 && (
<Icon
type="error"
className={
isSelected && treeFocused
? styles.ErrorIconContrast
: styles.ErrorIcon
}
/>
)}
{showInlineWarningsAndErrors && warningCount > 0 && (
<Icon
type="warning"
className={
isSelected && treeFocused
? styles.WarningIconContrast
: styles.WarningIcon
}
/>
)}
{showStrictModeBadge && (
<Icon
className={
isSelected && treeFocused
? styles.StrictModeContrast
: styles.StrictMode
}
title="This component is not running in StrictMode."
type="strict-mode-non-compliant"
/>
)}
</div>
</div>
);
}
// Prevent double clicks on toggle from drilling into the owner list.
// $FlowFixMe[missing-local-annot]
const swallowDoubleClick = event => {
event.preventDefault();
event.stopPropagation();
};
type ExpandCollapseToggleProps = {
element: ElementType,
store: Store,
};
function ExpandCollapseToggle({element, store}: ExpandCollapseToggleProps) {
const {children, id, isCollapsed} = element;
// $FlowFixMe[missing-local-annot]
const toggleCollapsed = event => {
event.preventDefault();
event.stopPropagation();
store.toggleIsCollapsed(id, !isCollapsed);
};
// $FlowFixMe[missing-local-annot]
const stopPropagation = event => {
// Prevent the row from selecting
event.stopPropagation();
};
if (children.length === 0) {
return <div className={styles.ExpandCollapseToggle} />;
}
return (
<div
className={styles.ExpandCollapseToggle}
onMouseDown={stopPropagation}
onClick={toggleCollapsed}
onDoubleClick={swallowDoubleClick}>
<ButtonIcon type={isCollapsed ? 'collapsed' : 'expanded'} />
</div>
);
}
| 27.794677 | 98 | 0.628368 |
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 {Source} from 'shared/ReactElementType';
import type {LazyComponent} from 'react/src/ReactLazy';
import {enableComponentStackLocations} from 'shared/ReactFeatureFlags';
import {
REACT_SUSPENSE_TYPE,
REACT_SUSPENSE_LIST_TYPE,
REACT_FORWARD_REF_TYPE,
REACT_MEMO_TYPE,
REACT_LAZY_TYPE,
} from 'shared/ReactSymbols';
import {disableLogs, reenableLogs} from 'shared/ConsolePatchingDev';
import ReactSharedInternals from 'shared/ReactSharedInternals';
const {ReactCurrentDispatcher} = ReactSharedInternals;
let prefix;
export function describeBuiltInComponentFrame(
name: string,
source: void | null | Source,
ownerFn: void | null | Function,
): string {
if (enableComponentStackLocations) {
if (prefix === undefined) {
// Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
const match = x.stack.trim().match(/\n( *(at )?)/);
prefix = (match && match[1]) || '';
}
}
// We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
} else {
let ownerName = null;
if (__DEV__ && ownerFn) {
ownerName = ownerFn.displayName || ownerFn.name || null;
}
return describeComponentFrame(name, source, ownerName);
}
}
let reentry = false;
let componentFrameCache;
if (__DEV__) {
const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap<Function, string>();
}
/**
* Leverages native browser/VM stack frames to get proper details (e.g.
* filename, line + col number) for a single component in a component stack. We
* do this by:
* (1) throwing and catching an error in the function - this will be our
* control error.
* (2) calling the component which will eventually throw an error that we'll
* catch - this will be our sample error.
* (3) diffing the control and sample error stacks to find the stack frame
* which represents our component.
*/
export function describeNativeComponentFrame(
fn: Function,
construct: boolean,
): string {
// If something asked for a stack inside a fake render, it should get ignored.
if (!fn || reentry) {
return '';
}
if (__DEV__) {
const frame = componentFrameCache.get(fn);
if (frame !== undefined) {
return frame;
}
}
reentry = true;
const previousPrepareStackTrace = Error.prepareStackTrace;
// $FlowFixMe[incompatible-type] It does accept undefined.
Error.prepareStackTrace = undefined;
let previousDispatcher;
if (__DEV__) {
previousDispatcher = ReactCurrentDispatcher.current;
// Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher.current = null;
disableLogs();
}
/**
* Finding a common stack frame between sample and control errors can be
* tricky given the different types and levels of stack trace truncation from
* different JS VMs. So instead we'll attempt to control what that common
* frame should be through this object method:
* Having both the sample and control errors be in the function under the
* `DescribeNativeComponentFrameRoot` property, + setting the `name` and
* `displayName` properties of the function ensures that a stack
* frame exists that has the method name `DescribeNativeComponentFrameRoot` in
* it for both control and sample stacks.
*/
const RunInRootFrame = {
DetermineComponentFrameRoot(): [?string, ?string] {
let control;
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
const Fake = function () {
throw Error();
};
// $FlowFixMe[prop-missing]
Object.defineProperty(Fake.prototype, 'props', {
set: function () {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
},
});
if (typeof Reflect === 'object' && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
// $FlowFixMe[prop-missing] found when upgrading Flow
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
// TODO(luna): This will currently only throw if the function component
// tries to access React/ReactDOM/props. We should probably make this throw
// in simple components too
const maybePromise = fn();
// If the function component returns a promise, it's likely an async
// component, which we don't yet support. Attach a noop catch handler to
// silence the error.
// TODO: Implement component stacks for async client components?
if (maybePromise && typeof maybePromise.catch === 'function') {
maybePromise.catch(() => {});
}
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === 'string') {
return [sample.stack, control.stack];
}
}
return [null, null];
},
};
// $FlowFixMe[prop-missing]
RunInRootFrame.DetermineComponentFrameRoot.displayName =
'DetermineComponentFrameRoot';
const namePropDescriptor = Object.getOwnPropertyDescriptor(
RunInRootFrame.DetermineComponentFrameRoot,
'name',
);
// Before ES6, the `name` property was not configurable.
if (namePropDescriptor && namePropDescriptor.configurable) {
// V8 utilizes a function's `name` property when generating a stack trace.
Object.defineProperty(
RunInRootFrame.DetermineComponentFrameRoot,
// Configurable properties can be updated even if its writable descriptor
// is set to `false`.
// $FlowFixMe[cannot-write]
'name',
{value: 'DetermineComponentFrameRoot'},
);
}
try {
const [sampleStack, controlStack] =
RunInRootFrame.DetermineComponentFrameRoot();
if (sampleStack && controlStack) {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
const sampleLines = sampleStack.split('\n');
const controlLines = controlStack.split('\n');
let s = 0;
let c = 0;
while (
s < sampleLines.length &&
!sampleLines[s].includes('DetermineComponentFrameRoot')
) {
s++;
}
while (
c < controlLines.length &&
!controlLines[c].includes('DetermineComponentFrameRoot')
) {
c++;
}
// We couldn't find our intentionally injected common root frame, attempt
// to find another common root frame by search from the bottom of the
// control stack...
if (s === sampleLines.length || c === controlLines.length) {
s = sampleLines.length - 1;
c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
}
}
for (; s >= 1 && c >= 0; s--, c--) {
// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) {
do {
s--;
c--;
// We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
let frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
// If our component frame is labeled "<anonymous>"
// but we have a user-provided "displayName"
// splice it in to make the stack more readable.
if (fn.displayName && frame.includes('<anonymous>')) {
frame = frame.replace('<anonymous>', fn.displayName);
}
if (__DEV__) {
if (typeof fn === 'function') {
componentFrameCache.set(fn, frame);
}
}
// Return the line we found.
return frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
if (__DEV__) {
ReactCurrentDispatcher.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
}
// Fallback to just using the name if we couldn't make it throw.
const name = fn ? fn.displayName || fn.name : '';
const syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
if (__DEV__) {
if (typeof fn === 'function') {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
const BEFORE_SLASH_RE = /^(.*)[\\\/]/;
function describeComponentFrame(
name: null | string,
source: void | null | Source,
ownerName: null | string,
) {
let sourceInfo = '';
if (__DEV__ && source) {
const path = source.fileName;
let fileName = path.replace(BEFORE_SLASH_RE, '');
// In DEV, include code for a common special case:
// prefer "folder/index.js" instead of just "index.js".
if (/^index\./.test(fileName)) {
const match = path.match(BEFORE_SLASH_RE);
if (match) {
const pathBeforeSlash = match[1];
if (pathBeforeSlash) {
const folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
fileName = folderName + '/' + fileName;
}
}
}
sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
} else if (ownerName) {
sourceInfo = ' (created by ' + ownerName + ')';
}
return '\n in ' + (name || 'Unknown') + sourceInfo;
}
export function describeClassComponentFrame(
ctor: Function,
source: void | null | Source,
ownerFn: void | null | Function,
): string {
if (enableComponentStackLocations) {
return describeNativeComponentFrame(ctor, true);
} else {
return describeFunctionComponentFrame(ctor, source, ownerFn);
}
}
export function describeFunctionComponentFrame(
fn: Function,
source: void | null | Source,
ownerFn: void | null | Function,
): string {
if (enableComponentStackLocations) {
return describeNativeComponentFrame(fn, false);
} else {
if (!fn) {
return '';
}
const name = fn.displayName || fn.name || null;
let ownerName = null;
if (__DEV__ && ownerFn) {
ownerName = ownerFn.displayName || ownerFn.name || null;
}
return describeComponentFrame(name, source, ownerName);
}
}
function shouldConstruct(Component: Function) {
const prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
export function describeUnknownElementTypeFrameInDEV(
type: any,
source: void | null | Source,
ownerFn: void | null | Function,
): string {
if (!__DEV__) {
return '';
}
if (type == null) {
return '';
}
if (typeof type === 'function') {
if (enableComponentStackLocations) {
return describeNativeComponentFrame(type, shouldConstruct(type));
} else {
return describeFunctionComponentFrame(type, source, ownerFn);
}
}
if (typeof type === 'string') {
return describeBuiltInComponentFrame(type, source, ownerFn);
}
switch (type) {
case REACT_SUSPENSE_TYPE:
return describeBuiltInComponentFrame('Suspense', source, ownerFn);
case REACT_SUSPENSE_LIST_TYPE:
return describeBuiltInComponentFrame('SuspenseList', source, ownerFn);
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render, source, ownerFn);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE: {
const lazyComponent: LazyComponent<any, any> = (type: any);
const payload = lazyComponent._payload;
const init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(
init(payload),
source,
ownerFn,
);
} catch (x) {}
}
}
}
return '';
}
| 33.644928 | 98 | 0.612816 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {BoxStyle} from './types';
/**
* This mirrors react-native/Libraries/Inspector/resolveBoxStyle.js (but without RTL support).
*
* Resolve a style property into it's component parts, e.g.
*
* resolveBoxStyle('margin', {margin: 5, marginBottom: 10})
* -> {top: 5, left: 5, right: 5, bottom: 10}
*/
export default function resolveBoxStyle(
prefix: string,
style: Object,
): BoxStyle | null {
let hasParts = false;
const result = {
bottom: 0,
left: 0,
right: 0,
top: 0,
};
const styleForAll = style[prefix];
if (styleForAll != null) {
// eslint-disable-next-line no-for-of-loops/no-for-of-loops
for (const key of Object.keys(result)) {
result[key] = styleForAll;
}
hasParts = true;
}
const styleForHorizontal = style[prefix + 'Horizontal'];
if (styleForHorizontal != null) {
result.left = styleForHorizontal;
result.right = styleForHorizontal;
hasParts = true;
} else {
const styleForLeft = style[prefix + 'Left'];
if (styleForLeft != null) {
result.left = styleForLeft;
hasParts = true;
}
const styleForRight = style[prefix + 'Right'];
if (styleForRight != null) {
result.right = styleForRight;
hasParts = true;
}
const styleForEnd = style[prefix + 'End'];
if (styleForEnd != null) {
// TODO RTL support
result.right = styleForEnd;
hasParts = true;
}
const styleForStart = style[prefix + 'Start'];
if (styleForStart != null) {
// TODO RTL support
result.left = styleForStart;
hasParts = true;
}
}
const styleForVertical = style[prefix + 'Vertical'];
if (styleForVertical != null) {
result.bottom = styleForVertical;
result.top = styleForVertical;
hasParts = true;
} else {
const styleForBottom = style[prefix + 'Bottom'];
if (styleForBottom != null) {
result.bottom = styleForBottom;
hasParts = true;
}
const styleForTop = style[prefix + 'Top'];
if (styleForTop != null) {
result.top = styleForTop;
hasParts = true;
}
}
return hasParts ? result : null;
}
| 23.840426 | 94 | 0.626392 |
null | #!/usr/bin/env node
'use strict';
const {exec, spawn} = require('child-process-promise');
const {join} = require('path');
const {readFileSync} = require('fs');
const theme = require('./theme');
const {getDateStringForCommit, logPromise, printDiff} = require('./utils');
const cwd = join(__dirname, '..', '..');
const CIRCLE_CI_BUILD = 12707;
const COMMIT = 'b3d1a81a9';
const VERSION = '1.2.3';
const run = async () => {
const defaultOptions = {
cwd,
env: process.env,
};
try {
// Start with a known build/revision:
// https://circleci.com/gh/facebook/react/12707
let promise = spawn(
'node',
[
'./scripts/release/prepare-release-from-ci.js',
`--build=${CIRCLE_CI_BUILD}`,
],
defaultOptions
);
logPromise(
promise,
theme`Checking out "next" build {version ${CIRCLE_CI_BUILD}}`
);
await promise;
const dateString = await getDateStringForCommit(COMMIT);
// Upgrade the above build top a known React version.
// Note that using the --local flag skips NPM checkout.
// This isn't totally necessary but is useful if we want to test an unpublished "next" build.
promise = spawn(
'node',
[
'./scripts/release/prepare-release-from-npm.js',
`--version=0.0.0-${COMMIT}-${dateString}`,
'--local',
],
defaultOptions
);
promise.childProcess.stdin.setEncoding('utf-8');
promise.childProcess.stdout.setEncoding('utf-8');
promise.childProcess.stdout.on('data', data => {
if (data.includes('✓ Version for')) {
// Update all packages to a stable version
promise.childProcess.stdin.write(VERSION);
} else if (data.includes('(y/N)')) {
// Accept all of the confirmation prompts
promise.childProcess.stdin.write('y');
}
});
logPromise(promise, theme`Preparing stable release {version ${VERSION}}`);
await promise;
const beforeContents = readFileSync(
join(cwd, 'scripts/release/snapshot-test.snapshot'),
'utf-8'
);
await exec('cp build/temp.diff scripts/release/snapshot-test.snapshot', {
cwd,
});
const afterContents = readFileSync(
join(cwd, 'scripts/release/snapshot-test.snapshot'),
'utf-8'
);
if (beforeContents === afterContents) {
console.log(theme.header`Snapshot test passed.`);
} else {
printDiff(
'scripts/release/snapshot-test.snapshot',
beforeContents,
afterContents
);
console.log();
console.error(theme.error('Snapshot test failed!'));
console.log();
console.log(
'If this failure was expected, please update the contents of the snapshot file:'
);
console.log(
theme` {command git add} {path scripts/release/snapshot-test.snapshot}`
);
console.log(
theme` {command git commit -m "Updating release script snapshot file."}`
);
process.exit(1);
}
} catch (error) {
console.error(theme.error(error));
process.exit(1);
}
};
run();
| 27.238532 | 97 | 0.61196 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Interaction} from './useCanvasInteraction';
import type {IntrinsicSize, Rect, Size} from './geometry';
import type {Layouter} from './layouter';
import type {ViewRefs} from './Surface';
import {Surface} from './Surface';
import {
rectEqualToRect,
intersectionOfRects,
rectIntersectsRect,
sizeIsEmpty,
sizeIsValid,
unionOfRects,
zeroRect,
} from './geometry';
import {noopLayout, viewsToLayout, collapseLayoutIntoViews} from './layouter';
/**
* Base view class that can be subclassed to draw custom content or manage
* subclasses.
*/
export class View {
_backgroundColor: string | null;
currentCursor: string | null = null;
surface: Surface;
frame: Rect;
visibleArea: Rect;
superview: ?View;
subviews: View[] = [];
/**
* An injected function that lays out our subviews.
* @private
*/
_layouter: Layouter;
/**
* Whether this view needs to be drawn.
*
* NOTE: Do not set directly! Use `setNeedsDisplay`.
*
* @see setNeedsDisplay
* @private
*/
_needsDisplay: boolean = true;
/**
* Whether the hierarchy below this view has subviews that need display.
*
* NOTE: Do not set directly! Use `setSubviewsNeedDisplay`.
*
* @see setSubviewsNeedDisplay
* @private
*/
_subviewsNeedDisplay: boolean = false;
constructor(
surface: Surface,
frame: Rect,
layouter: Layouter = noopLayout,
visibleArea: Rect = frame,
backgroundColor?: string | null = null,
) {
this._backgroundColor = backgroundColor || null;
this.surface = surface;
this.frame = frame;
this._layouter = layouter;
this.visibleArea = visibleArea;
}
/**
* Invalidates view's contents.
*
* Downward propagating; once called, all subviews of this view should also
* be invalidated.
*/
setNeedsDisplay() {
this._needsDisplay = true;
if (this.superview) {
this.superview._setSubviewsNeedDisplay();
}
this.subviews.forEach(subview => subview.setNeedsDisplay());
}
/**
* Informs superview that it has subviews that need to be drawn.
*
* Upward propagating; once called, all superviews of this view should also
* have `subviewsNeedDisplay` = true.
*
* @private
*/
_setSubviewsNeedDisplay() {
this._subviewsNeedDisplay = true;
if (this.superview) {
this.superview._setSubviewsNeedDisplay();
}
}
setFrame(newFrame: Rect) {
if (!rectEqualToRect(this.frame, newFrame)) {
this.frame = newFrame;
if (sizeIsValid(newFrame.size)) {
this.frame = newFrame;
} else {
this.frame = zeroRect;
}
this.setNeedsDisplay();
}
}
setVisibleArea(newVisibleArea: Rect) {
if (!rectEqualToRect(this.visibleArea, newVisibleArea)) {
if (sizeIsValid(newVisibleArea.size)) {
this.visibleArea = newVisibleArea;
} else {
this.visibleArea = zeroRect;
}
this.setNeedsDisplay();
}
}
/**
* A size that can be used as a hint by layout functions.
*
* Implementations should typically return the intrinsic content size or a
* size that fits all the view's content.
*
* The default implementation returns a size that fits all the view's
* subviews.
*
* Can be overridden by subclasses.
*/
desiredSize(): Size | IntrinsicSize {
if (this._needsDisplay) {
this.layoutSubviews();
}
const frames = this.subviews.map(subview => subview.frame);
return unionOfRects(...frames).size;
}
/**
* Appends `view` to the list of this view's `subviews`.
*/
addSubview(view: View) {
if (this.subviews.includes(view)) {
return;
}
this.subviews.push(view);
view.superview = this;
}
/**
* Breaks the subview-superview relationship between `view` and this view, if
* `view` is a subview of this view.
*/
removeSubview(view: View) {
const subviewIndex = this.subviews.indexOf(view);
if (subviewIndex === -1) {
return;
}
view.superview = undefined;
this.subviews.splice(subviewIndex, 1);
}
/**
* Removes all subviews from this view.
*/
removeAllSubviews() {
this.subviews.forEach(subview => (subview.superview = undefined));
this.subviews = [];
}
/**
* Executes the display flow if this view needs to be drawn.
*
* 1. Lays out subviews with `layoutSubviews`.
* 2. Draws content with `draw`.
*/
displayIfNeeded(context: CanvasRenderingContext2D, viewRefs: ViewRefs) {
if (
(this._needsDisplay || this._subviewsNeedDisplay) &&
rectIntersectsRect(this.frame, this.visibleArea) &&
!sizeIsEmpty(this.visibleArea.size)
) {
this.layoutSubviews();
if (this._needsDisplay) {
this._needsDisplay = false;
}
if (this._subviewsNeedDisplay) this._subviewsNeedDisplay = false;
// Clip anything drawn by the view to prevent it from overflowing its visible area.
const visibleArea = this.visibleArea;
const region = new Path2D();
region.rect(
visibleArea.origin.x,
visibleArea.origin.y,
visibleArea.size.width,
visibleArea.size.height,
);
context.save();
context.clip(region);
context.beginPath();
this.draw(context, viewRefs);
// Stop clipping
context.restore();
}
}
/**
* Layout self and subviews.
*
* Implementations should call `setNeedsDisplay` if a draw is required.
*
* The default implementation uses `this.layouter` to lay out subviews.
*
* Can be overwritten by subclasses that wish to manually manage their
* subviews' layout.
*
* NOTE: Do not call directly! Use `displayIfNeeded`.
*
* @see displayIfNeeded
*/
layoutSubviews() {
const {frame, _layouter, subviews, visibleArea} = this;
const existingLayout = viewsToLayout(subviews);
const newLayout = _layouter(existingLayout, frame);
collapseLayoutIntoViews(newLayout);
subviews.forEach((subview, subviewIndex) => {
if (rectIntersectsRect(visibleArea, subview.frame)) {
subview.setVisibleArea(intersectionOfRects(visibleArea, subview.frame));
} else {
subview.setVisibleArea(zeroRect);
}
});
}
/**
* Draw the contents of this view in the given canvas `context`.
*
* Defaults to drawing this view's `subviews`.
*
* To be overwritten by subclasses that wish to draw custom content.
*
* NOTE: Do not call directly! Use `displayIfNeeded`.
*
* @see displayIfNeeded
*/
draw(context: CanvasRenderingContext2D, viewRefs: ViewRefs) {
const {subviews, visibleArea} = this;
subviews.forEach(subview => {
if (rectIntersectsRect(visibleArea, subview.visibleArea)) {
subview.displayIfNeeded(context, viewRefs);
}
});
const backgroundColor = this._backgroundColor;
if (backgroundColor !== null) {
const desiredSize = this.desiredSize();
if (visibleArea.size.height > desiredSize.height) {
context.fillStyle = backgroundColor;
context.fillRect(
visibleArea.origin.x,
visibleArea.origin.y + desiredSize.height,
visibleArea.size.width,
visibleArea.size.height - desiredSize.height,
);
}
}
}
/**
* Handle an `interaction`.
*
* To be overwritten by subclasses that wish to handle interactions.
*
* NOTE: Do not call directly! Use `handleInteractionAndPropagateToSubviews`
*/
handleInteraction(interaction: Interaction, viewRefs: ViewRefs): ?boolean {}
/**
* Handle an `interaction` and propagates it to all of this view's
* `subviews`.
*
* NOTE: Should not be overridden! Subclasses should override
* `handleInteraction` instead.
*
* @see handleInteraction
* @protected
*/
handleInteractionAndPropagateToSubviews(
interaction: Interaction,
viewRefs: ViewRefs,
): boolean {
const {subviews, visibleArea} = this;
if (visibleArea.size.height === 0) {
return false;
}
// Pass the interaction to subviews first,
// so they have the opportunity to claim it before it bubbles.
//
// Views are painted first to last,
// so they should process interactions last to first,
// so views in front (on top) can claim the interaction first.
for (let i = subviews.length - 1; i >= 0; i--) {
const subview = subviews[i];
if (rectIntersectsRect(visibleArea, subview.visibleArea)) {
const didSubviewHandle =
subview.handleInteractionAndPropagateToSubviews(
interaction,
viewRefs,
) === true;
if (didSubviewHandle) {
return true;
}
}
}
const didSelfHandle =
this.handleInteraction(interaction, viewRefs) === true;
if (didSelfHandle) {
return true;
}
return false;
}
}
| 25.225434 | 89 | 0.64455 |
null | 'use strict';
const fs = require('fs');
const nodePath = require('path');
const inlinedHostConfigs = require('../shared/inlinedHostConfigs');
function resolveEntryFork(resolvedEntry, isFBBundle) {
// Pick which entry point fork to use:
// .modern.fb.js
// .classic.fb.js
// .fb.js
// .stable.js
// .experimental.js
// .js
if (isFBBundle) {
if (__EXPERIMENTAL__) {
// We can't currently use the true modern entry point because too many tests fail.
// TODO: Fix tests to not use ReactDOM.render or gate them. Then we can remove this.
return resolvedEntry;
}
const resolvedFBEntry = resolvedEntry.replace(
'.js',
__EXPERIMENTAL__ ? '.modern.fb.js' : '.classic.fb.js'
);
if (fs.existsSync(resolvedFBEntry)) {
return resolvedFBEntry;
}
const resolvedGenericFBEntry = resolvedEntry.replace('.js', '.fb.js');
if (fs.existsSync(resolvedGenericFBEntry)) {
return resolvedGenericFBEntry;
}
// Even if it's a FB bundle we fallthrough to pick stable or experimental if we don't have an FB fork.
}
const resolvedForkedEntry = resolvedEntry.replace(
'.js',
__EXPERIMENTAL__ ? '.experimental.js' : '.stable.js'
);
if (fs.existsSync(resolvedForkedEntry)) {
return resolvedForkedEntry;
}
// Just use the plain .js one.
return resolvedEntry;
}
function mockReact() {
jest.mock('react', () => {
const resolvedEntryPoint = resolveEntryFork(
require.resolve('react'),
global.__WWW__
);
return jest.requireActual(resolvedEntryPoint);
});
}
// When we want to unmock React we really need to mock it again.
global.__unmockReact = mockReact;
mockReact();
jest.mock('react/react.shared-subset', () => {
const resolvedEntryPoint = resolveEntryFork(
require.resolve('react/src/ReactSharedSubset'),
global.__WWW__
);
return jest.requireActual(resolvedEntryPoint);
});
// When testing the custom renderer code path through `react-reconciler`,
// turn the export into a function, and use the argument as host config.
const shimHostConfigPath = 'react-reconciler/src/ReactFiberConfig';
jest.mock('react-reconciler', () => {
return config => {
jest.mock(shimHostConfigPath, () => config);
return jest.requireActual('react-reconciler');
};
});
const shimServerStreamConfigPath = 'react-server/src/ReactServerStreamConfig';
const shimServerConfigPath = 'react-server/src/ReactFizzConfig';
const shimFlightServerConfigPath = 'react-server/src/ReactFlightServerConfig';
jest.mock('react-server', () => {
return config => {
jest.mock(shimServerStreamConfigPath, () => config);
jest.mock(shimServerConfigPath, () => config);
return jest.requireActual('react-server');
};
});
jest.mock('react-server/flight', () => {
return config => {
jest.mock(shimServerStreamConfigPath, () => config);
jest.mock(shimServerConfigPath, () => config);
jest.mock('react-server/src/ReactFlightServerConfigBundlerCustom', () => ({
isClientReference: config.isClientReference,
isServerReference: config.isServerReference,
getClientReferenceKey: config.getClientReferenceKey,
resolveClientReferenceMetadata: config.resolveClientReferenceMetadata,
}));
jest.mock(shimFlightServerConfigPath, () =>
jest.requireActual(
'react-server/src/forks/ReactFlightServerConfig.custom'
)
);
return jest.requireActual('react-server/flight');
};
});
const shimFlightClientConfigPath = 'react-client/src/ReactFlightClientConfig';
jest.mock('react-client/flight', () => {
return config => {
jest.mock(shimFlightClientConfigPath, () => config);
return jest.requireActual('react-client/flight');
};
});
const configPaths = [
'react-reconciler/src/ReactFiberConfig',
'react-client/src/ReactFlightClientConfig',
'react-server/src/ReactServerStreamConfig',
'react-server/src/ReactFizzConfig',
'react-server/src/ReactFlightServerConfig',
];
function mockAllConfigs(rendererInfo) {
configPaths.forEach(path => {
// We want the reconciler to pick up the host config for this renderer.
jest.mock(path, () => {
let idx = path.lastIndexOf('/');
let forkPath = path.slice(0, idx) + '/forks' + path.slice(idx);
let parts = rendererInfo.shortName.split('-');
while (parts.length) {
try {
const candidate = `${forkPath}.${parts.join('-')}.js`;
fs.statSync(nodePath.join(process.cwd(), 'packages', candidate));
return jest.requireActual(candidate);
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
// try without a part
}
parts.pop();
}
throw new Error(
`Expected to find a fork for ${path} but did not find one.`
);
});
});
}
// But for inlined host configs (such as React DOM, Native, etc), we
// mock their named entry points to establish a host config mapping.
inlinedHostConfigs.forEach(rendererInfo => {
if (rendererInfo.shortName === 'custom') {
// There is no inline entry point for the custom renderers.
// Instead, it's handled by the generic `react-reconciler` entry point above.
return;
}
rendererInfo.entryPoints.forEach(entryPoint => {
jest.mock(entryPoint, () => {
mockAllConfigs(rendererInfo);
const resolvedEntryPoint = resolveEntryFork(
require.resolve(entryPoint),
global.__WWW__
);
return jest.requireActual(resolvedEntryPoint);
});
});
});
// Make it possible to import this module inside
// the React package itself.
jest.mock('shared/ReactSharedInternals', () =>
jest.requireActual('react/src/ReactSharedInternalsClient')
);
// Make it possible to import this module inside
// the ReactDOM package itself.
jest.mock('shared/ReactDOMSharedInternals', () =>
jest.requireActual('react-dom/src/ReactDOMSharedInternals')
);
jest.mock('scheduler', () => jest.requireActual('scheduler/unstable_mock'));
| 31.901099 | 106 | 0.676132 |
PenetrationTestingScripts | // rAF never fires on devtools_page (because it's in the background)
// https://bugs.chromium.org/p/chromium/issues/detail?id=1241986#c31
// Since we render React elements here, we need to polyfill it with setTimeout
// The polyfill is based on https://gist.github.com/jalbam/5fe05443270fa6d8136238ec72accbc0
const FRAME_TIME = 16;
let lastTime = 0;
window.requestAnimationFrame = function (callback, element) {
const now = window.performance.now();
const nextTime = Math.max(lastTime + FRAME_TIME, now);
return setTimeout(function () {
callback((lastTime = nextTime));
}, nextTime - now);
};
window.cancelAnimationFrame = clearTimeout;
| 35.277778 | 91 | 0.745399 |
owtf | function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
// Compile this with Babel.
// babel --config-file ./babel.config.json BabelClasses.js --out-file BabelClasses-compiled.js --source-maps
let BabelClass = /*#__PURE__*/ (function (_React$Component) {
_inheritsLoose(BabelClass, _React$Component);
function BabelClass() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = BabelClass.prototype;
_proto.render = function render() {
return this.props.children;
};
return BabelClass;
})(React.Component);
let BabelClassWithFields = /*#__PURE__*/ (function (_React$Component2) {
_inheritsLoose(BabelClassWithFields, _React$Component2);
function BabelClassWithFields(...args) {
var _this;
_this = _React$Component2.call(this, ...args) || this;
_defineProperty(
_assertThisInitialized(_assertThisInitialized(_this)),
'props',
void 0
);
_defineProperty(
_assertThisInitialized(_assertThisInitialized(_this)),
'state',
{}
);
return _this;
}
var _proto2 = BabelClassWithFields.prototype;
_proto2.render = function render() {
return this.props.children;
};
return BabelClassWithFields;
})(React.Component);
//# sourceMappingURL=BabelClasses-compiled.js.map
| 22.08642 | 108 | 0.663456 |
Broken-Droid-Factory | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
// Polyfills for test environment
global.ReadableStream =
require('web-streams-polyfill/ponyfill/es6').ReadableStream;
global.TextEncoder = require('util').TextEncoder;
global.TextDecoder = require('util').TextDecoder;
// Don't wait before processing work on the server.
// TODO: we can replace this with FlightServer.act().
global.setTimeout = cb => cb();
let clientExports;
let turbopackMap;
let turbopackModules;
let React;
let ReactDOMServer;
let ReactServerDOMServer;
let ReactServerDOMClient;
let use;
describe('ReactFlightDOMEdge', () => {
beforeEach(() => {
jest.resetModules();
// Simulate the condition resolution
jest.mock('react', () => require('react/react.shared-subset'));
jest.mock('react-server-dom-turbopack/server', () =>
require('react-server-dom-turbopack/server.edge'),
);
const TurbopackMock = require('./utils/TurbopackMock');
clientExports = TurbopackMock.clientExports;
turbopackMap = TurbopackMock.turbopackMap;
turbopackModules = TurbopackMock.turbopackModules;
ReactServerDOMServer = require('react-server-dom-turbopack/server.edge');
jest.resetModules();
__unmockReact();
React = require('react');
ReactDOMServer = require('react-dom/server.edge');
ReactServerDOMClient = require('react-server-dom-turbopack/client.edge');
use = React.use;
});
async function readResult(stream) {
const reader = stream.getReader();
let result = '';
while (true) {
const {done, value} = await reader.read();
if (done) {
return result;
}
result += Buffer.from(value).toString('utf8');
}
}
it('should allow an alternative module mapping to be used for SSR', async () => {
function ClientComponent() {
return <span>Client Component</span>;
}
// The Client build may not have the same IDs as the Server bundles for the same
// component.
const ClientComponentOnTheClient = clientExports(ClientComponent);
const ClientComponentOnTheServer = clientExports(ClientComponent);
// In the SSR bundle this module won't exist. We simulate this by deleting it.
const clientId = turbopackMap[ClientComponentOnTheClient.$$id].id;
delete turbopackModules[clientId];
// Instead, we have to provide a translation from the client meta data to the SSR
// meta data.
const ssrMetadata = turbopackMap[ClientComponentOnTheServer.$$id];
const translationMap = {
[clientId]: {
'*': ssrMetadata,
},
};
function App() {
return <ClientComponentOnTheClient />;
}
const stream = ReactServerDOMServer.renderToReadableStream(
<App />,
turbopackMap,
);
const response = ReactServerDOMClient.createFromReadableStream(stream, {
ssrManifest: {
moduleMap: translationMap,
moduleLoading: null,
},
});
function ClientRoot() {
return use(response);
}
const ssrStream = await ReactDOMServer.renderToReadableStream(
<ClientRoot />,
);
const result = await readResult(ssrStream);
expect(result).toEqual('<span>Client Component</span>');
});
});
| 27.905983 | 85 | 0.680864 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('SyntheticMouseEvent', () => {
let container;
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
// The container has to be attached for events to fire.
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('should only use values from movementX/Y when event type is mousemove', () => {
const events = [];
const onMouseMove = event => {
events.push(event.movementX);
};
const onMouseDown = event => {
events.push(event.movementX);
};
const node = ReactDOM.render(
<div onMouseMove={onMouseMove} onMouseDown={onMouseDown} />,
container,
);
let event = new MouseEvent('mousemove', {
relatedTarget: null,
bubbles: true,
screenX: 2,
screenY: 2,
});
node.dispatchEvent(event);
event = new MouseEvent('mousemove', {
relatedTarget: null,
bubbles: true,
screenX: 8,
screenY: 8,
});
node.dispatchEvent(event);
// Now trigger a mousedown event to see if movementX has changed back to 0
event = new MouseEvent('mousedown', {
relatedTarget: null,
bubbles: true,
screenX: 25,
screenY: 65,
});
node.dispatchEvent(event);
expect(events.length).toBe(3);
expect(events[0]).toBe(0);
expect(events[1]).toBe(6);
expect(events[2]).toBe(0); // mousedown event should have movementX at 0
});
it('should correctly calculate movementX/Y for capture phase', () => {
const events = [];
const onMouseMove = event => {
events.push(['move', false, event.movementX, event.movementY]);
};
const onMouseMoveCapture = event => {
events.push(['move', true, event.movementX, event.movementY]);
};
const onMouseDown = event => {
events.push(['down', false, event.movementX, event.movementY]);
};
const onMouseDownCapture = event => {
events.push(['down', true, event.movementX, event.movementY]);
};
const node = ReactDOM.render(
<div
onMouseMove={onMouseMove}
onMouseMoveCapture={onMouseMoveCapture}
onMouseDown={onMouseDown}
onMouseDownCapture={onMouseDownCapture}
/>,
container,
);
let event = new MouseEvent('mousemove', {
relatedTarget: null,
bubbles: true,
screenX: 2,
screenY: 2,
});
node.dispatchEvent(event);
event = new MouseEvent('mousemove', {
relatedTarget: null,
bubbles: true,
screenX: 8,
screenY: 9,
});
node.dispatchEvent(event);
// Now trigger a mousedown event to see if movementX has changed back to 0
event = new MouseEvent('mousedown', {
relatedTarget: null,
bubbles: true,
screenX: 25,
screenY: 65,
});
node.dispatchEvent(event);
expect(events).toEqual([
['move', true, 0, 0],
['move', false, 0, 0],
['move', true, 6, 7],
['move', false, 6, 7],
['down', true, 0, 0],
['down', false, 0, 0],
]);
});
});
| 22.737931 | 84 | 0.598663 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
jest.resetModules();
const React = require('react');
let ReactFreshRuntime;
if (__DEV__) {
ReactFreshRuntime = require('react-refresh/runtime');
ReactFreshRuntime.injectIntoGlobalHook(global);
}
const ReactDOM = require('react-dom');
jest.resetModules();
const ReactART = require('react-art');
const ARTSVGMode = require('art/modes/svg');
const ARTCurrentMode = require('art/modes/current');
ARTCurrentMode.setCurrent(ARTSVGMode);
describe('ReactFresh', () => {
let container;
beforeEach(() => {
if (__DEV__) {
container = document.createElement('div');
document.body.appendChild(container);
}
});
afterEach(() => {
if (__DEV__) {
document.body.removeChild(container);
container = null;
}
});
it('can update components managed by different renderers independently', () => {
if (__DEV__) {
const InnerV1 = function () {
return <ReactART.Shape fill="blue" />;
};
ReactFreshRuntime.register(InnerV1, 'Inner');
const OuterV1 = function () {
return (
<div style={{color: 'blue'}}>
<ReactART.Surface>
<InnerV1 />
</ReactART.Surface>
</div>
);
};
ReactFreshRuntime.register(OuterV1, 'Outer');
ReactDOM.render(<OuterV1 />, container);
const el = container.firstChild;
const pathEl = el.querySelector('path');
expect(el.style.color).toBe('blue');
expect(pathEl.getAttributeNS(null, 'fill')).toBe('rgb(0, 0, 255)');
// Perform a hot update to the ART-rendered component.
const InnerV2 = function () {
return <ReactART.Shape fill="red" />;
};
ReactFreshRuntime.register(InnerV2, 'Inner');
ReactFreshRuntime.performReactRefresh();
expect(container.firstChild).toBe(el);
expect(el.querySelector('path')).toBe(pathEl);
expect(el.style.color).toBe('blue');
expect(pathEl.getAttributeNS(null, 'fill')).toBe('rgb(255, 0, 0)');
// Perform a hot update to the DOM-rendered component.
const OuterV2 = function () {
return (
<div style={{color: 'red'}}>
<ReactART.Surface>
<InnerV1 />
</ReactART.Surface>
</div>
);
};
ReactFreshRuntime.register(OuterV2, 'Outer');
ReactFreshRuntime.performReactRefresh();
expect(el.style.color).toBe('red');
expect(container.firstChild).toBe(el);
expect(el.querySelector('path')).toBe(pathEl);
expect(pathEl.getAttributeNS(null, 'fill')).toBe('rgb(255, 0, 0)');
}
});
});
| 27.32 | 82 | 0.607206 |
owtf | 'use client';
import * as React from 'react';
export function Dynamic() {
return (
<div>
This client component should be loaded in a single chunk even when it is
used as both a client reference and as a dynamic import.
</div>
);
}
| 18.846154 | 78 | 0.653696 |
Python-Penetration-Testing-Cookbook | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {
unstable_getCacheForType as getCacheForType,
startTransition,
} from 'react';
import Store from 'react-devtools-shared/src/devtools/store';
import {inspectElement as inspectElementMutableSource} from 'react-devtools-shared/src/inspectedElementMutableSource';
import ElementPollingCancellationError from 'react-devtools-shared/src//errors/ElementPollingCancellationError';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type {Wakeable} from 'shared/ReactTypes';
import type {
Element,
InspectedElement as InspectedElementFrontend,
InspectedElementResponseType,
InspectedElementPath,
} from 'react-devtools-shared/src/frontend/types';
const Pending = 0;
const Resolved = 1;
const Rejected = 2;
type PendingRecord = {
status: 0,
value: Wakeable,
};
type ResolvedRecord<T> = {
status: 1,
value: T,
};
type RejectedRecord = {
status: 2,
value: Error | string,
};
type Record<T> = PendingRecord | ResolvedRecord<T> | RejectedRecord;
function readRecord<T>(record: Record<T>): ResolvedRecord<T> {
if (record.status === Resolved) {
// This is just a type refinement.
return record;
} else {
throw record.value;
}
}
type InspectedElementMap = WeakMap<Element, Record<InspectedElementFrontend>>;
type CacheSeedKey = () => InspectedElementMap;
function createMap(): InspectedElementMap {
return new WeakMap();
}
function getRecordMap(): WeakMap<Element, Record<InspectedElementFrontend>> {
return getCacheForType(createMap);
}
function createCacheSeed(
element: Element,
inspectedElement: InspectedElementFrontend,
): [CacheSeedKey, InspectedElementMap] {
const newRecord: Record<InspectedElementFrontend> = {
status: Resolved,
value: inspectedElement,
};
const map = createMap();
map.set(element, newRecord);
return [createMap, map];
}
/**
* Fetches element props and state from the backend for inspection.
* This method should be called during render; it will suspend if data has not yet been fetched.
*/
export function inspectElement(
element: Element,
path: InspectedElementPath | null,
store: Store,
bridge: FrontendBridge,
): InspectedElementFrontend | null {
const map = getRecordMap();
let record = map.get(element);
if (!record) {
const callbacks = new Set<() => mixed>();
const wakeable: Wakeable = {
then(callback: () => mixed) {
callbacks.add(callback);
},
// Optional property used by Timeline:
displayName: `Inspecting ${element.displayName || 'Unknown'}`,
};
const wake = () => {
// This assumes they won't throw.
callbacks.forEach(callback => callback());
callbacks.clear();
};
const newRecord: Record<InspectedElementFrontend> = (record = {
status: Pending,
value: wakeable,
});
const rendererID = store.getRendererIDForElement(element.id);
if (rendererID == null) {
const rejectedRecord = ((newRecord: any): RejectedRecord);
rejectedRecord.status = Rejected;
rejectedRecord.value = new Error(
`Could not inspect element with id "${element.id}". No renderer found.`,
);
map.set(element, record);
return null;
}
inspectElementMutableSource(bridge, element, path, rendererID).then(
([inspectedElement]: [
InspectedElementFrontend,
InspectedElementResponseType,
]) => {
const resolvedRecord =
((newRecord: any): ResolvedRecord<InspectedElementFrontend>);
resolvedRecord.status = Resolved;
resolvedRecord.value = inspectedElement;
wake();
},
error => {
console.error(error);
const rejectedRecord = ((newRecord: any): RejectedRecord);
rejectedRecord.status = Rejected;
rejectedRecord.value = error;
wake();
},
);
map.set(element, record);
}
const response = readRecord(record).value;
return response;
}
type RefreshFunction = (
seedKey: CacheSeedKey,
cacheMap: InspectedElementMap,
) => void;
/**
* Asks the backend for updated props and state from an expected element.
* This method should never be called during render; call it from an effect or event handler.
* This method will schedule an update if updated information is returned.
*/
export function checkForUpdate({
bridge,
element,
refresh,
store,
}: {
bridge: FrontendBridge,
element: Element,
refresh: RefreshFunction,
store: Store,
}): void | Promise<void> {
const {id} = element;
const rendererID = store.getRendererIDForElement(id);
if (rendererID == null) {
return;
}
return inspectElementMutableSource(
bridge,
element,
null,
rendererID,
true,
).then(
([inspectedElement, responseType]: [
InspectedElementFrontend,
InspectedElementResponseType,
]) => {
if (responseType === 'full-data') {
startTransition(() => {
const [key, value] = createCacheSeed(element, inspectedElement);
refresh(key, value);
});
}
},
);
}
function createPromiseWhichResolvesInOneSecond() {
return new Promise(resolve => setTimeout(resolve, 1000));
}
type PollingStatus = 'idle' | 'running' | 'paused' | 'aborted';
export function startElementUpdatesPolling({
bridge,
element,
refresh,
store,
}: {
bridge: FrontendBridge,
element: Element,
refresh: RefreshFunction,
store: Store,
}): {abort: () => void, pause: () => void, resume: () => void} {
let status: PollingStatus = 'idle';
function abort() {
status = 'aborted';
}
function resume() {
if (status === 'running' || status === 'aborted') {
return;
}
status = 'idle';
poll();
}
function pause() {
if (status === 'paused' || status === 'aborted') {
return;
}
status = 'paused';
}
function poll(): Promise<void> {
status = 'running';
return Promise.allSettled([
checkForUpdate({bridge, element, refresh, store}),
createPromiseWhichResolvesInOneSecond(),
])
.then(([{status: updateStatus, reason}]) => {
// There isn't much to do about errors in this case,
// but we should at least log them, so they aren't silent.
// Log only if polling is still active, we can't handle the case when
// request was sent, and then bridge was remounted (for example, when user did navigate to a new page),
// but at least we can mark that polling was aborted
if (updateStatus === 'rejected' && status !== 'aborted') {
// This is expected Promise rejection, no need to log it
if (reason instanceof ElementPollingCancellationError) {
return;
}
console.error(reason);
}
})
.finally(() => {
const shouldContinuePolling =
status !== 'aborted' && status !== 'paused';
status = 'idle';
if (shouldContinuePolling) {
return poll();
}
});
}
poll();
return {abort, resume, pause};
}
export function clearCacheBecauseOfError(refresh: RefreshFunction): void {
startTransition(() => {
const map = createMap();
refresh(createMap, map);
});
}
| 24.356164 | 118 | 0.653924 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export type Destination = ReadableStreamController;
export type PrecomputedChunk = Uint8Array;
export opaque type Chunk = Uint8Array;
export type BinaryChunk = Uint8Array;
export function scheduleWork(callback: () => void) {
setTimeout(callback, 0);
}
export function flushBuffered(destination: Destination) {
// WHATWG Streams do not yet have a way to flush the underlying
// transform streams. https://github.com/whatwg/streams/issues/960
}
const VIEW_SIZE = 512;
let currentView = null;
let writtenBytes = 0;
export function beginWriting(destination: Destination) {
currentView = new Uint8Array(VIEW_SIZE);
writtenBytes = 0;
}
export function writeChunk(
destination: Destination,
chunk: PrecomputedChunk | Chunk | BinaryChunk,
): void {
if (chunk.byteLength === 0) {
return;
}
if (chunk.byteLength > VIEW_SIZE) {
if (__DEV__) {
if (precomputedChunkSet.has(chunk)) {
console.error(
'A large precomputed chunk was passed to writeChunk without being copied.' +
' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' +
' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.',
);
}
}
// this chunk may overflow a single view which implies it was not
// one that is cached by the streaming renderer. We will enqueu
// it directly and expect it is not re-used
if (writtenBytes > 0) {
destination.enqueue(
new Uint8Array(
((currentView: any): Uint8Array).buffer,
0,
writtenBytes,
),
);
currentView = new Uint8Array(VIEW_SIZE);
writtenBytes = 0;
}
destination.enqueue(chunk);
return;
}
let bytesToWrite = chunk;
const allowableBytes = ((currentView: any): Uint8Array).length - writtenBytes;
if (allowableBytes < bytesToWrite.byteLength) {
// this chunk would overflow the current view. We enqueue a full view
// and start a new view with the remaining chunk
if (allowableBytes === 0) {
// the current view is already full, send it
destination.enqueue(currentView);
} else {
// fill up the current view and apply the remaining chunk bytes
// to a new view.
((currentView: any): Uint8Array).set(
bytesToWrite.subarray(0, allowableBytes),
writtenBytes,
);
// writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view
destination.enqueue(currentView);
bytesToWrite = bytesToWrite.subarray(allowableBytes);
}
currentView = new Uint8Array(VIEW_SIZE);
writtenBytes = 0;
}
((currentView: any): Uint8Array).set(bytesToWrite, writtenBytes);
writtenBytes += bytesToWrite.byteLength;
}
export function writeChunkAndReturn(
destination: Destination,
chunk: PrecomputedChunk | Chunk | BinaryChunk,
): boolean {
writeChunk(destination, chunk);
// in web streams there is no backpressure so we can alwas write more
return true;
}
export function completeWriting(destination: Destination) {
if (currentView && writtenBytes > 0) {
destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));
currentView = null;
writtenBytes = 0;
}
}
export function close(destination: Destination) {
destination.close();
}
const textEncoder = new TextEncoder();
export function stringToChunk(content: string): Chunk {
return textEncoder.encode(content);
}
const precomputedChunkSet: Set<Chunk | BinaryChunk> = __DEV__
? new Set()
: (null: any);
export function stringToPrecomputedChunk(content: string): PrecomputedChunk {
const precomputedChunk = textEncoder.encode(content);
if (__DEV__) {
precomputedChunkSet.add(precomputedChunk);
}
return precomputedChunk;
}
export function typedArrayToBinaryChunk(
content: $ArrayBufferView,
): BinaryChunk {
// Convert any non-Uint8Array array to Uint8Array. We could avoid this for Uint8Arrays.
// If we passed through this straight to enqueue we wouldn't have to convert it but since
// we need to copy the buffer in that case, we need to convert it to copy it.
// When we copy it into another array using set() it needs to be a Uint8Array.
const buffer = new Uint8Array(
content.buffer,
content.byteOffset,
content.byteLength,
);
// We clone large chunks so that we can transfer them when we write them.
// Others get copied into the target buffer.
return content.byteLength > VIEW_SIZE ? buffer.slice() : buffer;
}
export function clonePrecomputedChunk(
precomputedChunk: PrecomputedChunk,
): PrecomputedChunk {
return precomputedChunk.byteLength > VIEW_SIZE
? precomputedChunk.slice()
: precomputedChunk;
}
export function byteLengthOfChunk(chunk: Chunk | PrecomputedChunk): number {
return chunk.byteLength;
}
export function byteLengthOfBinaryChunk(chunk: BinaryChunk): number {
return chunk.byteLength;
}
export function closeWithError(destination: Destination, error: mixed): void {
// $FlowFixMe[method-unbinding]
if (typeof destination.error === 'function') {
// $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types.
destination.error(error);
} else {
// Earlier implementations doesn't support this method. In that environment you're
// supposed to throw from a promise returned but we don't return a promise in our
// approach. We could fork this implementation but this is environment is an edge
// case to begin with. It's even less common to run this in an older environment.
// Even then, this is not where errors are supposed to happen and they get reported
// to a global callback in addition to this anyway. So it's fine just to close this.
destination.close();
}
}
export {createFastHashJS as createFastHash} from 'react-server/src/createFastHashJS';
| 32.203209 | 177 | 0.710213 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export * from 'react-native-renderer/src/ReactFiberConfigFabric';
| 23.636364 | 66 | 0.718519 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type Store from 'react-devtools-shared/src/devtools/store';
describe('InspectedElementContext', () => {
let React;
let ReactDOM;
let bridge: FrontendBridge;
let store: Store;
let backendAPI;
const act = (callback: Function) => {
callback();
jest.runAllTimers(); // Flush Bridge operations
};
async function read(
id: number,
path: Array<string | number> = null,
): Promise<Object> {
const rendererID = ((store.getRendererIDForElement(id): any): number);
const promise = backendAPI
.inspectElement(bridge, false, id, path, rendererID)
.then(data =>
backendAPI.convertInspectedElementBackendToFrontend(data.value),
);
jest.runOnlyPendingTimers();
return promise;
}
beforeEach(() => {
bridge = global.bridge;
store = global.store;
backendAPI = require('react-devtools-shared/src/backendAPI');
// Redirect all React/ReactDOM requires to the v15 UMD.
// We use the UMD because Jest doesn't enable us to mock deep imports (e.g. "react/lib/Something").
jest.mock('react', () => jest.requireActual('react-15/dist/react.js'));
jest.mock('react-dom', () =>
jest.requireActual('react-dom-15/dist/react-dom.js'),
);
React = require('react');
ReactDOM = require('react-dom');
});
// @reactVersion >= 16.0
it('should inspect the currently selected element', async () => {
const Example = () => null;
act(() =>
ReactDOM.render(<Example a={1} b="abc" />, document.createElement('div')),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchInlineSnapshot(`
{
"context": {},
"events": undefined,
"hooks": null,
"id": 2,
"owners": null,
"props": {
"a": 1,
"b": "abc",
},
"rootType": null,
"state": null,
}
`);
});
// @reactVersion >= 16.0
it('should support simple data types', async () => {
const Example = () => null;
act(() =>
ReactDOM.render(
<Example
boolean_false={false}
boolean_true={true}
infinity={Infinity}
integer_zero={0}
integer_one={1}
float={1.23}
string="abc"
string_empty=""
nan={NaN}
value_null={null}
value_undefined={undefined}
/>,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchInlineSnapshot(`
{
"context": {},
"events": undefined,
"hooks": null,
"id": 2,
"owners": null,
"props": {
"boolean_false": false,
"boolean_true": true,
"float": 1.23,
"infinity": Infinity,
"integer_one": 1,
"integer_zero": 0,
"nan": NaN,
"string": "abc",
"string_empty": "",
"value_null": null,
"value_undefined": undefined,
},
"rootType": null,
"state": null,
}
`);
});
// @reactVersion >= 16.0
it('should support complex data types', async () => {
const Immutable = require('immutable');
const Example = () => null;
const arrayOfArrays = [[['abc', 123, true], []]];
const div = document.createElement('div');
const exampleFunction = () => {};
const setShallow = new Set(['abc', 123]);
const mapShallow = new Map([
['name', 'Brian'],
['food', 'sushi'],
]);
const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]);
const mapOfMaps = new Map([
['first', mapShallow],
['second', mapShallow],
]);
const objectOfObjects = {
inner: {string: 'abc', number: 123, boolean: true},
};
const typedArray = Int8Array.from([100, -100, 0]);
const arrayBuffer = typedArray.buffer;
const dataView = new DataView(arrayBuffer);
const immutableMap = Immutable.fromJS({
a: [{hello: 'there'}, 'fixed', true],
b: 123,
c: {
'1': 'xyz',
xyz: 1,
},
});
class Class {
anonymousFunction = () => {};
}
const instance = new Class();
act(() =>
ReactDOM.render(
<Example
anonymous_fn={instance.anonymousFunction}
array_buffer={arrayBuffer}
array_of_arrays={arrayOfArrays}
// eslint-disable-next-line no-undef
big_int={BigInt(123)}
bound_fn={exampleFunction.bind(this)}
data_view={dataView}
date={new Date(123)}
fn={exampleFunction}
html_element={div}
immutable={immutableMap}
map={mapShallow}
map_of_maps={mapOfMaps}
object_of_objects={objectOfObjects}
react_element={<span />}
regexp={/abc/giu}
set={setShallow}
set_of_sets={setOfSets}
symbol={Symbol('symbol')}
typed_array={typedArray}
/>,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement.props).toMatchInlineSnapshot(`
{
"anonymous_fn": Dehydrated {
"preview_short": ƒ () {},
"preview_long": ƒ () {},
},
"array_buffer": Dehydrated {
"preview_short": ArrayBuffer(3),
"preview_long": ArrayBuffer(3),
},
"array_of_arrays": [
Dehydrated {
"preview_short": Array(2),
"preview_long": [Array(3), Array(0)],
},
],
"big_int": Dehydrated {
"preview_short": 123n,
"preview_long": 123n,
},
"bound_fn": Dehydrated {
"preview_short": ƒ bound exampleFunction() {},
"preview_long": ƒ bound exampleFunction() {},
},
"data_view": Dehydrated {
"preview_short": DataView(3),
"preview_long": DataView(3),
},
"date": Dehydrated {
"preview_short": Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time),
"preview_long": Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time),
},
"fn": Dehydrated {
"preview_short": ƒ exampleFunction() {},
"preview_long": ƒ exampleFunction() {},
},
"html_element": Dehydrated {
"preview_short": <div />,
"preview_long": <div />,
},
"immutable": {
"0": Dehydrated {
"preview_short": Array(2),
"preview_long": ["a", List(3)],
},
"1": Dehydrated {
"preview_short": Array(2),
"preview_long": ["b", 123],
},
"2": Dehydrated {
"preview_short": Array(2),
"preview_long": ["c", Map(2)],
},
},
"map": {
"0": Dehydrated {
"preview_short": Array(2),
"preview_long": ["name", "Brian"],
},
"1": Dehydrated {
"preview_short": Array(2),
"preview_long": ["food", "sushi"],
},
},
"map_of_maps": {
"0": Dehydrated {
"preview_short": Array(2),
"preview_long": ["first", Map(2)],
},
"1": Dehydrated {
"preview_short": Array(2),
"preview_long": ["second", Map(2)],
},
},
"object_of_objects": {
"inner": Dehydrated {
"preview_short": {…},
"preview_long": {boolean: true, number: 123, string: "abc"},
},
},
"react_element": Dehydrated {
"preview_short": <span />,
"preview_long": <span />,
},
"regexp": Dehydrated {
"preview_short": /abc/giu,
"preview_long": /abc/giu,
},
"set": {
"0": "abc",
"1": 123,
},
"set_of_sets": {
"0": Dehydrated {
"preview_short": Set(3),
"preview_long": Set(3) {"a", "b", "c"},
},
"1": Dehydrated {
"preview_short": Set(3),
"preview_long": Set(3) {1, 2, 3},
},
},
"symbol": Dehydrated {
"preview_short": Symbol(symbol),
"preview_long": Symbol(symbol),
},
"typed_array": {
"0": 100,
"1": -100,
"2": 0,
},
}
`);
});
// @reactVersion >= 16.0
it('should support objects with no prototype', async () => {
const Example = () => null;
const object = Object.create(null);
object.string = 'abc';
object.number = 123;
object.boolean = true;
act(() =>
ReactDOM.render(
<Example object={object} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement.props).toMatchInlineSnapshot(`
{
"object": {
"boolean": true,
"number": 123,
"string": "abc",
},
}
`);
});
// @reactVersion >= 16.0
it('should support objects with overridden hasOwnProperty', async () => {
const Example = () => null;
const object = {
name: 'blah',
hasOwnProperty: true,
};
act(() =>
ReactDOM.render(
<Example object={object} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
// TRICKY: Don't use toMatchInlineSnapshot() for this test!
// Our snapshot serializer relies on hasOwnProperty() for feature detection.
expect(inspectedElement.props.object.name).toBe('blah');
expect(inspectedElement.props.object.hasOwnProperty).toBe(true);
});
// @reactVersion >= 16.0
it('should not consume iterables while inspecting', async () => {
const Example = () => null;
function* generator() {
yield 1;
yield 2;
}
const iteratable = generator();
act(() =>
ReactDOM.render(
<Example iteratable={iteratable} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchInlineSnapshot(`
{
"context": {},
"events": undefined,
"hooks": null,
"id": 2,
"owners": null,
"props": {
"iteratable": Dehydrated {
"preview_short": Generator,
"preview_long": Generator,
},
},
"rootType": null,
"state": null,
}
`);
// Inspecting should not consume the iterable.
expect(iteratable.next().value).toEqual(1);
expect(iteratable.next().value).toEqual(2);
expect(iteratable.next().value).toBeUndefined();
});
// @reactVersion >= 16.0
it('should support custom objects with enumerable properties and getters', async () => {
class CustomData {
_number = 42;
get number() {
return this._number;
}
set number(value) {
this._number = value;
}
}
const descriptor = ((Object.getOwnPropertyDescriptor(
CustomData.prototype,
'number',
): any): PropertyDescriptor<number>);
descriptor.enumerable = true;
Object.defineProperty(CustomData.prototype, 'number', descriptor);
const Example = ({data}) => null;
act(() =>
ReactDOM.render(
<Example data={new CustomData()} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchInlineSnapshot(`
{
"context": {},
"events": undefined,
"hooks": null,
"id": 2,
"owners": null,
"props": {
"data": {
"_number": 42,
"number": 42,
},
},
"rootType": null,
"state": null,
}
`);
});
// @reactVersion >= 16.0
it('should support objects with inherited keys', async () => {
const Example = () => null;
const base = Object.create(Object.prototype, {
enumerableStringBase: {
value: 1,
writable: true,
enumerable: true,
configurable: true,
},
[Symbol('enumerableSymbolBase')]: {
value: 1,
writable: true,
enumerable: true,
configurable: true,
},
nonEnumerableStringBase: {
value: 1,
writable: true,
enumerable: false,
configurable: true,
},
[Symbol('nonEnumerableSymbolBase')]: {
value: 1,
writable: true,
enumerable: false,
configurable: true,
},
});
const object = Object.create(base, {
enumerableString: {
value: 2,
writable: true,
enumerable: true,
configurable: true,
},
nonEnumerableString: {
value: 3,
writable: true,
enumerable: false,
configurable: true,
},
123: {
value: 3,
writable: true,
enumerable: true,
configurable: true,
},
[Symbol('nonEnumerableSymbol')]: {
value: 2,
writable: true,
enumerable: false,
configurable: true,
},
[Symbol('enumerableSymbol')]: {
value: 3,
writable: true,
enumerable: true,
configurable: true,
},
});
act(() =>
ReactDOM.render(<Example data={object} />, document.createElement('div')),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchInlineSnapshot(`
{
"context": {},
"events": undefined,
"hooks": null,
"id": 2,
"owners": null,
"props": {
"data": {
"123": 3,
"Symbol(enumerableSymbol)": 3,
"Symbol(enumerableSymbolBase)": 1,
"enumerableString": 2,
"enumerableStringBase": 1,
},
},
"rootType": null,
"state": null,
}
`);
});
// @reactVersion >= 16.0
it('should allow component prop value and value`s prototype has same name params.', async () => {
const testData = Object.create(
{
a: undefined,
b: Infinity,
c: NaN,
d: 'normal',
},
{
a: {
value: undefined,
writable: true,
enumerable: true,
configurable: true,
},
b: {
value: Infinity,
writable: true,
enumerable: true,
configurable: true,
},
c: {
value: NaN,
writable: true,
enumerable: true,
configurable: true,
},
d: {
value: 'normal',
writable: true,
enumerable: true,
configurable: true,
},
},
);
const Example = ({data}) => null;
act(() =>
ReactDOM.render(
<Example data={testData} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement.props).toMatchInlineSnapshot(`
{
"data": {
"a": undefined,
"b": Infinity,
"c": NaN,
"d": "normal",
},
}
`);
});
// @reactVersion >= 16.0
it('should not dehydrate nested values until explicitly requested', async () => {
const Example = () => null;
act(() =>
ReactDOM.render(
<Example
nestedObject={{
a: {
b: {
c: [
{
d: {
e: {},
},
},
],
},
},
}}
/>,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
let inspectedElement = await read(id);
expect(inspectedElement.props).toMatchInlineSnapshot(`
{
"nestedObject": {
"a": Dehydrated {
"preview_short": {…},
"preview_long": {b: {…}},
},
},
}
`);
inspectedElement = await read(id, ['props', 'nestedObject', 'a']);
expect(inspectedElement.props).toMatchInlineSnapshot(`
{
"nestedObject": {
"a": {
"b": {
"c": Dehydrated {
"preview_short": Array(1),
"preview_long": [{…}],
},
},
},
},
}
`);
inspectedElement = await read(id, ['props', 'nestedObject', 'a', 'b', 'c']);
expect(inspectedElement.props).toMatchInlineSnapshot(`
{
"nestedObject": {
"a": {
"b": {
"c": [
{
"d": Dehydrated {
"preview_short": {…},
"preview_long": {e: {…}},
},
},
],
},
},
},
}
`);
inspectedElement = await read(id, [
'props',
'nestedObject',
'a',
'b',
'c',
0,
'd',
]);
expect(inspectedElement.props).toMatchInlineSnapshot(`
{
"nestedObject": {
"a": {
"b": {
"c": [
{
"d": {
"e": {},
},
},
],
},
},
},
}
`);
});
// @reactVersion >= 16.0
it('should enable inspected values to be stored as global variables', () => {
const Example = () => null;
const nestedObject = {
a: {
value: 1,
b: {
value: 1,
c: {
value: 1,
},
},
},
};
act(() =>
ReactDOM.render(
<Example nestedObject={nestedObject} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const rendererID = ((store.getRendererIDForElement(id): any): number);
const logSpy = jest.fn();
jest.spyOn(console, 'log').mockImplementation(logSpy);
// Should store the whole value (not just the hydrated parts)
backendAPI.storeAsGlobal({
bridge,
id,
path: ['props', 'nestedObject'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(logSpy).toHaveBeenCalledWith('$reactTemp0');
expect(global.$reactTemp0).toBe(nestedObject);
logSpy.mockReset();
// Should store the nested property specified (not just the outer value)
backendAPI.storeAsGlobal({
bridge,
id,
path: ['props', 'nestedObject', 'a', 'b'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(logSpy).toHaveBeenCalledWith('$reactTemp1');
expect(global.$reactTemp1).toBe(nestedObject.a.b);
});
// @reactVersion >= 16.0
it('should enable inspected values to be copied to the clipboard', () => {
const Example = () => null;
const nestedObject = {
a: {
value: 1,
b: {
value: 1,
c: {
value: 1,
},
},
},
};
act(() =>
ReactDOM.render(
<Example nestedObject={nestedObject} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const rendererID = ((store.getRendererIDForElement(id): any): number);
// Should copy the whole value (not just the hydrated parts)
backendAPI.copyInspectedElementPath({
bridge,
id,
path: ['props', 'nestedObject'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
expect(global.mockClipboardCopy).toHaveBeenCalledWith(
JSON.stringify(nestedObject, undefined, 2),
);
global.mockClipboardCopy.mockReset();
// Should copy the nested property specified (not just the outer value)
backendAPI.copyInspectedElementPath({
bridge,
id,
path: ['props', 'nestedObject', 'a', 'b'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
expect(global.mockClipboardCopy).toHaveBeenCalledWith(
JSON.stringify(nestedObject.a.b, undefined, 2),
);
});
// @reactVersion >= 16.0
it('should enable complex values to be copied to the clipboard', () => {
const Immutable = require('immutable');
const Example = () => null;
const set = new Set(['abc', 123]);
const map = new Map([
['name', 'Brian'],
['food', 'sushi'],
]);
const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]);
const mapOfMaps = new Map([
['first', map],
['second', map],
]);
const typedArray = Int8Array.from([100, -100, 0]);
const arrayBuffer = typedArray.buffer;
const dataView = new DataView(arrayBuffer);
const immutable = Immutable.fromJS({
a: [{hello: 'there'}, 'fixed', true],
b: 123,
c: {
'1': 'xyz',
xyz: 1,
},
});
const bigInt = BigInt(123); // eslint-disable-line no-undef
act(() =>
ReactDOM.render(
<Example
arrayBuffer={arrayBuffer}
dataView={dataView}
map={map}
set={set}
mapOfMaps={mapOfMaps}
setOfSets={setOfSets}
typedArray={typedArray}
immutable={immutable}
bigInt={bigInt}
/>,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const rendererID = ((store.getRendererIDForElement(id): any): number);
// Should copy the whole value (not just the hydrated parts)
backendAPI.copyInspectedElementPath({
bridge,
id,
path: ['props'],
rendererID,
});
jest.runOnlyPendingTimers();
// Should not error despite lots of unserialized values.
global.mockClipboardCopy.mockReset();
// Should copy the nested property specified (not just the outer value)
backendAPI.copyInspectedElementPath({
bridge,
id,
path: ['props', 'bigInt'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
expect(global.mockClipboardCopy).toHaveBeenCalledWith(
JSON.stringify('123n'),
);
global.mockClipboardCopy.mockReset();
// Should copy the nested property specified (not just the outer value)
backendAPI.copyInspectedElementPath({
bridge,
id,
path: ['props', 'typedArray'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
expect(global.mockClipboardCopy).toHaveBeenCalledWith(
JSON.stringify({0: 100, 1: -100, 2: 0}, undefined, 2),
);
});
});
| 24.446467 | 103 | 0.511192 |
Python-Penetration-Testing-Cookbook | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {createContext, useContext, useDebugValue} from 'react';
export const ThemeContext = createContext('bright');
export default function useTheme() {
const theme = useContext(ThemeContext);
useDebugValue(theme);
return theme;
}
| 22.421053 | 66 | 0.727477 |
owtf | /** @license React v0.14.10
* react-jsx-dev-runtime.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
if (process.env.NODE_ENV !== "production") {
(function() {
'use strict';
var React = require('react');
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = 0xeac7;
var REACT_PORTAL_TYPE = 0xeaca;
exports.Fragment = 0xeacb;
var REACT_STRICT_MODE_TYPE = 0xeacc;
var REACT_PROFILER_TYPE = 0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
var REACT_SUSPENSE_TYPE = 0xead1;
var REACT_SUSPENSE_LIST_TYPE = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_BLOCK_TYPE = 0xead9;
var REACT_SERVER_BLOCK_TYPE = 0xeada;
var REACT_FUNDAMENTAL_TYPE = 0xead5;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symbolFor('react.fragment');
REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
REACT_PROFILER_TYPE = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
REACT_MEMO_TYPE = symbolFor('react.memo');
REACT_LAZY_TYPE = symbolFor('react.lazy');
REACT_BLOCK_TYPE = symbolFor('react.block');
REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
REACT_SCOPE_TYPE = symbolFor('react.scope');
REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
function error(format) {
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var stack = '';
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
}
var argsWithFormat = args.map(function (item) {
return '' + item;
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableScopeAPI = false; // Experimental Create Event Handle API.
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === exports.Fragment || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI ) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) {
return true;
}
}
return false;
}
var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
function describeComponentFrame (name, source, ownerName) {
var sourceInfo = '';
if (source) {
var path = source.fileName;
var fileName = path.replace(BEFORE_SLASH_RE, '');
{
// In DEV, include code for a common special case:
// prefer "folder/index.js" instead of just "index.js".
if (/^index\./.test(fileName)) {
var match = path.match(BEFORE_SLASH_RE);
if (match) {
var pathBeforeSlash = match[1];
if (pathBeforeSlash) {
var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
fileName = folderName + '/' + fileName;
}
}
}
}
sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
} else if (ownerName) {
sourceInfo = ' (created by ' + ownerName + ')';
}
return '\n in ' + (name || 'Unknown') + sourceInfo;
}
var Resolved = 1;
function refineResolvedLazyComponent(lazyComponent) {
return lazyComponent._status === Resolved ? lazyComponent._result : null;
}
function getWrappedName(outerType, innerType, wrapperName) {
var functionName = innerType.displayName || innerType.name || '';
return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
}
function getComponentName(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case exports.Fragment:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case REACT_PROFILER_TYPE:
return "Profiler";
case REACT_STRICT_MODE_TYPE:
return 'StrictMode';
case REACT_SUSPENSE_TYPE:
return 'Suspense';
case REACT_SUSPENSE_LIST_TYPE:
return 'SuspenseList';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
return 'Context.Consumer';
case REACT_PROVIDER_TYPE:
return 'Context.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
return getComponentName(type.type);
case REACT_BLOCK_TYPE:
return getComponentName(type.render);
case REACT_LAZY_TYPE:
{
var thenable = type;
var resolvedThenable = refineResolvedLazyComponent(thenable);
if (resolvedThenable) {
return getComponentName(resolvedThenable);
}
break;
}
}
}
return null;
}
var loggedTypeFailures = {};
var currentlyValidatingElement = null;
function setCurrentlyValidatingElement(element) {
currentlyValidatingElement = element;
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(Object.prototype.hasOwnProperty);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
var ReactCurrentOwner = require('react/lib/ReactCurrentOwner');
var hasOwnProperty = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown;
var specialPropRefWarningShown;
var didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
{
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
{
var warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
}
function defineRefPropWarningGetter(props, displayName) {
{
var warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
{
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* https://github.com/reactjs/rfcs/pull/107
* @param {*} type
* @param {object} props
* @param {string} key
*/
function jsxDEV(type, config, maybeKey, source, self) {
{
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null; // Currently, key can be spread in as a prop. This causes a potential
// issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
// or <div key="Hi" {...props} /> ). We want to deprecate key spread,
// but as an intermediary step, we will use jsxDEV for everything except
// <div {...props} key="Hi" />, because we aren't currently able to tell if
// key is explicitly declared to be undefined or not.
if (maybeKey !== undefined) {
key = '' + maybeKey;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
if (hasValidRef(config)) {
ref = config.ref;
} // Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
}
var ReactCurrentOwner$1 = require('react/lib/ReactCurrentOwner');
function setCurrentlyValidatingElement$1(element) {
currentlyValidatingElement = element;
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
{
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
}
function getDeclarationErrorAddendum() {
{
if (ReactCurrentOwner$1.current) {
var name = ReactCurrentOwner$1.current.getName();
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
}
function getSourceInfoErrorAddendum(source) {
{
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
{
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
{
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
// Give the component that originally created this child.
childOwner = " It was passed a child from " + element._owner.getName() + ".";
}
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
{
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentName(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentName(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
{
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendum(source);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (Array.isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
var children = props.children;
if (children !== undefined) {
if (isStaticChildren) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
validateChildKeys(children[i], type);
}
if (Object.freeze) {
Object.freeze(children);
}
} else {
error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
}
} else {
validateChildKeys(children, type);
}
}
}
if (type === exports.Fragment) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
} // These two functions exist to still get child warnings in dev
var jsxDEV$1 = jsxWithValidation ;
exports.jsxDEV = jsxDEV$1;
})();
}
| 30.460557 | 397 | 0.64636 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
module.exports = {
meta: {
schema: [],
},
create(context) {
function report(node, name, msg) {
context.report(node, `Do not use the ${name} constructor. ${msg}`);
}
function check(node) {
const name = node.callee.name;
switch (name) {
case 'Boolean':
report(
node,
name,
'To cast a value to a boolean, use double negation: !!value'
);
break;
case 'String':
if (node.type === 'NewExpression') {
context.report(
node,
"Do not use `new String()`. Use String() without new (or '' + value for perf-sensitive code)."
);
}
break;
case 'Number':
report(
node,
name,
'To cast a value to a number, use the plus operator: +value'
);
break;
}
}
return {
CallExpression: check,
NewExpression: check,
};
},
};
| 21.563636 | 108 | 0.504032 |
null | 'use strict';
const ClosureCompiler = require('google-closure-compiler').compiler;
const {promisify} = require('util');
const fs = require('fs');
const tmp = require('tmp');
const writeFileAsync = promisify(fs.writeFile);
function compile(flags) {
return new Promise((resolve, reject) => {
const closureCompiler = new ClosureCompiler(flags);
closureCompiler.run(function (exitCode, stdOut, stdErr) {
if (!stdErr) {
resolve(stdOut);
} else {
reject(new Error(stdErr));
}
});
});
}
module.exports = function closure(flags = {}, {needsSourcemaps}) {
return {
name: 'scripts/rollup/plugins/closure-plugin',
async renderChunk(code, chunk, options) {
const inputFile = tmp.fileSync();
// Use a path like `node_modules/react/cjs/react.production.min.js.map` for the sourcemap file
const sourcemapPath = options.file.replace('.js', '.js.map');
// Tell Closure what JS source file to read, and optionally what sourcemap file to write
const finalFlags = {
...flags,
js: inputFile.name,
...(needsSourcemaps && {create_source_map: sourcemapPath}),
};
await writeFileAsync(inputFile.name, code, 'utf8');
const compiledCode = await compile(finalFlags);
inputFile.removeCallback();
return {code: compiledCode};
},
};
};
| 28.630435 | 100 | 0.647577 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = require("react");
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const A = /*#__PURE__*/(0, _react.createContext)(1);
const B = /*#__PURE__*/(0, _react.createContext)(2);
function Component() {
const a = (0, _react.useContext)(A);
const b = (0, _react.useContext)(B); // prettier-ignore
const c = (0, _react.useContext)(A),
d = (0, _react.useContext)(B); // eslint-disable-line one-var
return a + b + c + d;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZS5qcyJdLCJuYW1lcyI6WyJBIiwiQiIsIkNvbXBvbmVudCIsImEiLCJiIiwiYyIsImQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7QUFUQTs7Ozs7Ozs7QUFXQSxNQUFNQSxDQUFDLGdCQUFHLDBCQUFjLENBQWQsQ0FBVjtBQUNBLE1BQU1DLENBQUMsZ0JBQUcsMEJBQWMsQ0FBZCxDQUFWOztBQUVPLFNBQVNDLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsQ0FBQyxHQUFHLHVCQUFXSCxDQUFYLENBQVY7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdILENBQVgsQ0FBVixDQUYwQixDQUkxQjs7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBVjtBQUFBLFFBQXlCTSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBN0IsQ0FMMEIsQ0FLa0I7O0FBRTVDLFNBQU9FLENBQUMsR0FBR0MsQ0FBSixHQUFRQyxDQUFSLEdBQVlDLENBQW5CO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0fSBmcm9tICdyZWFjdCc7XG5cbmNvbnN0IEEgPSBjcmVhdGVDb250ZXh0KDEpO1xuY29uc3QgQiA9IGNyZWF0ZUNvbnRleHQoMik7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IGEgPSB1c2VDb250ZXh0KEEpO1xuICBjb25zdCBiID0gdXNlQ29udGV4dChCKTtcblxuICAvLyBwcmV0dGllci1pZ25vcmVcbiAgY29uc3QgYyA9IHVzZUNvbnRleHQoQSksIGQgPSB1c2VDb250ZXh0KEIpOyAvLyBlc2xpbnQtZGlzYWJsZS1saW5lIG9uZS12YXJcblxuICByZXR1cm4gYSArIGIgKyBjICsgZDtcbn1cbiJdLCJ4X3JlYWN0X3NvdXJjZXMiOltbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJhIiwiYiIsImMiLCJkIl0sIm1hcHBpbmdzIjoiQ0FBRDtnQllDQSxBYURBO2lCYkVBLEFhRkE7b0JiR0EsQWFIQSxBTUlBLEFhSkEifV1dfX1dfQ== | 79.766667 | 1,716 | 0.886457 |
Penetration-Testing-Study-Notes | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export {default} from './npm/Rectangle';
| 21.363636 | 66 | 0.689796 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type Store from 'react-devtools-shared/src/devtools/store';
describe('commit tree', () => {
let React;
let ReactDOMClient;
let Scheduler;
let legacyRender;
let store: Store;
let utils;
beforeEach(() => {
utils = require('./utils');
utils.beforeEachProfiling();
legacyRender = utils.legacyRender;
store = global.store;
store.collapseNodesByDefault = false;
store.recordChangeDescriptions = true;
React = require('react');
ReactDOMClient = require('react-dom/client');
Scheduler = require('scheduler');
});
// @reactVersion >= 16.9
it('should be able to rebuild the store tree for each commit', () => {
const Parent = ({count}) => {
Scheduler.unstable_advanceTime(10);
return new Array(count)
.fill(true)
.map((_, index) => <Child key={index} />);
};
const Child = React.memo(function Child() {
Scheduler.unstable_advanceTime(2);
return null;
});
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => legacyRender(<Parent count={1} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="0"> [Memo]
`);
utils.act(() => legacyRender(<Parent count={3} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="0"> [Memo]
<Child key="1"> [Memo]
<Child key="2"> [Memo]
`);
utils.act(() => legacyRender(<Parent count={2} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
▾ <Parent>
<Child key="0"> [Memo]
<Child key="1"> [Memo]
`);
utils.act(() => legacyRender(<Parent count={0} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
<Parent>
`);
utils.act(() => store.profilerStore.stopProfiling());
const rootID = store.roots[0];
const commitTrees = [];
for (let commitIndex = 0; commitIndex < 4; commitIndex++) {
commitTrees.push(
store.profilerStore.profilingCache.getCommitTree({
commitIndex,
rootID,
}),
);
}
expect(commitTrees[0].nodes.size).toBe(3); // <Root> + <Parent> + <Child>
expect(commitTrees[1].nodes.size).toBe(5); // <Root> + <Parent> + <Child> x 3
expect(commitTrees[2].nodes.size).toBe(4); // <Root> + <Parent> + <Child> x 2
expect(commitTrees[3].nodes.size).toBe(2); // <Root> + <Parent>
});
describe('Lazy', () => {
async function fakeImport(result) {
return {default: result};
}
const LazyInnerComponent = () => null;
const App = ({renderChildren}) => {
if (renderChildren) {
return (
<React.Suspense fallback="Loading...">
<LazyComponent />
</React.Suspense>
);
} else {
return null;
}
};
let LazyComponent;
beforeEach(() => {
LazyComponent = React.lazy(() => fakeImport(LazyInnerComponent));
});
// @reactVersion >= 16.9
it('should support Lazy components (legacy render)', async () => {
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => legacyRender(<App renderChildren={true} />, container));
await Promise.resolve();
expect(store).toMatchInlineSnapshot(`
[root]
▾ <App>
<Suspense>
`);
utils.act(() => legacyRender(<App renderChildren={true} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
▾ <App>
▾ <Suspense>
<LazyInnerComponent>
`);
utils.act(() => legacyRender(<App renderChildren={false} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
<App>
`);
utils.act(() => store.profilerStore.stopProfiling());
const rootID = store.roots[0];
const commitTrees = [];
for (let commitIndex = 0; commitIndex < 3; commitIndex++) {
commitTrees.push(
store.profilerStore.profilingCache.getCommitTree({
commitIndex,
rootID,
}),
);
}
expect(commitTrees[0].nodes.size).toBe(3); // <Root> + <App> + <Suspense>
expect(commitTrees[1].nodes.size).toBe(4); // <Root> + <App> + <Suspense> + <LazyInnerComponent>
expect(commitTrees[2].nodes.size).toBe(2); // <Root> + <App>
});
// @reactVersion >= 18.0
it('should support Lazy components (createRoot)', async () => {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => root.render(<App renderChildren={true} />));
await Promise.resolve();
expect(store).toMatchInlineSnapshot(`
[root]
▾ <App>
<Suspense>
`);
utils.act(() => root.render(<App renderChildren={true} />));
expect(store).toMatchInlineSnapshot(`
[root]
▾ <App>
▾ <Suspense>
<LazyInnerComponent>
`);
utils.act(() => root.render(<App renderChildren={false} />));
expect(store).toMatchInlineSnapshot(`
[root]
<App>
`);
utils.act(() => store.profilerStore.stopProfiling());
const rootID = store.roots[0];
const commitTrees = [];
for (let commitIndex = 0; commitIndex < 3; commitIndex++) {
commitTrees.push(
store.profilerStore.profilingCache.getCommitTree({
commitIndex,
rootID,
}),
);
}
expect(commitTrees[0].nodes.size).toBe(3); // <Root> + <App> + <Suspense>
expect(commitTrees[1].nodes.size).toBe(4); // <Root> + <App> + <Suspense> + <LazyInnerComponent>
expect(commitTrees[2].nodes.size).toBe(2); // <Root> + <App>
});
// @reactVersion >= 16.9
it('should support Lazy components that are unmounted before resolving (legacy render)', async () => {
const container = document.createElement('div');
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => legacyRender(<App renderChildren={true} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
▾ <App>
<Suspense>
`);
utils.act(() => legacyRender(<App renderChildren={false} />, container));
expect(store).toMatchInlineSnapshot(`
[root]
<App>
`);
utils.act(() => store.profilerStore.stopProfiling());
const rootID = store.roots[0];
const commitTrees = [];
for (let commitIndex = 0; commitIndex < 2; commitIndex++) {
commitTrees.push(
store.profilerStore.profilingCache.getCommitTree({
commitIndex,
rootID,
}),
);
}
expect(commitTrees[0].nodes.size).toBe(3); // <Root> + <App> + <Suspense>
expect(commitTrees[1].nodes.size).toBe(2); // <Root> + <App>
});
// @reactVersion >= 18.0
it('should support Lazy components that are unmounted before resolving (createRoot)', async () => {
const container = document.createElement('div');
const root = ReactDOMClient.createRoot(container);
utils.act(() => store.profilerStore.startProfiling());
utils.act(() => root.render(<App renderChildren={true} />));
expect(store).toMatchInlineSnapshot(`
[root]
▾ <App>
<Suspense>
`);
utils.act(() => root.render(<App renderChildren={false} />));
expect(store).toMatchInlineSnapshot(`
[root]
<App>
`);
utils.act(() => store.profilerStore.stopProfiling());
const rootID = store.roots[0];
const commitTrees = [];
for (let commitIndex = 0; commitIndex < 2; commitIndex++) {
commitTrees.push(
store.profilerStore.profilingCache.getCommitTree({
commitIndex,
rootID,
}),
);
}
expect(commitTrees[0].nodes.size).toBe(3); // <Root> + <App> + <Suspense>
expect(commitTrees[1].nodes.size).toBe(2); // <Root> + <App>
});
});
});
| 30.14652 | 106 | 0.565632 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = require("react");
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const A = /*#__PURE__*/(0, _react.createContext)(1);
const B = /*#__PURE__*/(0, _react.createContext)(2);
function Component() {
const a = (0, _react.useContext)(A);
const b = (0, _react.useContext)(B); // prettier-ignore
const c = (0, _react.useContext)(A),
d = (0, _react.useContext)(B); // eslint-disable-line one-var
return a + b + c + d;
}
//# sourceMappingURL=ComponentWithMultipleHooksPerLine.js.map?foo=bar¶m=some_value | 25.433333 | 86 | 0.655303 |
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';
let React;
let ReactNoop;
let Scheduler;
let act;
let readText;
let resolveText;
let startTransition;
let useState;
let useEffect;
let assertLog;
let waitFor;
let waitForAll;
let unstable_waitForExpired;
describe('ReactExpiration', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
startTransition = React.startTransition;
useState = React.useState;
useEffect = React.useEffect;
const InternalTestUtils = require('internal-test-utils');
assertLog = InternalTestUtils.assertLog;
waitFor = InternalTestUtils.waitFor;
waitForAll = InternalTestUtils.waitForAll;
unstable_waitForExpired = InternalTestUtils.unstable_waitForExpired;
const textCache = new Map();
readText = text => {
const record = textCache.get(text);
if (record !== undefined) {
switch (record.status) {
case 'pending':
throw record.promise;
case 'rejected':
throw Error('Failed to load: ' + text);
case 'resolved':
return text;
}
} else {
let ping;
const promise = new Promise(resolve => (ping = resolve));
const newRecord = {
status: 'pending',
ping: ping,
promise,
};
textCache.set(text, newRecord);
throw promise;
}
};
resolveText = text => {
const record = textCache.get(text);
if (record !== undefined) {
if (record.status === 'pending') {
Scheduler.log(`Promise resolved [${text}]`);
record.ping();
record.ping = null;
record.status = 'resolved';
clearTimeout(record.promise._timer);
record.promise = null;
}
} else {
const newRecord = {
ping: null,
status: 'resolved',
promise: null,
};
textCache.set(text, newRecord);
}
};
});
function Text(props) {
Scheduler.log(props.text);
return props.text;
}
function AsyncText(props) {
const text = props.text;
try {
readText(text);
Scheduler.log(text);
return text;
} catch (promise) {
if (typeof promise.then === 'function') {
Scheduler.log(`Suspend! [${text}]`);
if (typeof props.ms === 'number' && promise._timer === undefined) {
promise._timer = setTimeout(() => {
resolveText(text);
}, props.ms);
}
} else {
Scheduler.log(`Error! [${text}]`);
}
throw promise;
}
}
function flushNextRenderIfExpired() {
// This will start rendering the next level of work. If the work hasn't
// expired yet, React will exit without doing anything. If it has expired,
// it will schedule a sync task.
Scheduler.unstable_flushExpired();
// Flush the sync task.
ReactNoop.flushSync();
}
it('increases priority of updates as time progresses', async () => {
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
ReactNoop.render(<span prop="done" />);
expect(ReactNoop).toMatchRenderedOutput(null);
// Nothing has expired yet because time hasn't advanced.
flushNextRenderIfExpired();
expect(ReactNoop).toMatchRenderedOutput(null);
// Advance time a bit, but not enough to expire the low pri update.
ReactNoop.expire(4500);
flushNextRenderIfExpired();
expect(ReactNoop).toMatchRenderedOutput(null);
// Advance by another second. Now the update should expire and flush.
ReactNoop.expire(500);
flushNextRenderIfExpired();
expect(ReactNoop).toMatchRenderedOutput(<span prop="done" />);
} else {
ReactNoop.render(<Text text="Step 1" />);
React.startTransition(() => {
ReactNoop.render(<Text text="Step 2" />);
});
await waitFor(['Step 1']);
expect(ReactNoop).toMatchRenderedOutput('Step 1');
// Nothing has expired yet because time hasn't advanced.
await unstable_waitForExpired([]);
expect(ReactNoop).toMatchRenderedOutput('Step 1');
// Advance time a bit, but not enough to expire the low pri update.
ReactNoop.expire(4500);
await unstable_waitForExpired([]);
expect(ReactNoop).toMatchRenderedOutput('Step 1');
// Advance by a little bit more. Now the update should expire and flush.
ReactNoop.expire(500);
await unstable_waitForExpired(['Step 2']);
expect(ReactNoop).toMatchRenderedOutput('Step 2');
}
});
it('two updates of like priority in the same event always flush within the same batch', async () => {
class TextClass extends React.Component {
componentDidMount() {
Scheduler.log(`${this.props.text} [commit]`);
}
componentDidUpdate() {
Scheduler.log(`${this.props.text} [commit]`);
}
render() {
Scheduler.log(`${this.props.text} [render]`);
return <span prop={this.props.text} />;
}
}
function interrupt() {
ReactNoop.flushSync(() => {
ReactNoop.renderToRootWithID(null, 'other-root');
});
}
// First, show what happens for updates in two separate events.
// Schedule an update.
React.startTransition(() => {
ReactNoop.render(<TextClass text="A" />);
});
// Advance the timer.
Scheduler.unstable_advanceTime(2000);
// Partially flush the first update, then interrupt it.
await waitFor(['A [render]']);
interrupt();
// Don't advance time by enough to expire the first update.
assertLog([]);
expect(ReactNoop).toMatchRenderedOutput(null);
// Schedule another update.
ReactNoop.render(<TextClass text="B" />);
// Both updates are batched
await waitForAll(['B [render]', 'B [commit]']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Now do the same thing again, except this time don't flush any work in
// between the two updates.
ReactNoop.render(<TextClass text="A" />);
Scheduler.unstable_advanceTime(2000);
assertLog([]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Schedule another update.
ReactNoop.render(<TextClass text="B" />);
// The updates should flush in the same batch, since as far as the scheduler
// knows, they may have occurred inside the same event.
await waitForAll(['B [render]', 'B [commit]']);
});
it(
'two updates of like priority in the same event always flush within the ' +
"same batch, even if there's a sync update in between",
async () => {
class TextClass extends React.Component {
componentDidMount() {
Scheduler.log(`${this.props.text} [commit]`);
}
componentDidUpdate() {
Scheduler.log(`${this.props.text} [commit]`);
}
render() {
Scheduler.log(`${this.props.text} [render]`);
return <span prop={this.props.text} />;
}
}
function interrupt() {
ReactNoop.flushSync(() => {
ReactNoop.renderToRootWithID(null, 'other-root');
});
}
// First, show what happens for updates in two separate events.
// Schedule an update.
React.startTransition(() => {
ReactNoop.render(<TextClass text="A" />);
});
// Advance the timer.
Scheduler.unstable_advanceTime(2000);
// Partially flush the first update, then interrupt it.
await waitFor(['A [render]']);
interrupt();
// Don't advance time by enough to expire the first update.
assertLog([]);
expect(ReactNoop).toMatchRenderedOutput(null);
// Schedule another update.
ReactNoop.render(<TextClass text="B" />);
// Both updates are batched
await waitForAll(['B [render]', 'B [commit]']);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Now do the same thing again, except this time don't flush any work in
// between the two updates.
ReactNoop.render(<TextClass text="A" />);
Scheduler.unstable_advanceTime(2000);
assertLog([]);
expect(ReactNoop).toMatchRenderedOutput(<span prop="B" />);
// Perform some synchronous work. The scheduler must assume we're inside
// the same event.
interrupt();
// Schedule another update.
ReactNoop.render(<TextClass text="B" />);
// The updates should flush in the same batch, since as far as the scheduler
// knows, they may have occurred inside the same event.
await waitForAll(['B [render]', 'B [commit]']);
},
);
it('cannot update at the same expiration time that is already rendering', async () => {
const store = {text: 'initial'};
const subscribers = [];
class Connected extends React.Component {
state = {text: store.text};
componentDidMount() {
subscribers.push(this);
Scheduler.log(`${this.state.text} [${this.props.label}] [commit]`);
}
componentDidUpdate() {
Scheduler.log(`${this.state.text} [${this.props.label}] [commit]`);
}
render() {
Scheduler.log(`${this.state.text} [${this.props.label}] [render]`);
return <span prop={this.state.text} />;
}
}
function App() {
return (
<>
<Connected label="A" />
<Connected label="B" />
<Connected label="C" />
<Connected label="D" />
</>
);
}
// Initial mount
React.startTransition(() => {
ReactNoop.render(<App />);
});
await waitForAll([
'initial [A] [render]',
'initial [B] [render]',
'initial [C] [render]',
'initial [D] [render]',
'initial [A] [commit]',
'initial [B] [commit]',
'initial [C] [commit]',
'initial [D] [commit]',
]);
// Partial update
React.startTransition(() => {
subscribers.forEach(s => s.setState({text: '1'}));
});
await waitFor(['1 [A] [render]', '1 [B] [render]']);
// Before the update can finish, update again. Even though no time has
// advanced, this update should be given a different expiration time than
// the currently rendering one. So, C and D should render with 1, not 2.
React.startTransition(() => {
subscribers.forEach(s => s.setState({text: '2'}));
});
await waitFor(['1 [C] [render]', '1 [D] [render]']);
});
it('stops yielding if CPU-bound update takes too long to finish', async () => {
const root = ReactNoop.createRoot();
function App() {
return (
<>
<Text text="A" />
<Text text="B" />
<Text text="C" />
<Text text="D" />
<Text text="E" />
</>
);
}
React.startTransition(() => {
root.render(<App />);
});
await waitFor(['A']);
await waitFor(['B']);
await waitFor(['C']);
Scheduler.unstable_advanceTime(10000);
await unstable_waitForExpired(['D', 'E']);
expect(root).toMatchRenderedOutput('ABCDE');
});
it('root expiration is measured from the time of the first update', async () => {
Scheduler.unstable_advanceTime(10000);
const root = ReactNoop.createRoot();
function App() {
return (
<>
<Text text="A" />
<Text text="B" />
<Text text="C" />
<Text text="D" />
<Text text="E" />
</>
);
}
React.startTransition(() => {
root.render(<App />);
});
await waitFor(['A']);
await waitFor(['B']);
await waitFor(['C']);
Scheduler.unstable_advanceTime(10000);
await unstable_waitForExpired(['D', 'E']);
expect(root).toMatchRenderedOutput('ABCDE');
});
it('should measure expiration times relative to module initialization', async () => {
// Tests an implementation detail where expiration times are computed using
// bitwise operations.
jest.resetModules();
Scheduler = require('scheduler');
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
// Before importing the renderer, advance the current time by a number
// larger than the maximum allowed for bitwise operations.
const maxSigned31BitInt = 1073741823;
Scheduler.unstable_advanceTime(maxSigned31BitInt * 100);
// Now import the renderer. On module initialization, it will read the
// current time.
ReactNoop = require('react-noop-renderer');
ReactNoop.render('Hi');
// The update should not have expired yet.
flushNextRenderIfExpired();
await waitFor([]);
expect(ReactNoop).toMatchRenderedOutput(null);
// Advance the time some more to expire the update.
Scheduler.unstable_advanceTime(10000);
flushNextRenderIfExpired();
await waitFor([]);
expect(ReactNoop).toMatchRenderedOutput('Hi');
} else {
const InternalTestUtils = require('internal-test-utils');
waitFor = InternalTestUtils.waitFor;
assertLog = InternalTestUtils.assertLog;
unstable_waitForExpired = InternalTestUtils.unstable_waitForExpired;
// Before importing the renderer, advance the current time by a number
// larger than the maximum allowed for bitwise operations.
const maxSigned31BitInt = 1073741823;
Scheduler.unstable_advanceTime(maxSigned31BitInt * 100);
// Now import the renderer. On module initialization, it will read the
// current time.
ReactNoop = require('react-noop-renderer');
React = require('react');
ReactNoop.render(<Text text="Step 1" />);
React.startTransition(() => {
ReactNoop.render(<Text text="Step 2" />);
});
await waitFor(['Step 1']);
// The update should not have expired yet.
await unstable_waitForExpired([]);
expect(ReactNoop).toMatchRenderedOutput('Step 1');
// Advance the time some more to expire the update.
Scheduler.unstable_advanceTime(10000);
await unstable_waitForExpired(['Step 2']);
expect(ReactNoop).toMatchRenderedOutput('Step 2');
}
});
it('should measure callback timeout relative to current time, not start-up time', async () => {
// Corresponds to a bugfix: https://github.com/facebook/react/pull/15479
// The bug wasn't caught by other tests because we use virtual times that
// default to 0, and most tests don't advance time.
// Before scheduling an update, advance the current time.
Scheduler.unstable_advanceTime(10000);
React.startTransition(() => {
ReactNoop.render('Hi');
});
await unstable_waitForExpired([]);
expect(ReactNoop).toMatchRenderedOutput(null);
// Advancing by ~5 seconds should be sufficient to expire the update. (I
// used a slightly larger number to allow for possible rounding.)
Scheduler.unstable_advanceTime(6000);
await unstable_waitForExpired([]);
expect(ReactNoop).toMatchRenderedOutput('Hi');
});
it('prevents starvation by sync updates by disabling time slicing if too much time has elapsed', async () => {
let updateSyncPri;
let updateNormalPri;
function App() {
const [highPri, setHighPri] = useState(0);
const [normalPri, setNormalPri] = useState(0);
updateSyncPri = () => {
ReactNoop.flushSync(() => {
setHighPri(n => n + 1);
});
};
updateNormalPri = () => setNormalPri(n => n + 1);
return (
<>
<Text text={'Sync pri: ' + highPri} />
{', '}
<Text text={'Normal pri: ' + normalPri} />
</>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['Sync pri: 0', 'Normal pri: 0']);
expect(root).toMatchRenderedOutput('Sync pri: 0, Normal pri: 0');
// First demonstrate what happens when there's no starvation
await act(async () => {
React.startTransition(() => {
updateNormalPri();
});
await waitFor(['Sync pri: 0']);
updateSyncPri();
assertLog(['Sync pri: 1', 'Normal pri: 0']);
// The remaining work hasn't expired, so the render phase is time sliced.
// In other words, we can flush just the first child without flushing
// the rest.
//
// Yield right after first child.
await waitFor(['Sync pri: 1']);
// Now do the rest.
await waitForAll(['Normal pri: 1']);
});
expect(root).toMatchRenderedOutput('Sync pri: 1, Normal pri: 1');
// Do the same thing, but starve the first update
await act(async () => {
React.startTransition(() => {
updateNormalPri();
});
await waitFor(['Sync pri: 1']);
// This time, a lot of time has elapsed since the normal pri update
// started rendering. (This should advance time by some number that's
// definitely bigger than the constant heuristic we use to detect
// starvation of normal priority updates.)
Scheduler.unstable_advanceTime(10000);
updateSyncPri();
assertLog(['Sync pri: 2', 'Normal pri: 1']);
// The remaining work _has_ expired, so the render phase is _not_ time
// sliced. Attempting to flush just the first child also flushes the rest.
await waitFor(['Sync pri: 2'], {
additionalLogsAfterAttemptingToYield: ['Normal pri: 2'],
});
});
expect(root).toMatchRenderedOutput('Sync pri: 2, Normal pri: 2');
});
it('idle work never expires', async () => {
let updateSyncPri;
let updateIdlePri;
function App() {
const [syncPri, setSyncPri] = useState(0);
const [highPri, setIdlePri] = useState(0);
updateSyncPri = () => ReactNoop.flushSync(() => setSyncPri(n => n + 1));
updateIdlePri = () =>
ReactNoop.idleUpdates(() => {
setIdlePri(n => n + 1);
});
return (
<>
<Text text={'Sync pri: ' + syncPri} />
{', '}
<Text text={'Idle pri: ' + highPri} />
</>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['Sync pri: 0', 'Idle pri: 0']);
expect(root).toMatchRenderedOutput('Sync pri: 0, Idle pri: 0');
// First demonstrate what happens when there's no starvation
await act(async () => {
updateIdlePri();
await waitFor(['Sync pri: 0']);
updateSyncPri();
});
// Same thing should happen as last time
assertLog([
// Interrupt idle update to render sync update
'Sync pri: 1',
'Idle pri: 0',
// Now render idle
'Sync pri: 1',
'Idle pri: 1',
]);
expect(root).toMatchRenderedOutput('Sync pri: 1, Idle pri: 1');
// Do the same thing, but starve the first update
await act(async () => {
updateIdlePri();
await waitFor(['Sync pri: 1']);
// Advance a ridiculously large amount of time to demonstrate that the
// idle work never expires
Scheduler.unstable_advanceTime(100000);
updateSyncPri();
});
assertLog([
// Interrupt idle update to render sync update
'Sync pri: 2',
'Idle pri: 1',
// Now render idle
'Sync pri: 2',
'Idle pri: 2',
]);
expect(root).toMatchRenderedOutput('Sync pri: 2, Idle pri: 2');
});
it('when multiple lanes expire, we can finish the in-progress one without including the others', async () => {
let setA;
let setB;
function App() {
const [a, _setA] = useState(0);
const [b, _setB] = useState(0);
setA = _setA;
setB = _setB;
return (
<>
<Text text={'A' + a} />
<Text text={'B' + b} />
<Text text="C" />
</>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['A0', 'B0', 'C']);
expect(root).toMatchRenderedOutput('A0B0C');
await act(async () => {
startTransition(() => {
setA(1);
});
await waitFor(['A1']);
startTransition(() => {
setB(1);
});
await waitFor(['B0']);
// Expire both the transitions
Scheduler.unstable_advanceTime(10000);
// Both transitions have expired, but since they aren't related
// (entangled), we should be able to finish the in-progress transition
// without also including the next one.
await waitFor([], {
additionalLogsAfterAttemptingToYield: ['C'],
});
expect(root).toMatchRenderedOutput('A1B0C');
// The next transition also finishes without yielding.
await waitFor(['A1'], {
additionalLogsAfterAttemptingToYield: ['B1', 'C'],
});
expect(root).toMatchRenderedOutput('A1B1C');
});
});
it('updates do not expire while they are IO-bound', async () => {
const {Suspense} = React;
function App({step}) {
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText text={'A' + step} />
<Text text="B" />
<Text text="C" />
</Suspense>
);
}
const root = ReactNoop.createRoot();
await act(async () => {
await resolveText('A0');
root.render(<App step={0} />);
});
assertLog(['A0', 'B', 'C']);
expect(root).toMatchRenderedOutput('A0BC');
await act(async () => {
React.startTransition(() => {
root.render(<App step={1} />);
});
await waitForAll(['Suspend! [A1]', 'Loading...']);
// Lots of time elapses before the promise resolves
Scheduler.unstable_advanceTime(10000);
await resolveText('A1');
assertLog(['Promise resolved [A1]']);
await waitFor(['A1']);
expect(root).toMatchRenderedOutput('A0BC');
// Lots more time elapses. We're CPU-bound now, so we should treat this
// as starvation.
Scheduler.unstable_advanceTime(10000);
// The rest of the update finishes without yielding.
await waitFor([], {
additionalLogsAfterAttemptingToYield: ['B', 'C'],
});
});
});
it('flushSync should not affect expired work', async () => {
let setA;
let setB;
function App() {
const [a, _setA] = useState(0);
const [b, _setB] = useState(0);
setA = _setA;
setB = _setB;
return (
<>
<Text text={'A' + a} />
<Text text={'B' + b} />
</>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App />);
});
assertLog(['A0', 'B0']);
await act(async () => {
startTransition(() => {
setA(1);
});
await waitFor(['A1']);
// Expire the in-progress update
Scheduler.unstable_advanceTime(10000);
ReactNoop.flushSync(() => {
setB(1);
});
assertLog(['A0', 'B1']);
// Now flush the original update. Because it expired, it should finish
// without yielding.
await waitFor(['A1'], {
additionalLogsAfterAttemptingToYield: ['B1'],
});
});
});
it('passive effects of expired update flush after paint', async () => {
function App({step}) {
useEffect(() => {
Scheduler.log('Effect: ' + step);
}, [step]);
return (
<>
<Text text={'A' + step} />
<Text text={'B' + step} />
<Text text={'C' + step} />
</>
);
}
const root = ReactNoop.createRoot();
await act(() => {
root.render(<App step={0} />);
});
assertLog(['A0', 'B0', 'C0', 'Effect: 0']);
expect(root).toMatchRenderedOutput('A0B0C0');
await act(async () => {
startTransition(() => {
root.render(<App step={1} />);
});
await waitFor(['A1']);
// Expire the update
Scheduler.unstable_advanceTime(10000);
// The update finishes without yielding. But it does not flush the effect.
await waitFor(['B1'], {
additionalLogsAfterAttemptingToYield: ['C1'],
});
});
// The effect flushes after paint.
assertLog(['Effect: 1']);
});
});
| 29.277916 | 112 | 0.585051 |
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.
*
* Based on the escape-html library, which is used under the MIT License below:
*
* Copyright (c) 2012-2013 TJ Holowaychuk
* Copyright (c) 2015 Andreas Lubbe
* Copyright (c) 2015 Tiancheng "Timothy" Gu
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
// code copied and modified from escape-html
/**
* Module variables.
* @private
*/
import {checkHtmlStringCoercion} from 'shared/CheckStringCoercion';
const matchHtmlRegExp = /["'&<>]/;
/**
* Escapes special characters and HTML entities in a given html string.
*
* @param {string} string HTML string to escape for later insertion
* @return {string}
* @public
*/
function escapeHtml(string: string) {
if (__DEV__) {
checkHtmlStringCoercion(string);
}
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = '''; // modified from escape-html; used to be '''
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.slice(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
}
// end code copied and modified from escape-html
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextForBrowser(text: string | number | boolean): string {
if (typeof text === 'boolean' || typeof text === 'number') {
// this shortcircuit helps perf for types that we know will never have
// special characters, especially given that this function is used often
// for numeric dom ids.
return '' + (text: any);
}
return escapeHtml(text);
}
export default escapeTextForBrowser;
| 27.89916 | 79 | 0.663467 |
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 {HostContext, HostContextDev} from './ReactFiberConfigDOM';
import {HostContextNamespaceNone} from './ReactFiberConfigDOM';
import {
registrationNameDependencies,
possibleRegistrationNames,
} from '../events/EventRegistry';
import {canUseDOM} from 'shared/ExecutionEnvironment';
import {checkHtmlStringCoercion} from 'shared/CheckStringCoercion';
import {checkAttributeStringCoercion} from 'shared/CheckStringCoercion';
import {checkControlledValueProps} from '../shared/ReactControlledValuePropTypes';
import {
getValueForAttribute,
getValueForAttributeOnCustomComponent,
setValueForPropertyOnCustomComponent,
setValueForKnownAttribute,
setValueForAttribute,
setValueForNamespacedAttribute,
} from './DOMPropertyOperations';
import {
validateInputProps,
initInput,
updateInput,
restoreControlledInputState,
} from './ReactDOMInput';
import {validateOptionProps} from './ReactDOMOption';
import {
validateSelectProps,
initSelect,
restoreControlledSelectState,
updateSelect,
} from './ReactDOMSelect';
import {
validateTextareaProps,
initTextarea,
updateTextarea,
restoreControlledTextareaState,
} from './ReactDOMTextarea';
import {validateTextNesting} from './validateDOMNesting';
import {track} from './inputValueTracking';
import setInnerHTML from './setInnerHTML';
import setTextContent from './setTextContent';
import {
createDangerousStringForStyles,
setValueForStyles,
} from './CSSPropertyOperations';
import {SVG_NAMESPACE, MATH_NAMESPACE} from './DOMNamespaces';
import isCustomElement from '../shared/isCustomElement';
import getAttributeAlias from '../shared/getAttributeAlias';
import possibleStandardNames from '../shared/possibleStandardNames';
import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook';
import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook';
import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook';
import sanitizeURL from '../shared/sanitizeURL';
import {
enableCustomElementPropertySupport,
enableClientRenderFallbackOnTextMismatch,
enableFormActions,
disableIEWorkarounds,
enableTrustedTypesIntegration,
enableFilterEmptyStringAttributesDOM,
} from 'shared/ReactFeatureFlags';
import {
mediaEventTypes,
listenToNonDelegatedEvent,
} from '../events/DOMPluginEventSystem';
let didWarnControlledToUncontrolled = false;
let didWarnUncontrolledToControlled = false;
let didWarnInvalidHydration = false;
let didWarnFormActionType = false;
let didWarnFormActionName = false;
let didWarnFormActionTarget = false;
let didWarnFormActionMethod = false;
let canDiffStyleForHydrationWarning;
if (__DEV__) {
// IE 11 parses & normalizes the style attribute as opposed to other
// browsers. It adds spaces and sorts the properties in some
// non-alphabetical order. Handling that would require sorting CSS
// properties in the client & server versions or applying
// `expectedStyle` to a temporary DOM node to read its `style` attribute
// normalized. Since it only affects IE, we're skipping style warnings
// in that browser completely in favor of doing all that work.
// See https://github.com/facebook/react/issues/11807
canDiffStyleForHydrationWarning =
disableIEWorkarounds || (canUseDOM && !document.documentMode);
}
function validatePropertiesInDevelopment(type: string, props: any) {
if (__DEV__) {
validateARIAProperties(type, props);
validateInputProperties(type, props);
validateUnknownProperties(type, props, {
registrationNameDependencies,
possibleRegistrationNames,
});
if (
props.contentEditable &&
!props.suppressContentEditableWarning &&
props.children != null
) {
console.error(
'A component is `contentEditable` and contains `children` managed by ' +
'React. It is now your responsibility to guarantee that none of ' +
'those nodes are unexpectedly modified or duplicated. This is ' +
'probably not intentional.',
);
}
}
}
function validateFormActionInDevelopment(
tag: string,
key: string,
value: mixed,
props: any,
) {
if (__DEV__) {
if (value == null) {
return;
}
if (tag === 'form') {
if (key === 'formAction') {
console.error(
'You can only pass the formAction prop to <input> or <button>. Use the action prop on <form>.',
);
} else if (typeof value === 'function') {
if (
(props.encType != null || props.method != null) &&
!didWarnFormActionMethod
) {
didWarnFormActionMethod = true;
console.error(
'Cannot specify a encType or method for a form that specifies a ' +
'function as the action. React provides those automatically. ' +
'They will get overridden.',
);
}
if (props.target != null && !didWarnFormActionTarget) {
didWarnFormActionTarget = true;
console.error(
'Cannot specify a target for a form that specifies a function as the action. ' +
'The function will always be executed in the same window.',
);
}
}
} else if (tag === 'input' || tag === 'button') {
if (key === 'action') {
console.error(
'You can only pass the action prop to <form>. Use the formAction prop on <input> or <button>.',
);
} else if (
tag === 'input' &&
props.type !== 'submit' &&
props.type !== 'image' &&
!didWarnFormActionType
) {
didWarnFormActionType = true;
console.error(
'An input can only specify a formAction along with type="submit" or type="image".',
);
} else if (
tag === 'button' &&
props.type != null &&
props.type !== 'submit' &&
!didWarnFormActionType
) {
didWarnFormActionType = true;
console.error(
'A button can only specify a formAction along with type="submit" or no type.',
);
} else if (typeof value === 'function') {
// Function form actions cannot control the form properties
if (props.name != null && !didWarnFormActionName) {
didWarnFormActionName = true;
console.error(
'Cannot specify a "name" prop for a button that specifies a function as a formAction. ' +
'React needs it to encode which action should be invoked. It will get overridden.',
);
}
if (
(props.formEncType != null || props.formMethod != null) &&
!didWarnFormActionMethod
) {
didWarnFormActionMethod = true;
console.error(
'Cannot specify a formEncType or formMethod for a button that specifies a ' +
'function as a formAction. React provides those automatically. They will get overridden.',
);
}
if (props.formTarget != null && !didWarnFormActionTarget) {
didWarnFormActionTarget = true;
console.error(
'Cannot specify a formTarget for a button that specifies a function as a formAction. ' +
'The function will always be executed in the same window.',
);
}
}
} else {
if (key === 'action') {
console.error('You can only pass the action prop to <form>.');
} else {
console.error(
'You can only pass the formAction prop to <input> or <button>.',
);
}
}
}
}
function warnForPropDifference(
propName: string,
serverValue: mixed,
clientValue: mixed,
) {
if (__DEV__) {
if (didWarnInvalidHydration) {
return;
}
if (serverValue === clientValue) {
return;
}
const normalizedClientValue =
normalizeMarkupForTextOrAttribute(clientValue);
const normalizedServerValue =
normalizeMarkupForTextOrAttribute(serverValue);
if (normalizedServerValue === normalizedClientValue) {
return;
}
didWarnInvalidHydration = true;
console.error(
'Prop `%s` did not match. Server: %s Client: %s',
propName,
JSON.stringify(normalizedServerValue),
JSON.stringify(normalizedClientValue),
);
}
}
function warnForExtraAttributes(attributeNames: Set<string>) {
if (__DEV__) {
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
const names = [];
attributeNames.forEach(function (name) {
names.push(name);
});
console.error('Extra attributes from the server: %s', names);
}
}
function warnForInvalidEventListener(registrationName: string, listener: any) {
if (__DEV__) {
if (listener === false) {
console.error(
'Expected `%s` listener to be a function, instead got `false`.\n\n' +
'If you used to conditionally omit it with %s={condition && value}, ' +
'pass %s={condition ? value : undefined} instead.',
registrationName,
registrationName,
registrationName,
);
} else {
console.error(
'Expected `%s` listener to be a function, instead got a value of `%s` type.',
registrationName,
typeof listener,
);
}
}
}
// Parse the HTML and read it back to normalize the HTML string so that it
// can be used for comparison.
function normalizeHTML(parent: Element, html: string) {
if (__DEV__) {
// We could have created a separate document here to avoid
// re-initializing custom elements if they exist. But this breaks
// how <noscript> is being handled. So we use the same document.
// See the discussion in https://github.com/facebook/react/pull/11157.
const testElement =
parent.namespaceURI === MATH_NAMESPACE ||
parent.namespaceURI === SVG_NAMESPACE
? parent.ownerDocument.createElementNS(
(parent.namespaceURI: any),
parent.tagName,
)
: parent.ownerDocument.createElement(parent.tagName);
testElement.innerHTML = html;
return testElement.innerHTML;
}
}
// HTML parsing normalizes CR and CRLF to LF.
// It also can turn \u0000 into \uFFFD inside attributes.
// https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
// If we have a mismatch, it might be caused by that.
// We will still patch up in this case but not fire the warning.
const NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
const NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
function normalizeMarkupForTextOrAttribute(markup: mixed): string {
if (__DEV__) {
checkHtmlStringCoercion(markup);
}
const markupString = typeof markup === 'string' ? markup : '' + (markup: any);
return markupString
.replace(NORMALIZE_NEWLINES_REGEX, '\n')
.replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
}
export function checkForUnmatchedText(
serverText: string,
clientText: string | number,
isConcurrentMode: boolean,
shouldWarnDev: boolean,
) {
const normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
const normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
if (normalizedServerText === normalizedClientText) {
return;
}
if (shouldWarnDev) {
if (__DEV__) {
if (!didWarnInvalidHydration) {
didWarnInvalidHydration = true;
console.error(
'Text content did not match. Server: "%s" Client: "%s"',
normalizedServerText,
normalizedClientText,
);
}
}
}
if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) {
// In concurrent roots, we throw when there's a text mismatch and revert to
// client rendering, up to the nearest Suspense boundary.
throw new Error('Text content does not match server-rendered HTML.');
}
}
function noop() {}
export function trapClickOnNonInteractiveElement(node: HTMLElement) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
// https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
// Just set it using the onclick property so that we don't have to manage any
// bookkeeping for it. Not sure if we need to clear it when the listener is
// removed.
// TODO: Only do this for the relevant Safaris maybe?
node.onclick = noop;
}
const xlinkNamespace = 'http://www.w3.org/1999/xlink';
const xmlNamespace = 'http://www.w3.org/XML/1998/namespace';
function setProp(
domElement: Element,
tag: string,
key: string,
value: mixed,
props: any,
prevValue: mixed,
): void {
switch (key) {
case 'children': {
if (typeof value === 'string') {
if (__DEV__) {
validateTextNesting(value, tag);
}
// Avoid setting initial textContent when the text is empty. In IE11 setting
// textContent on a <textarea> will cause the placeholder to not
// show within the <textarea> until it has been focused and blurred again.
// https://github.com/facebook/react/issues/6731#issuecomment-254874553
const canSetTextContent =
tag !== 'body' && (tag !== 'textarea' || value !== '');
if (canSetTextContent) {
setTextContent(domElement, value);
}
} else if (typeof value === 'number') {
if (__DEV__) {
validateTextNesting('' + value, tag);
}
const canSetTextContent = tag !== 'body';
if (canSetTextContent) {
setTextContent(domElement, '' + value);
}
}
break;
}
// These are very common props and therefore are in the beginning of the switch.
// TODO: aria-label is a very common prop but allows booleans so is not like the others
// but should ideally go in this list too.
case 'className':
setValueForKnownAttribute(domElement, 'class', value);
break;
case 'tabIndex':
// This has to be case sensitive in SVG.
setValueForKnownAttribute(domElement, 'tabindex', value);
break;
case 'dir':
case 'role':
case 'viewBox':
case 'width':
case 'height': {
setValueForKnownAttribute(domElement, key, value);
break;
}
case 'style': {
setValueForStyles(domElement, value, prevValue);
break;
}
// These attributes accept URLs. These must not allow javascript: URLS.
case 'src':
case 'href': {
if (enableFilterEmptyStringAttributesDOM) {
if (value === '') {
if (__DEV__) {
if (key === 'src') {
console.error(
'An empty string ("") was passed to the %s attribute. ' +
'This may cause the browser to download the whole page again over the network. ' +
'To fix this, either do not render the element at all ' +
'or pass null to %s instead of an empty string.',
key,
key,
);
} else {
console.error(
'An empty string ("") was passed to the %s attribute. ' +
'To fix this, either do not render the element at all ' +
'or pass null to %s instead of an empty string.',
key,
key,
);
}
}
domElement.removeAttribute(key);
break;
}
}
if (
value == null ||
typeof value === 'function' ||
typeof value === 'symbol' ||
typeof value === 'boolean'
) {
domElement.removeAttribute(key);
break;
}
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (__DEV__) {
checkAttributeStringCoercion(value, key);
}
const sanitizedValue = (sanitizeURL(
enableTrustedTypesIntegration ? value : '' + (value: any),
): any);
domElement.setAttribute(key, sanitizedValue);
break;
}
case 'action':
case 'formAction': {
// TODO: Consider moving these special cases to the form, input and button tags.
if (__DEV__) {
validateFormActionInDevelopment(tag, key, value, props);
}
if (enableFormActions) {
if (typeof value === 'function') {
// Set a javascript URL that doesn't do anything. We don't expect this to be invoked
// because we'll preventDefault, but it can happen if a form is manually submitted or
// if someone calls stopPropagation before React gets the event.
// If CSP is used to block javascript: URLs that's fine too. It just won't show this
// error message but the URL will be logged.
domElement.setAttribute(
key,
// eslint-disable-next-line no-script-url
"javascript:throw new Error('" +
'A React form was unexpectedly submitted. If you called form.submit() manually, ' +
"consider using form.requestSubmit() instead. If you\\'re trying to use " +
'event.stopPropagation() in a submit event handler, consider also calling ' +
'event.preventDefault().' +
"')",
);
break;
} else if (typeof prevValue === 'function') {
// When we're switching off a Server Action that was originally hydrated.
// The server control these fields during SSR that are now trailing.
// The regular diffing doesn't apply since we compare against the previous props.
// Instead, we need to force them to be set to whatever they should be now.
// This would be a lot cleaner if we did this whole fork in the per-tag approach.
if (key === 'formAction') {
if (tag !== 'input') {
// Setting the name here isn't completely safe for inputs if this is switching
// to become a radio button. In that case we let the tag based override take
// control.
setProp(domElement, tag, 'name', props.name, props, null);
}
setProp(
domElement,
tag,
'formEncType',
props.formEncType,
props,
null,
);
setProp(
domElement,
tag,
'formMethod',
props.formMethod,
props,
null,
);
setProp(
domElement,
tag,
'formTarget',
props.formTarget,
props,
null,
);
} else {
setProp(domElement, tag, 'encType', props.encType, props, null);
setProp(domElement, tag, 'method', props.method, props, null);
setProp(domElement, tag, 'target', props.target, props, null);
}
}
}
if (
value == null ||
(!enableFormActions && typeof value === 'function') ||
typeof value === 'symbol' ||
typeof value === 'boolean'
) {
domElement.removeAttribute(key);
break;
}
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (__DEV__) {
checkAttributeStringCoercion(value, key);
}
const sanitizedValue = (sanitizeURL(
enableTrustedTypesIntegration ? value : '' + (value: any),
): any);
domElement.setAttribute(key, sanitizedValue);
break;
}
case 'onClick': {
// TODO: This cast may not be sound for SVG, MathML or custom elements.
if (value != null) {
if (__DEV__ && typeof value !== 'function') {
warnForInvalidEventListener(key, value);
}
trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
}
break;
}
case 'onScroll': {
if (value != null) {
if (__DEV__ && typeof value !== 'function') {
warnForInvalidEventListener(key, value);
}
listenToNonDelegatedEvent('scroll', domElement);
}
break;
}
case 'onScrollEnd': {
if (value != null) {
if (__DEV__ && typeof value !== 'function') {
warnForInvalidEventListener(key, value);
}
listenToNonDelegatedEvent('scrollend', domElement);
}
break;
}
case 'dangerouslySetInnerHTML': {
if (value != null) {
if (typeof value !== 'object' || !('__html' in value)) {
throw new Error(
'`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' +
'Please visit https://reactjs.org/link/dangerously-set-inner-html ' +
'for more information.',
);
}
const nextHtml: any = value.__html;
if (nextHtml != null) {
if (props.children != null) {
throw new Error(
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
);
}
if (disableIEWorkarounds) {
domElement.innerHTML = nextHtml;
} else {
setInnerHTML(domElement, nextHtml);
}
}
}
break;
}
// Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
case 'multiple': {
(domElement: any).multiple =
value && typeof value !== 'function' && typeof value !== 'symbol';
break;
}
case 'muted': {
(domElement: any).muted =
value && typeof value !== 'function' && typeof value !== 'symbol';
break;
}
case 'suppressContentEditableWarning':
case 'suppressHydrationWarning':
case 'defaultValue': // Reserved
case 'defaultChecked':
case 'innerHTML': {
// Noop
break;
}
case 'autoFocus': {
// We polyfill it separately on the client during commit.
// We could have excluded it in the property list instead of
// adding a special case here, but then it wouldn't be emitted
// on server rendering (but we *do* want to emit it in SSR).
break;
}
case 'xlinkHref': {
if (
value == null ||
typeof value === 'function' ||
typeof value === 'boolean' ||
typeof value === 'symbol'
) {
domElement.removeAttribute('xlink:href');
break;
}
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (__DEV__) {
checkAttributeStringCoercion(value, key);
}
const sanitizedValue = (sanitizeURL(
enableTrustedTypesIntegration ? value : '' + (value: any),
): any);
domElement.setAttributeNS(xlinkNamespace, 'xlink:href', sanitizedValue);
break;
}
case 'contentEditable':
case 'spellCheck':
case 'draggable':
case 'value':
case 'autoReverse':
case 'externalResourcesRequired':
case 'focusable':
case 'preserveAlpha': {
// Booleanish String
// These are "enumerated" attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// The SVG attributes are case-sensitive. Since the HTML attributes are
// insensitive they also work even though we canonically use lower case.
if (
value != null &&
typeof value !== 'function' &&
typeof value !== 'symbol'
) {
if (__DEV__) {
checkAttributeStringCoercion(value, key);
}
domElement.setAttribute(
key,
enableTrustedTypesIntegration ? (value: any) : '' + (value: any),
);
} else {
domElement.removeAttribute(key);
}
break;
}
// Boolean
case 'allowFullScreen':
case 'async':
case 'autoPlay':
case 'controls':
case 'default':
case 'defer':
case 'disabled':
case 'disablePictureInPicture':
case 'disableRemotePlayback':
case 'formNoValidate':
case 'hidden':
case 'loop':
case 'noModule':
case 'noValidate':
case 'open':
case 'playsInline':
case 'readOnly':
case 'required':
case 'reversed':
case 'scoped':
case 'seamless':
case 'itemScope': {
if (value && typeof value !== 'function' && typeof value !== 'symbol') {
domElement.setAttribute(key, '');
} else {
domElement.removeAttribute(key);
}
break;
}
// Overloaded Boolean
case 'capture':
case 'download': {
// An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.
if (value === true) {
domElement.setAttribute(key, '');
} else if (
value !== false &&
value != null &&
typeof value !== 'function' &&
typeof value !== 'symbol'
) {
if (__DEV__) {
checkAttributeStringCoercion(value, key);
}
domElement.setAttribute(key, (value: any));
} else {
domElement.removeAttribute(key);
}
break;
}
case 'cols':
case 'rows':
case 'size':
case 'span': {
// These are HTML attributes that must be positive numbers.
if (
value != null &&
typeof value !== 'function' &&
typeof value !== 'symbol' &&
!isNaN(value) &&
(value: any) >= 1
) {
if (__DEV__) {
checkAttributeStringCoercion(value, key);
}
domElement.setAttribute(key, (value: any));
} else {
domElement.removeAttribute(key);
}
break;
}
case 'rowSpan':
case 'start': {
// These are HTML attributes that must be numbers.
if (
value != null &&
typeof value !== 'function' &&
typeof value !== 'symbol' &&
!isNaN(value)
) {
if (__DEV__) {
checkAttributeStringCoercion(value, key);
}
domElement.setAttribute(key, (value: any));
} else {
domElement.removeAttribute(key);
}
break;
}
case 'xlinkActuate':
setValueForNamespacedAttribute(
domElement,
xlinkNamespace,
'xlink:actuate',
value,
);
break;
case 'xlinkArcrole':
setValueForNamespacedAttribute(
domElement,
xlinkNamespace,
'xlink:arcrole',
value,
);
break;
case 'xlinkRole':
setValueForNamespacedAttribute(
domElement,
xlinkNamespace,
'xlink:role',
value,
);
break;
case 'xlinkShow':
setValueForNamespacedAttribute(
domElement,
xlinkNamespace,
'xlink:show',
value,
);
break;
case 'xlinkTitle':
setValueForNamespacedAttribute(
domElement,
xlinkNamespace,
'xlink:title',
value,
);
break;
case 'xlinkType':
setValueForNamespacedAttribute(
domElement,
xlinkNamespace,
'xlink:type',
value,
);
break;
case 'xmlBase':
setValueForNamespacedAttribute(
domElement,
xmlNamespace,
'xml:base',
value,
);
break;
case 'xmlLang':
setValueForNamespacedAttribute(
domElement,
xmlNamespace,
'xml:lang',
value,
);
break;
case 'xmlSpace':
setValueForNamespacedAttribute(
domElement,
xmlNamespace,
'xml:space',
value,
);
break;
// Properties that should not be allowed on custom elements.
case 'is': {
if (__DEV__) {
if (prevValue != null) {
console.error(
'Cannot update the "is" prop after it has been initialized.',
);
}
}
// TODO: We shouldn't actually set this attribute, because we've already
// passed it to createElement. We don't also need the attribute.
// However, our tests currently query for it so it's plausible someone
// else does too so it's break.
setValueForAttribute(domElement, 'is', value);
break;
}
case 'innerText':
case 'textContent':
if (enableCustomElementPropertySupport) {
break;
}
// Fall through
default: {
if (
key.length > 2 &&
(key[0] === 'o' || key[0] === 'O') &&
(key[1] === 'n' || key[1] === 'N')
) {
if (
__DEV__ &&
registrationNameDependencies.hasOwnProperty(key) &&
value != null &&
typeof value !== 'function'
) {
warnForInvalidEventListener(key, value);
}
} else {
const attributeName = getAttributeAlias(key);
setValueForAttribute(domElement, attributeName, value);
}
}
}
}
function setPropOnCustomElement(
domElement: Element,
tag: string,
key: string,
value: mixed,
props: any,
prevValue: mixed,
): void {
switch (key) {
case 'style': {
setValueForStyles(domElement, value, prevValue);
break;
}
case 'dangerouslySetInnerHTML': {
if (value != null) {
if (typeof value !== 'object' || !('__html' in value)) {
throw new Error(
'`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' +
'Please visit https://reactjs.org/link/dangerously-set-inner-html ' +
'for more information.',
);
}
const nextHtml: any = value.__html;
if (nextHtml != null) {
if (props.children != null) {
throw new Error(
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
);
}
if (disableIEWorkarounds) {
domElement.innerHTML = nextHtml;
} else {
setInnerHTML(domElement, nextHtml);
}
}
}
break;
}
case 'children': {
if (typeof value === 'string') {
setTextContent(domElement, value);
} else if (typeof value === 'number') {
setTextContent(domElement, '' + value);
}
break;
}
case 'onScroll': {
if (value != null) {
if (__DEV__ && typeof value !== 'function') {
warnForInvalidEventListener(key, value);
}
listenToNonDelegatedEvent('scroll', domElement);
}
break;
}
case 'onScrollEnd': {
if (value != null) {
if (__DEV__ && typeof value !== 'function') {
warnForInvalidEventListener(key, value);
}
listenToNonDelegatedEvent('scrollend', domElement);
}
break;
}
case 'onClick': {
// TODO: This cast may not be sound for SVG, MathML or custom elements.
if (value != null) {
if (__DEV__ && typeof value !== 'function') {
warnForInvalidEventListener(key, value);
}
trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
}
break;
}
case 'suppressContentEditableWarning':
case 'suppressHydrationWarning':
case 'innerHTML': {
// Noop
break;
}
case 'innerText': // Properties
case 'textContent':
if (enableCustomElementPropertySupport) {
break;
}
// Fall through
default: {
if (registrationNameDependencies.hasOwnProperty(key)) {
if (__DEV__ && value != null && typeof value !== 'function') {
warnForInvalidEventListener(key, value);
}
} else {
if (enableCustomElementPropertySupport) {
setValueForPropertyOnCustomComponent(domElement, key, value);
} else {
if (typeof value === 'boolean') {
// Special case before the new flag is on
value = '' + (value: any);
}
setValueForAttribute(domElement, key, value);
}
}
}
}
}
export function setInitialProperties(
domElement: Element,
tag: string,
props: Object,
): void {
if (__DEV__) {
validatePropertiesInDevelopment(tag, props);
}
// TODO: Make sure that we check isMounted before firing any of these events.
switch (tag) {
case 'div':
case 'span':
case 'svg':
case 'path':
case 'a':
case 'g':
case 'p':
case 'li': {
// Fast track the most common tag types
break;
}
case 'input': {
if (__DEV__) {
checkControlledValueProps('input', props);
}
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
let name = null;
let type = null;
let value = null;
let defaultValue = null;
let checked = null;
let defaultChecked = null;
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const propValue = props[propKey];
if (propValue == null) {
continue;
}
switch (propKey) {
case 'name': {
name = propValue;
break;
}
case 'type': {
type = propValue;
break;
}
case 'checked': {
checked = propValue;
break;
}
case 'defaultChecked': {
defaultChecked = propValue;
break;
}
case 'value': {
value = propValue;
break;
}
case 'defaultValue': {
defaultValue = propValue;
break;
}
case 'children':
case 'dangerouslySetInnerHTML': {
if (propValue != null) {
throw new Error(
`${tag} is a void element tag and must neither have \`children\` nor ` +
'use `dangerouslySetInnerHTML`.',
);
}
break;
}
default: {
setProp(domElement, tag, propKey, propValue, props, null);
}
}
}
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
validateInputProps(domElement, props);
initInput(
domElement,
value,
defaultValue,
checked,
defaultChecked,
type,
name,
false,
);
track((domElement: any));
return;
}
case 'select': {
if (__DEV__) {
checkControlledValueProps('select', props);
}
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
let value = null;
let defaultValue = null;
let multiple = null;
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const propValue = props[propKey];
if (propValue == null) {
continue;
}
switch (propKey) {
case 'value': {
value = propValue;
// This is handled by initSelect below.
break;
}
case 'defaultValue': {
defaultValue = propValue;
// This is handled by initSelect below.
break;
}
case 'multiple': {
multiple = propValue;
// TODO: We don't actually have to fall through here because we set it
// in initSelect anyway. We can remove the special case in setProp.
}
// Fallthrough
default: {
setProp(domElement, tag, propKey, propValue, props, null);
}
}
}
validateSelectProps(domElement, props);
initSelect(domElement, value, defaultValue, multiple);
return;
}
case 'textarea': {
if (__DEV__) {
checkControlledValueProps('textarea', props);
}
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
let value = null;
let defaultValue = null;
let children = null;
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const propValue = props[propKey];
if (propValue == null) {
continue;
}
switch (propKey) {
case 'value': {
value = propValue;
// This is handled by initTextarea below.
break;
}
case 'defaultValue': {
defaultValue = propValue;
break;
}
case 'children': {
children = propValue;
// Handled by initTextarea above.
break;
}
case 'dangerouslySetInnerHTML': {
if (propValue != null) {
// TODO: Do we really need a special error message for this. It's also pretty blunt.
throw new Error(
'`dangerouslySetInnerHTML` does not make sense on <textarea>.',
);
}
break;
}
default: {
setProp(domElement, tag, propKey, propValue, props, null);
}
}
}
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
validateTextareaProps(domElement, props);
initTextarea(domElement, value, defaultValue, children);
track((domElement: any));
return;
}
case 'option': {
validateOptionProps(domElement, props);
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const propValue = props[propKey];
if (propValue == null) {
continue;
}
switch (propKey) {
case 'selected': {
// TODO: Remove support for selected on option.
(domElement: any).selected =
propValue &&
typeof propValue !== 'function' &&
typeof propValue !== 'symbol';
break;
}
default: {
setProp(domElement, tag, propKey, propValue, props, null);
}
}
}
return;
}
case 'dialog': {
listenToNonDelegatedEvent('cancel', domElement);
listenToNonDelegatedEvent('close', domElement);
break;
}
case 'iframe':
case 'object': {
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load', domElement);
break;
}
case 'video':
case 'audio': {
// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for (let i = 0; i < mediaEventTypes.length; i++) {
listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
}
break;
}
case 'image': {
// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error', domElement);
listenToNonDelegatedEvent('load', domElement);
break;
}
case 'details': {
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle', domElement);
break;
}
case 'embed':
case 'source':
case 'img':
case 'link': {
// These are void elements that also need delegated events.
listenToNonDelegatedEvent('error', domElement);
listenToNonDelegatedEvent('load', domElement);
// We fallthrough to the return of the void elements
}
case 'area':
case 'base':
case 'br':
case 'col':
case 'hr':
case 'keygen':
case 'meta':
case 'param':
case 'track':
case 'wbr':
case 'menuitem': {
// Void elements
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const propValue = props[propKey];
if (propValue == null) {
continue;
}
switch (propKey) {
case 'children':
case 'dangerouslySetInnerHTML': {
// TODO: Can we make this a DEV warning to avoid this deny list?
throw new Error(
`${tag} is a void element tag and must neither have \`children\` nor ` +
'use `dangerouslySetInnerHTML`.',
);
}
// defaultChecked and defaultValue are ignored by setProp
default: {
setProp(domElement, tag, propKey, propValue, props, null);
}
}
}
return;
}
default: {
if (isCustomElement(tag, props)) {
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const propValue = props[propKey];
if (propValue == null) {
continue;
}
setPropOnCustomElement(
domElement,
tag,
propKey,
propValue,
props,
null,
);
}
return;
}
}
}
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const propValue = props[propKey];
if (propValue == null) {
continue;
}
setProp(domElement, tag, propKey, propValue, props, null);
}
}
export function updateProperties(
domElement: Element,
tag: string,
lastProps: Object,
nextProps: Object,
): void {
if (__DEV__) {
validatePropertiesInDevelopment(tag, nextProps);
}
switch (tag) {
case 'div':
case 'span':
case 'svg':
case 'path':
case 'a':
case 'g':
case 'p':
case 'li': {
// Fast track the most common tag types
break;
}
case 'input': {
let name = null;
let type = null;
let value = null;
let defaultValue = null;
let lastDefaultValue = null;
let checked = null;
let defaultChecked = null;
for (const propKey in lastProps) {
const lastProp = lastProps[propKey];
if (lastProps.hasOwnProperty(propKey) && lastProp != null) {
switch (propKey) {
case 'checked': {
break;
}
case 'value': {
// This is handled by updateWrapper below.
break;
}
case 'defaultValue': {
lastDefaultValue = lastProp;
}
// defaultChecked and defaultValue are ignored by setProp
// Fallthrough
default: {
if (!nextProps.hasOwnProperty(propKey))
setProp(domElement, tag, propKey, null, nextProps, lastProp);
}
}
}
}
for (const propKey in nextProps) {
const nextProp = nextProps[propKey];
const lastProp = lastProps[propKey];
if (
nextProps.hasOwnProperty(propKey) &&
(nextProp != null || lastProp != null)
) {
switch (propKey) {
case 'type': {
type = nextProp;
break;
}
case 'name': {
name = nextProp;
break;
}
case 'checked': {
checked = nextProp;
break;
}
case 'defaultChecked': {
defaultChecked = nextProp;
break;
}
case 'value': {
value = nextProp;
break;
}
case 'defaultValue': {
defaultValue = nextProp;
break;
}
case 'children':
case 'dangerouslySetInnerHTML': {
if (nextProp != null) {
throw new Error(
`${tag} is a void element tag and must neither have \`children\` nor ` +
'use `dangerouslySetInnerHTML`.',
);
}
break;
}
default: {
if (nextProp !== lastProp)
setProp(
domElement,
tag,
propKey,
nextProp,
nextProps,
lastProp,
);
}
}
}
}
if (__DEV__) {
const wasControlled =
lastProps.type === 'checkbox' || lastProps.type === 'radio'
? lastProps.checked != null
: lastProps.value != null;
const isControlled =
nextProps.type === 'checkbox' || nextProps.type === 'radio'
? nextProps.checked != null
: nextProps.value != null;
if (
!wasControlled &&
isControlled &&
!didWarnUncontrolledToControlled
) {
console.error(
'A component is changing an uncontrolled input to be controlled. ' +
'This is likely caused by the value changing from undefined to ' +
'a defined value, which should not happen. ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components',
);
didWarnUncontrolledToControlled = true;
}
if (
wasControlled &&
!isControlled &&
!didWarnControlledToUncontrolled
) {
console.error(
'A component is changing a controlled input to be uncontrolled. ' +
'This is likely caused by the value changing from a defined to ' +
'undefined, which should not happen. ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components',
);
didWarnControlledToUncontrolled = true;
}
}
// Update the wrapper around inputs *after* updating props. This has to
// happen after updating the rest of props. Otherwise HTML5 input validations
// raise warnings and prevent the new value from being assigned.
updateInput(
domElement,
value,
defaultValue,
lastDefaultValue,
checked,
defaultChecked,
type,
name,
);
return;
}
case 'select': {
let value = null;
let defaultValue = null;
let multiple = null;
let wasMultiple = null;
for (const propKey in lastProps) {
const lastProp = lastProps[propKey];
if (lastProps.hasOwnProperty(propKey) && lastProp != null) {
switch (propKey) {
case 'value': {
// This is handled by updateWrapper below.
break;
}
// defaultValue are ignored by setProp
case 'multiple': {
wasMultiple = lastProp;
// TODO: Move special case in here from setProp.
}
// Fallthrough
default: {
if (!nextProps.hasOwnProperty(propKey))
setProp(domElement, tag, propKey, null, nextProps, lastProp);
}
}
}
}
for (const propKey in nextProps) {
const nextProp = nextProps[propKey];
const lastProp = lastProps[propKey];
if (
nextProps.hasOwnProperty(propKey) &&
(nextProp != null || lastProp != null)
) {
switch (propKey) {
case 'value': {
value = nextProp;
// This is handled by updateSelect below.
break;
}
case 'defaultValue': {
defaultValue = nextProp;
break;
}
case 'multiple': {
multiple = nextProp;
// TODO: Just move the special case in here from setProp.
}
// Fallthrough
default: {
if (nextProp !== lastProp)
setProp(
domElement,
tag,
propKey,
nextProp,
nextProps,
lastProp,
);
}
}
}
}
// <select> value update needs to occur after <option> children
// reconciliation
updateSelect(domElement, value, defaultValue, multiple, wasMultiple);
return;
}
case 'textarea': {
let value = null;
let defaultValue = null;
for (const propKey in lastProps) {
const lastProp = lastProps[propKey];
if (
lastProps.hasOwnProperty(propKey) &&
lastProp != null &&
!nextProps.hasOwnProperty(propKey)
) {
switch (propKey) {
case 'value': {
// This is handled by updateTextarea below.
break;
}
case 'children': {
// TODO: This doesn't actually do anything if it updates.
break;
}
// defaultValue is ignored by setProp
default: {
setProp(domElement, tag, propKey, null, nextProps, lastProp);
}
}
}
}
for (const propKey in nextProps) {
const nextProp = nextProps[propKey];
const lastProp = lastProps[propKey];
if (
nextProps.hasOwnProperty(propKey) &&
(nextProp != null || lastProp != null)
) {
switch (propKey) {
case 'value': {
value = nextProp;
// This is handled by updateTextarea below.
break;
}
case 'defaultValue': {
defaultValue = nextProp;
break;
}
case 'children': {
// TODO: This doesn't actually do anything if it updates.
break;
}
case 'dangerouslySetInnerHTML': {
if (nextProp != null) {
// TODO: Do we really need a special error message for this. It's also pretty blunt.
throw new Error(
'`dangerouslySetInnerHTML` does not make sense on <textarea>.',
);
}
break;
}
default: {
if (nextProp !== lastProp)
setProp(
domElement,
tag,
propKey,
nextProp,
nextProps,
lastProp,
);
}
}
}
}
updateTextarea(domElement, value, defaultValue);
return;
}
case 'option': {
for (const propKey in lastProps) {
const lastProp = lastProps[propKey];
if (
lastProps.hasOwnProperty(propKey) &&
lastProp != null &&
!nextProps.hasOwnProperty(propKey)
) {
switch (propKey) {
case 'selected': {
// TODO: Remove support for selected on option.
(domElement: any).selected = false;
break;
}
default: {
setProp(domElement, tag, propKey, null, nextProps, lastProp);
}
}
}
}
for (const propKey in nextProps) {
const nextProp = nextProps[propKey];
const lastProp = lastProps[propKey];
if (
nextProps.hasOwnProperty(propKey) &&
nextProp !== lastProp &&
(nextProp != null || lastProp != null)
) {
switch (propKey) {
case 'selected': {
// TODO: Remove support for selected on option.
(domElement: any).selected =
nextProp &&
typeof nextProp !== 'function' &&
typeof nextProp !== 'symbol';
break;
}
default: {
setProp(domElement, tag, propKey, nextProp, nextProps, lastProp);
}
}
}
}
return;
}
case 'img':
case 'link':
case 'area':
case 'base':
case 'br':
case 'col':
case 'embed':
case 'hr':
case 'keygen':
case 'meta':
case 'param':
case 'source':
case 'track':
case 'wbr':
case 'menuitem': {
// Void elements
for (const propKey in lastProps) {
const lastProp = lastProps[propKey];
if (
lastProps.hasOwnProperty(propKey) &&
lastProp != null &&
!nextProps.hasOwnProperty(propKey)
) {
setProp(domElement, tag, propKey, null, nextProps, lastProp);
}
}
for (const propKey in nextProps) {
const nextProp = nextProps[propKey];
const lastProp = lastProps[propKey];
if (
nextProps.hasOwnProperty(propKey) &&
nextProp !== lastProp &&
(nextProp != null || lastProp != null)
) {
switch (propKey) {
case 'children':
case 'dangerouslySetInnerHTML': {
if (nextProp != null) {
// TODO: Can we make this a DEV warning to avoid this deny list?
throw new Error(
`${tag} is a void element tag and must neither have \`children\` nor ` +
'use `dangerouslySetInnerHTML`.',
);
}
break;
}
// defaultChecked and defaultValue are ignored by setProp
default: {
setProp(domElement, tag, propKey, nextProp, nextProps, lastProp);
}
}
}
}
return;
}
default: {
if (isCustomElement(tag, nextProps)) {
for (const propKey in lastProps) {
const lastProp = lastProps[propKey];
if (
lastProps.hasOwnProperty(propKey) &&
lastProp != null &&
!nextProps.hasOwnProperty(propKey)
) {
setPropOnCustomElement(
domElement,
tag,
propKey,
null,
nextProps,
lastProp,
);
}
}
for (const propKey in nextProps) {
const nextProp = nextProps[propKey];
const lastProp = lastProps[propKey];
if (
nextProps.hasOwnProperty(propKey) &&
nextProp !== lastProp &&
(nextProp != null || lastProp != null)
) {
setPropOnCustomElement(
domElement,
tag,
propKey,
nextProp,
nextProps,
lastProp,
);
}
}
return;
}
}
}
for (const propKey in lastProps) {
const lastProp = lastProps[propKey];
if (
lastProps.hasOwnProperty(propKey) &&
lastProp != null &&
!nextProps.hasOwnProperty(propKey)
) {
setProp(domElement, tag, propKey, null, nextProps, lastProp);
}
}
for (const propKey in nextProps) {
const nextProp = nextProps[propKey];
const lastProp = lastProps[propKey];
if (
nextProps.hasOwnProperty(propKey) &&
nextProp !== lastProp &&
(nextProp != null || lastProp != null)
) {
setProp(domElement, tag, propKey, nextProp, nextProps, lastProp);
}
}
}
function getPossibleStandardName(propName: string): string | null {
if (__DEV__) {
const lowerCasedName = propName.toLowerCase();
if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
return null;
}
return possibleStandardNames[lowerCasedName] || null;
}
return null;
}
function diffHydratedStyles(domElement: Element, value: mixed) {
if (value != null && typeof value !== 'object') {
throw new Error(
'The `style` prop expects a mapping from style properties to values, ' +
"not a string. For example, style={{marginRight: spacing + 'em'}} when " +
'using JSX.',
);
}
if (canDiffStyleForHydrationWarning) {
const expectedStyle = createDangerousStringForStyles(value);
const serverValue = domElement.getAttribute('style');
warnForPropDifference('style', serverValue, expectedStyle);
}
}
function hydrateAttribute(
domElement: Element,
propKey: string,
attributeName: string,
value: any,
extraAttributes: Set<string>,
): void {
extraAttributes.delete(attributeName);
const serverValue = domElement.getAttribute(attributeName);
if (serverValue === null) {
switch (typeof value) {
case 'undefined':
case 'function':
case 'symbol':
case 'boolean':
return;
}
} else {
if (value == null) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
} else {
switch (typeof value) {
case 'function':
case 'symbol':
case 'boolean':
break;
default: {
if (__DEV__) {
checkAttributeStringCoercion(value, propKey);
}
if (serverValue === '' + value) {
return;
}
}
}
}
}
warnForPropDifference(propKey, serverValue, value);
}
function hydrateBooleanAttribute(
domElement: Element,
propKey: string,
attributeName: string,
value: any,
extraAttributes: Set<string>,
): void {
extraAttributes.delete(attributeName);
const serverValue = domElement.getAttribute(attributeName);
if (serverValue === null) {
switch (typeof value) {
case 'function':
case 'symbol':
return;
}
if (!value) {
return;
}
} else {
switch (typeof value) {
case 'function':
case 'symbol':
break;
default: {
if (value) {
// If this was a boolean, it doesn't matter what the value is
// the fact that we have it is the same as the expected.
// As long as it's positive.
return;
}
}
}
}
warnForPropDifference(propKey, serverValue, value);
}
function hydrateOverloadedBooleanAttribute(
domElement: Element,
propKey: string,
attributeName: string,
value: any,
extraAttributes: Set<string>,
): void {
extraAttributes.delete(attributeName);
const serverValue = domElement.getAttribute(attributeName);
if (serverValue === null) {
switch (typeof value) {
case 'undefined':
case 'function':
case 'symbol':
return;
default:
if (value === false) {
return;
}
}
} else {
if (value == null) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
} else {
switch (typeof value) {
case 'function':
case 'symbol':
break;
case 'boolean':
if (value === true && serverValue === '') {
return;
}
break;
default: {
if (__DEV__) {
checkAttributeStringCoercion(value, propKey);
}
if (serverValue === '' + value) {
return;
}
}
}
}
}
warnForPropDifference(propKey, serverValue, value);
}
function hydrateBooleanishAttribute(
domElement: Element,
propKey: string,
attributeName: string,
value: any,
extraAttributes: Set<string>,
): void {
extraAttributes.delete(attributeName);
const serverValue = domElement.getAttribute(attributeName);
if (serverValue === null) {
switch (typeof value) {
case 'undefined':
case 'function':
case 'symbol':
return;
}
} else {
if (value == null) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
} else {
switch (typeof value) {
case 'function':
case 'symbol':
break;
default: {
if (__DEV__) {
checkAttributeStringCoercion(value, attributeName);
}
if (serverValue === '' + (value: any)) {
return;
}
}
}
}
}
warnForPropDifference(propKey, serverValue, value);
}
function hydrateNumericAttribute(
domElement: Element,
propKey: string,
attributeName: string,
value: any,
extraAttributes: Set<string>,
): void {
extraAttributes.delete(attributeName);
const serverValue = domElement.getAttribute(attributeName);
if (serverValue === null) {
switch (typeof value) {
case 'undefined':
case 'function':
case 'symbol':
case 'boolean':
return;
default:
if (isNaN(value)) {
return;
}
}
} else {
if (value == null) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
} else {
switch (typeof value) {
case 'function':
case 'symbol':
case 'boolean':
break;
default: {
if (isNaN(value)) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
break;
}
if (__DEV__) {
checkAttributeStringCoercion(value, propKey);
}
if (serverValue === '' + value) {
return;
}
}
}
}
}
warnForPropDifference(propKey, serverValue, value);
}
function hydratePositiveNumericAttribute(
domElement: Element,
propKey: string,
attributeName: string,
value: any,
extraAttributes: Set<string>,
): void {
extraAttributes.delete(attributeName);
const serverValue = domElement.getAttribute(attributeName);
if (serverValue === null) {
switch (typeof value) {
case 'undefined':
case 'function':
case 'symbol':
case 'boolean':
return;
default:
if (isNaN(value) || value < 1) {
return;
}
}
} else {
if (value == null) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
} else {
switch (typeof value) {
case 'function':
case 'symbol':
case 'boolean':
break;
default: {
if (isNaN(value) || value < 1) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
break;
}
if (__DEV__) {
checkAttributeStringCoercion(value, propKey);
}
if (serverValue === '' + value) {
return;
}
}
}
}
}
warnForPropDifference(propKey, serverValue, value);
}
function hydrateSanitizedAttribute(
domElement: Element,
propKey: string,
attributeName: string,
value: any,
extraAttributes: Set<string>,
): void {
extraAttributes.delete(attributeName);
const serverValue = domElement.getAttribute(attributeName);
if (serverValue === null) {
switch (typeof value) {
case 'undefined':
case 'function':
case 'symbol':
case 'boolean':
return;
}
} else {
if (value == null) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
} else {
switch (typeof value) {
case 'function':
case 'symbol':
case 'boolean':
break;
default: {
if (__DEV__) {
checkAttributeStringCoercion(value, propKey);
}
const sanitizedValue = sanitizeURL('' + value);
if (serverValue === sanitizedValue) {
return;
}
}
}
}
}
warnForPropDifference(propKey, serverValue, value);
}
function diffHydratedCustomComponent(
domElement: Element,
tag: string,
props: Object,
hostContext: HostContext,
extraAttributes: Set<string>,
) {
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const value = props[propKey];
if (value == null) {
continue;
}
if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (typeof value !== 'function') {
warnForInvalidEventListener(propKey, value);
}
continue;
}
if (props.suppressHydrationWarning === true) {
// Don't bother comparing. We're ignoring all these warnings.
continue;
}
// Validate that the properties correspond to their expected values.
switch (propKey) {
case 'children': // Checked above already
case 'suppressContentEditableWarning':
case 'suppressHydrationWarning':
case 'defaultValue':
case 'defaultChecked':
case 'innerHTML':
// Noop
continue;
case 'dangerouslySetInnerHTML':
const serverHTML = domElement.innerHTML;
const nextHtml = value ? value.__html : undefined;
if (nextHtml != null) {
const expectedHTML = normalizeHTML(domElement, nextHtml);
warnForPropDifference(propKey, serverHTML, expectedHTML);
}
continue;
case 'style':
extraAttributes.delete(propKey);
diffHydratedStyles(domElement, value);
continue;
case 'offsetParent':
case 'offsetTop':
case 'offsetLeft':
case 'offsetWidth':
case 'offsetHeight':
case 'isContentEditable':
case 'outerText':
case 'outerHTML':
if (enableCustomElementPropertySupport) {
extraAttributes.delete(propKey.toLowerCase());
if (__DEV__) {
console.error(
'Assignment to read-only property will result in a no-op: `%s`',
propKey,
);
}
continue;
}
// Fall through
case 'className':
if (enableCustomElementPropertySupport) {
// className is a special cased property on the server to render as an attribute.
extraAttributes.delete('class');
const serverValue = getValueForAttributeOnCustomComponent(
domElement,
'class',
value,
);
warnForPropDifference('className', serverValue, value);
continue;
}
// Fall through
default: {
// This is a DEV-only path
const hostContextDev: HostContextDev = (hostContext: any);
const hostContextProd = hostContextDev.context;
if (
hostContextProd === HostContextNamespaceNone &&
tag !== 'svg' &&
tag !== 'math'
) {
extraAttributes.delete(propKey.toLowerCase());
} else {
extraAttributes.delete(propKey);
}
const serverValue = getValueForAttributeOnCustomComponent(
domElement,
propKey,
value,
);
warnForPropDifference(propKey, serverValue, value);
}
}
}
}
// This is the exact URL string we expect that Fizz renders if we provide a function action.
// We use this for hydration warnings. It needs to be in sync with Fizz. Maybe makes sense
// as a shared module for that reason.
const EXPECTED_FORM_ACTION_URL =
// eslint-disable-next-line no-script-url
"javascript:throw new Error('A React form was unexpectedly submitted.')";
function diffHydratedGenericElement(
domElement: Element,
tag: string,
props: Object,
hostContext: HostContext,
extraAttributes: Set<string>,
) {
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
const value = props[propKey];
if (value == null) {
continue;
}
if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (typeof value !== 'function') {
warnForInvalidEventListener(propKey, value);
}
continue;
}
if (props.suppressHydrationWarning === true) {
// Don't bother comparing. We're ignoring all these warnings.
continue;
}
// Validate that the properties correspond to their expected values.
switch (propKey) {
case 'children': // Checked above already
case 'suppressContentEditableWarning':
case 'suppressHydrationWarning':
case 'value': // Controlled attributes are not validated
case 'checked': // TODO: Only ignore them on controlled tags.
case 'selected':
case 'defaultValue':
case 'defaultChecked':
case 'innerHTML':
// Noop
continue;
case 'dangerouslySetInnerHTML':
const serverHTML = domElement.innerHTML;
const nextHtml = value ? value.__html : undefined;
if (nextHtml != null) {
const expectedHTML = normalizeHTML(domElement, nextHtml);
warnForPropDifference(propKey, serverHTML, expectedHTML);
}
continue;
case 'className':
hydrateAttribute(domElement, propKey, 'class', value, extraAttributes);
continue;
case 'tabIndex':
hydrateAttribute(
domElement,
propKey,
'tabindex',
value,
extraAttributes,
);
continue;
case 'style':
extraAttributes.delete(propKey);
diffHydratedStyles(domElement, value);
continue;
case 'multiple': {
extraAttributes.delete(propKey);
const serverValue = (domElement: any).multiple;
warnForPropDifference(propKey, serverValue, value);
continue;
}
case 'muted': {
extraAttributes.delete(propKey);
const serverValue = (domElement: any).muted;
warnForPropDifference(propKey, serverValue, value);
continue;
}
case 'autoFocus': {
extraAttributes.delete('autofocus');
const serverValue = (domElement: any).autofocus;
warnForPropDifference(propKey, serverValue, value);
continue;
}
case 'src':
case 'href':
if (enableFilterEmptyStringAttributesDOM) {
if (value === '') {
if (__DEV__) {
if (propKey === 'src') {
console.error(
'An empty string ("") was passed to the %s attribute. ' +
'This may cause the browser to download the whole page again over the network. ' +
'To fix this, either do not render the element at all ' +
'or pass null to %s instead of an empty string.',
propKey,
propKey,
);
} else {
console.error(
'An empty string ("") was passed to the %s attribute. ' +
'To fix this, either do not render the element at all ' +
'or pass null to %s instead of an empty string.',
propKey,
propKey,
);
}
}
hydrateSanitizedAttribute(
domElement,
propKey,
propKey,
null,
extraAttributes,
);
continue;
}
}
hydrateSanitizedAttribute(
domElement,
propKey,
propKey,
value,
extraAttributes,
);
continue;
case 'action':
case 'formAction':
if (enableFormActions) {
const serverValue = domElement.getAttribute(propKey);
if (typeof value === 'function') {
extraAttributes.delete(propKey.toLowerCase());
// The server can set these extra properties to implement actions.
// So we remove them from the extra attributes warnings.
if (propKey === 'formAction') {
extraAttributes.delete('name');
extraAttributes.delete('formenctype');
extraAttributes.delete('formmethod');
extraAttributes.delete('formtarget');
} else {
extraAttributes.delete('enctype');
extraAttributes.delete('method');
extraAttributes.delete('target');
}
// Ideally we should be able to warn if the server value was not a function
// however since the function can return any of these attributes any way it
// wants as a custom progressive enhancement, there's nothing to compare to.
// We can check if the function has the $FORM_ACTION property on the client
// and if it's not, warn, but that's an unnecessary constraint that they
// have to have the extra extension that doesn't do anything on the client.
continue;
} else if (serverValue === EXPECTED_FORM_ACTION_URL) {
extraAttributes.delete(propKey.toLowerCase());
warnForPropDifference(propKey, 'function', value);
continue;
}
}
hydrateSanitizedAttribute(
domElement,
propKey,
propKey.toLowerCase(),
value,
extraAttributes,
);
continue;
case 'xlinkHref':
hydrateSanitizedAttribute(
domElement,
propKey,
'xlink:href',
value,
extraAttributes,
);
continue;
case 'contentEditable': {
// Lower-case Booleanish String
hydrateBooleanishAttribute(
domElement,
propKey,
'contenteditable',
value,
extraAttributes,
);
continue;
}
case 'spellCheck': {
// Lower-case Booleanish String
hydrateBooleanishAttribute(
domElement,
propKey,
'spellcheck',
value,
extraAttributes,
);
continue;
}
case 'draggable':
case 'autoReverse':
case 'externalResourcesRequired':
case 'focusable':
case 'preserveAlpha': {
// Case-sensitive Booleanish String
hydrateBooleanishAttribute(
domElement,
propKey,
propKey,
value,
extraAttributes,
);
continue;
}
case 'allowFullScreen':
case 'async':
case 'autoPlay':
case 'controls':
case 'default':
case 'defer':
case 'disabled':
case 'disablePictureInPicture':
case 'disableRemotePlayback':
case 'formNoValidate':
case 'hidden':
case 'loop':
case 'noModule':
case 'noValidate':
case 'open':
case 'playsInline':
case 'readOnly':
case 'required':
case 'reversed':
case 'scoped':
case 'seamless':
case 'itemScope': {
// Some of these need to be lower case to remove them from the extraAttributes list.
hydrateBooleanAttribute(
domElement,
propKey,
propKey.toLowerCase(),
value,
extraAttributes,
);
continue;
}
case 'capture':
case 'download': {
hydrateOverloadedBooleanAttribute(
domElement,
propKey,
propKey,
value,
extraAttributes,
);
continue;
}
case 'cols':
case 'rows':
case 'size':
case 'span': {
hydratePositiveNumericAttribute(
domElement,
propKey,
propKey,
value,
extraAttributes,
);
continue;
}
case 'rowSpan': {
hydrateNumericAttribute(
domElement,
propKey,
'rowspan',
value,
extraAttributes,
);
continue;
}
case 'start': {
hydrateNumericAttribute(
domElement,
propKey,
propKey,
value,
extraAttributes,
);
continue;
}
case 'xHeight':
hydrateAttribute(
domElement,
propKey,
'x-height',
value,
extraAttributes,
);
continue;
case 'xlinkActuate':
hydrateAttribute(
domElement,
propKey,
'xlink:actuate',
value,
extraAttributes,
);
continue;
case 'xlinkArcrole':
hydrateAttribute(
domElement,
propKey,
'xlink:arcrole',
value,
extraAttributes,
);
continue;
case 'xlinkRole':
hydrateAttribute(
domElement,
propKey,
'xlink:role',
value,
extraAttributes,
);
continue;
case 'xlinkShow':
hydrateAttribute(
domElement,
propKey,
'xlink:show',
value,
extraAttributes,
);
continue;
case 'xlinkTitle':
hydrateAttribute(
domElement,
propKey,
'xlink:title',
value,
extraAttributes,
);
continue;
case 'xlinkType':
hydrateAttribute(
domElement,
propKey,
'xlink:type',
value,
extraAttributes,
);
continue;
case 'xmlBase':
hydrateAttribute(
domElement,
propKey,
'xml:base',
value,
extraAttributes,
);
continue;
case 'xmlLang':
hydrateAttribute(
domElement,
propKey,
'xml:lang',
value,
extraAttributes,
);
continue;
case 'xmlSpace':
hydrateAttribute(
domElement,
propKey,
'xml:space',
value,
extraAttributes,
);
continue;
default: {
if (
// shouldIgnoreAttribute
// We have already filtered out null/undefined and reserved words.
propKey.length > 2 &&
(propKey[0] === 'o' || propKey[0] === 'O') &&
(propKey[1] === 'n' || propKey[1] === 'N')
) {
continue;
}
const attributeName = getAttributeAlias(propKey);
let isMismatchDueToBadCasing = false;
// This is a DEV-only path
const hostContextDev: HostContextDev = (hostContext: any);
const hostContextProd = hostContextDev.context;
if (
hostContextProd === HostContextNamespaceNone &&
tag !== 'svg' &&
tag !== 'math'
) {
extraAttributes.delete(attributeName.toLowerCase());
} else {
const standardName = getPossibleStandardName(propKey);
if (standardName !== null && standardName !== propKey) {
// If an SVG prop is supplied with bad casing, it will
// be successfully parsed from HTML, but will produce a mismatch
// (and would be incorrectly rendered on the client).
// However, we already warn about bad casing elsewhere.
// So we'll skip the misleading extra mismatch warning in this case.
isMismatchDueToBadCasing = true;
extraAttributes.delete(standardName);
}
extraAttributes.delete(attributeName);
}
const serverValue = getValueForAttribute(
domElement,
attributeName,
value,
);
if (!isMismatchDueToBadCasing) {
warnForPropDifference(propKey, serverValue, value);
}
}
}
}
}
export function diffHydratedProperties(
domElement: Element,
tag: string,
props: Object,
isConcurrentMode: boolean,
shouldWarnDev: boolean,
hostContext: HostContext,
): void {
if (__DEV__) {
validatePropertiesInDevelopment(tag, props);
}
// TODO: Make sure that we check isMounted before firing any of these events.
switch (tag) {
case 'dialog':
listenToNonDelegatedEvent('cancel', domElement);
listenToNonDelegatedEvent('close', domElement);
break;
case 'iframe':
case 'object':
case 'embed':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load', domElement);
break;
case 'video':
case 'audio':
// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for (let i = 0; i < mediaEventTypes.length; i++) {
listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
}
break;
case 'source':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the error event.
listenToNonDelegatedEvent('error', domElement);
break;
case 'img':
case 'image':
case 'link':
// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error', domElement);
listenToNonDelegatedEvent('load', domElement);
break;
case 'details':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle', domElement);
break;
case 'input':
if (__DEV__) {
checkControlledValueProps('input', props);
}
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
validateInputProps(domElement, props);
// For input and textarea we current always set the value property at
// post mount to force it to diverge from attributes. However, for
// option and select we don't quite do the same thing and select
// is not resilient to the DOM state changing so we don't do that here.
// TODO: Consider not doing this for input and textarea.
initInput(
domElement,
props.value,
props.defaultValue,
props.checked,
props.defaultChecked,
props.type,
props.name,
true,
);
track((domElement: any));
break;
case 'option':
validateOptionProps(domElement, props);
break;
case 'select':
if (__DEV__) {
checkControlledValueProps('select', props);
}
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
validateSelectProps(domElement, props);
break;
case 'textarea':
if (__DEV__) {
checkControlledValueProps('textarea', props);
}
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
validateTextareaProps(domElement, props);
initTextarea(domElement, props.value, props.defaultValue, props.children);
track((domElement: any));
break;
}
const children = props.children;
// For text content children we compare against textContent. This
// might match additional HTML that is hidden when we read it using
// textContent. E.g. "foo" will match "f<span>oo</span>" but that still
// satisfies our requirement. Our requirement is not to produce perfect
// HTML and attributes. Ideally we should preserve structure but it's
// ok not to if the visible content is still enough to indicate what
// even listeners these nodes might be wired up to.
// TODO: Warn if there is more than a single textNode as a child.
// TODO: Should we use domElement.firstChild.nodeValue to compare?
if (typeof children === 'string' || typeof children === 'number') {
if (domElement.textContent !== '' + children) {
if (props.suppressHydrationWarning !== true) {
checkForUnmatchedText(
domElement.textContent,
children,
isConcurrentMode,
shouldWarnDev,
);
}
if (!isConcurrentMode || !enableClientRenderFallbackOnTextMismatch) {
// We really should be patching this in the commit phase but since
// this only affects legacy mode hydration which is deprecated anyway
// we can get away with it.
// Host singletons get their children appended and don't use the text
// content mechanism.
if (tag !== 'body') {
domElement.textContent = (children: any);
}
}
}
}
if (props.onScroll != null) {
listenToNonDelegatedEvent('scroll', domElement);
}
if (props.onScrollEnd != null) {
listenToNonDelegatedEvent('scrollend', domElement);
}
if (props.onClick != null) {
// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
}
if (__DEV__ && shouldWarnDev) {
const extraAttributes: Set<string> = new Set();
const attributes = domElement.attributes;
for (let i = 0; i < attributes.length; i++) {
const name = attributes[i].name.toLowerCase();
switch (name) {
// Controlled attributes are not validated
// TODO: Only ignore them on controlled tags.
case 'value':
break;
case 'checked':
break;
case 'selected':
break;
default:
// Intentionally use the original name.
// See discussion in https://github.com/facebook/react/pull/10676.
extraAttributes.add(attributes[i].name);
}
}
if (isCustomElement(tag, props)) {
diffHydratedCustomComponent(
domElement,
tag,
props,
hostContext,
extraAttributes,
);
} else {
diffHydratedGenericElement(
domElement,
tag,
props,
hostContext,
extraAttributes,
);
}
if (extraAttributes.size > 0 && props.suppressHydrationWarning !== true) {
warnForExtraAttributes(extraAttributes);
}
}
}
export function diffHydratedText(
textNode: Text,
text: string,
isConcurrentMode: boolean,
): boolean {
const isDifferent = textNode.nodeValue !== text;
return isDifferent;
}
export function warnForDeletedHydratableElement(
parentNode: Element | Document | DocumentFragment,
child: Element,
) {
if (__DEV__) {
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
console.error(
'Did not expect server HTML to contain a <%s> in <%s>.',
child.nodeName.toLowerCase(),
parentNode.nodeName.toLowerCase(),
);
}
}
export function warnForDeletedHydratableText(
parentNode: Element | Document | DocumentFragment,
child: Text,
) {
if (__DEV__) {
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
console.error(
'Did not expect server HTML to contain the text node "%s" in <%s>.',
child.nodeValue,
parentNode.nodeName.toLowerCase(),
);
}
}
export function warnForInsertedHydratedElement(
parentNode: Element | Document | DocumentFragment,
tag: string,
props: Object,
) {
if (__DEV__) {
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
console.error(
'Expected server HTML to contain a matching <%s> in <%s>.',
tag,
parentNode.nodeName.toLowerCase(),
);
}
}
export function warnForInsertedHydratedText(
parentNode: Element | Document | DocumentFragment,
text: string,
) {
if (__DEV__) {
if (text === '') {
// We expect to insert empty text nodes since they're not represented in
// the HTML.
// TODO: Remove this special case if we can just avoid inserting empty
// text nodes.
return;
}
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
console.error(
'Expected server HTML to contain a matching text node for "%s" in <%s>.',
text,
parentNode.nodeName.toLowerCase(),
);
}
}
export function restoreControlledState(
domElement: Element,
tag: string,
props: Object,
): void {
switch (tag) {
case 'input':
restoreControlledInputState(domElement, props);
return;
case 'textarea':
restoreControlledTextareaState(domElement, props);
return;
case 'select':
restoreControlledSelectState(domElement, props);
return;
}
}
| 28.968206 | 117 | 0.56188 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
describe('ReactDOMTestSelectors', () => {
let React;
let act;
let createComponentSelector;
let createHasPseudoClassSelector;
let createRoleSelector;
let createTextSelector;
let createTestNameSelector;
let findAllNodes;
let findBoundingRects;
let focusWithin;
let getFindAllNodesFailureDescription;
let observeVisibleRects;
let render;
let container;
beforeEach(() => {
jest.resetModules();
React = require('react');
act = React.unstable_act;
if (__EXPERIMENTAL__ || global.__WWW__) {
const ReactDOM = require('react-dom/unstable_testing');
createComponentSelector = ReactDOM.createComponentSelector;
createHasPseudoClassSelector = ReactDOM.createHasPseudoClassSelector;
createRoleSelector = ReactDOM.createRoleSelector;
createTextSelector = ReactDOM.createTextSelector;
createTestNameSelector = ReactDOM.createTestNameSelector;
findAllNodes = ReactDOM.findAllNodes;
findBoundingRects = ReactDOM.findBoundingRects;
focusWithin = ReactDOM.focusWithin;
getFindAllNodesFailureDescription =
ReactDOM.getFindAllNodesFailureDescription;
observeVisibleRects = ReactDOM.observeVisibleRects;
render = ReactDOM.render;
}
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
});
describe('findAllNodes', () => {
// @gate www || experimental
it('should support searching from the document root', () => {
function Example() {
return (
<div>
<div data-testname="match" id="match" />
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match');
});
// @gate www || experimental
it('should support searching from the container', () => {
function Example() {
return (
<div>
<div data-testname="match" id="match" />
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(container, [
createComponentSelector(Example),
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match');
});
// @gate www || experimental
it('should support searching from a previous match if the match had a data-testname', () => {
function Outer() {
return (
<div data-testname="outer" id="outer">
<Inner />
</div>
);
}
function Inner() {
return <div data-testname="inner" id="inner" />;
}
render(<Outer />, container);
let matches = findAllNodes(container, [
createComponentSelector(Outer),
createTestNameSelector('outer'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('outer');
matches = findAllNodes(matches[0], [
createComponentSelector(Inner),
createTestNameSelector('inner'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('inner');
});
// @gate www || experimental
it('should not support searching from a previous match if the match did not have a data-testname', () => {
function Outer() {
return (
<div id="outer">
<Inner />
</div>
);
}
function Inner() {
return <div id="inner" />;
}
render(<Outer />, container);
const matches = findAllNodes(container, [createComponentSelector(Outer)]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('outer');
expect(() => {
findAllNodes(matches[0], [
createComponentSelector(Inner),
createTestNameSelector('inner'),
]);
}).toThrow(
'Invalid host root specified. Should be either a React container or a node with a testname attribute.',
);
});
// @gate www || experimental
it('should support an multiple component types in the selector array', () => {
function Outer() {
return (
<>
<div data-testname="match" id="match1" />
<Middle />
</>
);
}
function Middle() {
return (
<>
<div data-testname="match" id="match2" />
<Inner />
</>
);
}
function Inner() {
return (
<>
<div data-testname="match" id="match3" />
</>
);
}
render(<Outer />, container);
let matches = findAllNodes(document.body, [
createComponentSelector(Outer),
createComponentSelector(Middle),
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(2);
expect(matches.map(m => m.id).sort()).toEqual(['match2', 'match3']);
matches = findAllNodes(document.body, [
createComponentSelector(Outer),
createComponentSelector(Middle),
createComponentSelector(Inner),
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match3');
matches = findAllNodes(document.body, [
createComponentSelector(Outer),
createComponentSelector(Inner),
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match3');
});
// @gate www || experimental
it('should find multiple matches', () => {
function Example1() {
return (
<div>
<div data-testname="match" id="match1" />
</div>
);
}
function Example2() {
return (
<div>
<div data-testname="match" id="match2" />
<div data-testname="match" id="match3" />
</div>
);
}
render(
<>
<Example1 />
<Example2 />
</>,
container,
);
const matches = findAllNodes(document.body, [
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(3);
expect(matches.map(m => m.id).sort()).toEqual([
'match1',
'match2',
'match3',
]);
});
// @gate www || experimental
it('should ignore nested matches', () => {
function Example() {
return (
<div data-testname="match" id="match1">
<div data-testname="match" id="match2" />
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toEqual('match1');
});
// @gate www || experimental
it('should enforce the specific order of selectors', () => {
function Outer() {
return (
<>
<div data-testname="match" id="match1" />
<Inner />
</>
);
}
function Inner() {
return <div data-testname="match" id="match1" />;
}
render(<Outer />, container);
expect(
findAllNodes(document.body, [
createComponentSelector(Inner),
createComponentSelector(Outer),
createTestNameSelector('match'),
]),
).toHaveLength(0);
});
// @gate www || experimental
it('should not search within hidden subtrees', () => {
const ref1 = React.createRef(null);
const ref2 = React.createRef(null);
function Outer() {
return (
<>
<div hidden={true}>
<div ref={ref1} data-testname="match" />
</div>
<Inner />
</>
);
}
function Inner() {
return <div ref={ref2} data-testname="match" />;
}
render(<Outer />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Outer),
createTestNameSelector('match'),
]);
expect(matches).toHaveLength(1);
expect(matches[0]).toBe(ref2.current);
});
// @gate www || experimental
it('should support filtering by display text', () => {
function Example() {
return (
<div>
<div>foo</div>
<div>
<div id="match">bar</div>
</div>
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createTextSelector('bar'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match');
});
// @gate www || experimental
it('should support filtering by explicit accessibiliy role', () => {
function Example() {
return (
<div>
<div>foo</div>
<div>
<div role="button" id="match">
bar
</div>
</div>
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createRoleSelector('button'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match');
});
// @gate www || experimental
it('should support filtering by explicit secondary accessibiliy role', () => {
const ref = React.createRef();
function Example() {
return (
<div>
<div>foo</div>
<div>
<div ref={ref} role="meter progressbar" />
</div>
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createRoleSelector('progressbar'),
]);
expect(matches).toHaveLength(1);
expect(matches[0]).toBe(ref.current);
});
// @gate www || experimental
it('should support filtering by implicit accessibiliy role', () => {
function Example() {
return (
<div>
<div>foo</div>
<div>
<button id="match">bar</button>
</div>
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createRoleSelector('button'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match');
});
// @gate www || experimental
it('should support filtering by implicit accessibiliy role with attributes qualifications', () => {
function Example() {
return (
<div>
<div>foo</div>
<div>
<input type="checkbox" id="match" value="bar" />
</div>
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createRoleSelector('checkbox'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match');
});
// @gate www || experimental
it('should support searching ahead with the has() selector', () => {
function Example() {
return (
<div>
<article>
<h1>Should match</h1>
<p>
<button id="match">Like</button>
</p>
</article>
<article>
<h1>Should not match</h1>
<p>
<button>Like</button>
</p>
</article>
</div>
);
}
render(<Example />, container);
const matches = findAllNodes(document.body, [
createComponentSelector(Example),
createRoleSelector('article'),
createHasPseudoClassSelector([
createRoleSelector('heading'),
createTextSelector('Should match'),
]),
createRoleSelector('button'),
]);
expect(matches).toHaveLength(1);
expect(matches[0].id).toBe('match');
});
// @gate www || experimental
it('should throw if no container can be found', () => {
expect(() => findAllNodes(document.body, [])).toThrow(
'Could not find React container within specified host subtree.',
);
});
// @gate www || experimental
it('should throw if an invalid host root is specified', () => {
const ref = React.createRef();
function Example() {
return <div ref={ref} />;
}
render(<Example />, container);
expect(() => findAllNodes(ref.current, [])).toThrow(
'Invalid host root specified. Should be either a React container or a node with a testname attribute.',
);
});
});
describe('getFindAllNodesFailureDescription', () => {
// @gate www || experimental
it('should describe findAllNodes failures caused by the component type selector', () => {
function Outer() {
return <Middle />;
}
function Middle() {
return <div />;
}
function NotRendered() {
return <div data-testname="match" />;
}
render(<Outer />, container);
const description = getFindAllNodesFailureDescription(document.body, [
createComponentSelector(Outer),
createComponentSelector(Middle),
createComponentSelector(NotRendered),
createTestNameSelector('match'),
]);
expect(description).toEqual(
`findAllNodes was able to match part of the selector:
<Outer> > <Middle>
No matching component was found for:
<NotRendered> > [data-testname="match"]`,
);
});
// @gate www || experimental
it('should return null if findAllNodes was able to find a match', () => {
function Example() {
return (
<div>
<div data-testname="match" id="match" />
</div>
);
}
render(<Example />, container);
const description = getFindAllNodesFailureDescription(document.body, [
createComponentSelector(Example),
]);
expect(description).toBe(null);
});
});
describe('findBoundingRects', () => {
// Stub out getBoundingClientRect for the specified target.
// This API is required by the test selectors but it isn't implemented by jsdom.
function setBoundingClientRect(target, {x, y, width, height}) {
target.getBoundingClientRect = function () {
return {
width,
height,
left: x,
right: x + width,
top: y,
bottom: y + height,
};
};
}
// @gate www || experimental
it('should return a single rect for a component that returns a single root host element', () => {
const ref = React.createRef();
function Example() {
return (
<div ref={ref}>
<div />
<div />
</div>
);
}
render(<Example />, container);
setBoundingClientRect(ref.current, {
x: 10,
y: 20,
width: 200,
height: 100,
});
const rects = findBoundingRects(document.body, [
createComponentSelector(Example),
]);
expect(rects).toHaveLength(1);
expect(rects).toContainEqual({
x: 10,
y: 20,
width: 200,
height: 100,
});
});
// @gate www || experimental
it('should return a multiple rects for multiple matches', () => {
const outerRef = React.createRef();
const innerRef = React.createRef();
function Outer() {
return (
<>
<div ref={outerRef} />
<Inner />
</>
);
}
function Inner() {
return <div ref={innerRef} />;
}
render(<Outer />, container);
setBoundingClientRect(outerRef.current, {
x: 10,
y: 20,
width: 200,
height: 100,
});
setBoundingClientRect(innerRef.current, {
x: 110,
y: 120,
width: 250,
height: 150,
});
const rects = findBoundingRects(document.body, [
createComponentSelector(Outer),
]);
expect(rects).toHaveLength(2);
expect(rects).toContainEqual({
x: 10,
y: 20,
width: 200,
height: 100,
});
expect(rects).toContainEqual({
x: 110,
y: 120,
width: 250,
height: 150,
});
});
// @gate www || experimental
it('should return a multiple rects for single match that returns a fragment', () => {
const refA = React.createRef();
const refB = React.createRef();
function Example() {
return (
<>
<div ref={refA}>
<div />
<div />
</div>
<div ref={refB} />
</>
);
}
render(<Example />, container);
setBoundingClientRect(refA.current, {
x: 10,
y: 20,
width: 200,
height: 100,
});
setBoundingClientRect(refB.current, {
x: 110,
y: 120,
width: 250,
height: 150,
});
const rects = findBoundingRects(document.body, [
createComponentSelector(Example),
]);
expect(rects).toHaveLength(2);
expect(rects).toContainEqual({
x: 10,
y: 20,
width: 200,
height: 100,
});
expect(rects).toContainEqual({
x: 110,
y: 120,
width: 250,
height: 150,
});
});
// @gate www || experimental
it('should merge overlapping rects', () => {
const refA = React.createRef();
const refB = React.createRef();
const refC = React.createRef();
function Example() {
return (
<>
<div ref={refA} />
<div ref={refB} />
<div ref={refC} />
</>
);
}
render(<Example />, container);
setBoundingClientRect(refA.current, {
x: 10,
y: 10,
width: 50,
height: 25,
});
setBoundingClientRect(refB.current, {
x: 10,
y: 10,
width: 20,
height: 10,
});
setBoundingClientRect(refC.current, {
x: 100,
y: 10,
width: 50,
height: 25,
});
const rects = findBoundingRects(document.body, [
createComponentSelector(Example),
]);
expect(rects).toHaveLength(2);
expect(rects).toContainEqual({
x: 10,
y: 10,
width: 50,
height: 25,
});
expect(rects).toContainEqual({
x: 100,
y: 10,
width: 50,
height: 25,
});
});
// @gate www || experimental
it('should merge some types of adjacent rects (if they are the same in one dimension)', () => {
const refA = React.createRef();
const refB = React.createRef();
const refC = React.createRef();
const refD = React.createRef();
const refE = React.createRef();
const refF = React.createRef();
const refG = React.createRef();
function Example() {
return (
<>
<div ref={refA} data-debug="A" />
<div ref={refB} data-debug="B" />
<div ref={refC} data-debug="C" />
<div ref={refD} data-debug="D" />
<div ref={refE} data-debug="E" />
<div ref={refF} data-debug="F" />
<div ref={refG} data-debug="G" />
</>
);
}
render(<Example />, container);
// A, B, and C are all adjacent and/or overlapping, with the same height.
setBoundingClientRect(refA.current, {
x: 30,
y: 0,
width: 40,
height: 25,
});
setBoundingClientRect(refB.current, {
x: 0,
y: 0,
width: 50,
height: 25,
});
setBoundingClientRect(refC.current, {
x: 70,
y: 0,
width: 20,
height: 25,
});
// D is partially overlapping with A and B, but is too tall to be merged.
setBoundingClientRect(refD.current, {
x: 20,
y: 0,
width: 20,
height: 30,
});
// Same thing but for a vertical group.
// Some of them could intersect with the horizontal group,
// except they're too far to the right.
setBoundingClientRect(refE.current, {
x: 100,
y: 25,
width: 25,
height: 50,
});
setBoundingClientRect(refF.current, {
x: 100,
y: 0,
width: 25,
height: 25,
});
setBoundingClientRect(refG.current, {
x: 100,
y: 75,
width: 25,
height: 10,
});
const rects = findBoundingRects(document.body, [
createComponentSelector(Example),
]);
expect(rects).toHaveLength(3);
expect(rects).toContainEqual({
x: 0,
y: 0,
width: 90,
height: 25,
});
expect(rects).toContainEqual({
x: 20,
y: 0,
width: 20,
height: 30,
});
expect(rects).toContainEqual({
x: 100,
y: 0,
width: 25,
height: 85,
});
});
// @gate www || experimental
it('should not search within hidden subtrees', () => {
const refA = React.createRef();
const refB = React.createRef();
const refC = React.createRef();
function Example() {
return (
<>
<div ref={refA} />
<div hidden={true} ref={refB} />
<div ref={refC} />
</>
);
}
render(<Example />, container);
setBoundingClientRect(refA.current, {
x: 10,
y: 10,
width: 50,
height: 25,
});
setBoundingClientRect(refB.current, {
x: 100,
y: 10,
width: 20,
height: 10,
});
setBoundingClientRect(refC.current, {
x: 200,
y: 10,
width: 50,
height: 25,
});
const rects = findBoundingRects(document.body, [
createComponentSelector(Example),
]);
expect(rects).toHaveLength(2);
expect(rects).toContainEqual({
x: 10,
y: 10,
width: 50,
height: 25,
});
expect(rects).toContainEqual({
x: 200,
y: 10,
width: 50,
height: 25,
});
});
});
describe('focusWithin', () => {
// @gate www || experimental
it('should return false if the specified component path has no matches', () => {
function Example() {
return <Child />;
}
function Child() {
return null;
}
function NotUsed() {
return null;
}
render(<Example />, container);
const didFocus = focusWithin(document.body, [
createComponentSelector(Example),
createComponentSelector(NotUsed),
]);
expect(didFocus).toBe(false);
});
// @gate www || experimental
it('should return false if there are no focusable elements within the matched subtree', () => {
function Example() {
return <Child />;
}
function Child() {
return 'not focusable';
}
render(<Example />, container);
const didFocus = focusWithin(document.body, [
createComponentSelector(Example),
createComponentSelector(Child),
]);
expect(didFocus).toBe(false);
});
// @gate www || experimental
it('should return false if the only focusable elements are disabled', () => {
function Example() {
return (
<button disabled={true} style={{width: 10, height: 10}}>
not clickable
</button>
);
}
render(<Example />, container);
const didFocus = focusWithin(document.body, [
createComponentSelector(Example),
]);
expect(didFocus).toBe(false);
});
// @gate www || experimental
it('should return false if the only focusable elements are hidden', () => {
function Example() {
return <button hidden={true}>not clickable</button>;
}
render(<Example />, container);
const didFocus = focusWithin(document.body, [
createComponentSelector(Example),
]);
expect(didFocus).toBe(false);
});
// @gate www || experimental
it('should successfully focus the first focusable element within the tree', () => {
const secondRef = React.createRef(null);
const handleFirstFocus = jest.fn();
const handleSecondFocus = jest.fn();
const handleThirdFocus = jest.fn();
function Example() {
return (
<>
<FirstChild />
<SecondChild />
<ThirdChild />
</>
);
}
function FirstChild() {
return (
<button hidden={true} onFocus={handleFirstFocus}>
not clickable
</button>
);
}
function SecondChild() {
return (
<button
ref={secondRef}
style={{width: 10, height: 10}}
onFocus={handleSecondFocus}>
clickable
</button>
);
}
function ThirdChild() {
return (
<button style={{width: 10, height: 10}} onFocus={handleThirdFocus}>
clickable
</button>
);
}
render(<Example />, container);
const didFocus = focusWithin(document.body, [
createComponentSelector(Example),
]);
expect(didFocus).toBe(true);
expect(document.activeElement).not.toBeNull();
expect(document.activeElement).toBe(secondRef.current);
expect(handleFirstFocus).not.toHaveBeenCalled();
expect(handleSecondFocus).toHaveBeenCalledTimes(1);
expect(handleThirdFocus).not.toHaveBeenCalled();
});
// @gate www || experimental
it('should successfully focus the first focusable element even if application logic interferes', () => {
const ref = React.createRef(null);
const handleFocus = jest.fn(event => {
event.target.blur();
});
function Example() {
return (
<button
ref={ref}
style={{width: 10, height: 10}}
onFocus={handleFocus}>
clickable
</button>
);
}
render(<Example />, container);
const didFocus = focusWithin(document.body, [
createComponentSelector(Example),
]);
expect(didFocus).toBe(true);
expect(ref.current).not.toBeNull();
expect(ref.current).not.toBe(document.activeElement);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
// @gate www || experimental
it('should not focus within hidden subtrees', () => {
const secondRef = React.createRef(null);
const handleFirstFocus = jest.fn();
const handleSecondFocus = jest.fn();
const handleThirdFocus = jest.fn();
function Example() {
return (
<>
<FirstChild />
<SecondChild />
<ThirdChild />
</>
);
}
function FirstChild() {
return (
<div hidden={true}>
<button style={{width: 10, height: 10}} onFocus={handleFirstFocus}>
hidden
</button>
</div>
);
}
function SecondChild() {
return (
<button
ref={secondRef}
style={{width: 10, height: 10}}
onFocus={handleSecondFocus}>
clickable
</button>
);
}
function ThirdChild() {
return (
<button style={{width: 10, height: 10}} onFocus={handleThirdFocus}>
clickable
</button>
);
}
render(<Example />, container);
const didFocus = focusWithin(document.body, [
createComponentSelector(Example),
]);
expect(didFocus).toBe(true);
expect(document.activeElement).not.toBeNull();
expect(document.activeElement).toBe(secondRef.current);
expect(handleFirstFocus).not.toHaveBeenCalled();
expect(handleSecondFocus).toHaveBeenCalledTimes(1);
expect(handleThirdFocus).not.toHaveBeenCalled();
});
});
describe('observeVisibleRects', () => {
// Stub out getBoundingClientRect for the specified target.
// This API is required by the test selectors but it isn't implemented by jsdom.
function setBoundingClientRect(target, {x, y, width, height}) {
target.getBoundingClientRect = function () {
return {
width,
height,
left: x,
right: x + width,
top: y,
bottom: y + height,
};
};
}
function simulateIntersection(...entries) {
callback(
entries.map(([target, rect, ratio]) => ({
boundingClientRect: {
top: rect.y,
left: rect.x,
width: rect.width,
height: rect.height,
},
intersectionRatio: ratio,
target,
})),
);
}
let callback;
let observedTargets;
beforeEach(() => {
callback = null;
observedTargets = [];
class IntersectionObserver {
constructor() {
callback = arguments[0];
}
disconnect() {
callback = null;
observedTargets.splice(0);
}
observe(target) {
observedTargets.push(target);
}
unobserve(target) {
const index = observedTargets.indexOf(target);
if (index >= 0) {
observedTargets.splice(index, 1);
}
}
}
// This is a broken polyfill.
// It is only intended to provide bare minimum test coverage.
// More meaningful tests will require the use of fixtures.
window.IntersectionObserver = IntersectionObserver;
});
// @gate www || experimental
it('should notify a listener when the underlying instance intersection changes', () => {
const ref = React.createRef(null);
function Example() {
return <div ref={ref} />;
}
render(<Example />, container);
// Stub out the size of the element this test will be observing.
const rect = {
x: 10,
y: 20,
width: 200,
height: 100,
};
setBoundingClientRect(ref.current, rect);
const handleVisibilityChange = jest.fn();
observeVisibleRects(
document.body,
[createComponentSelector(Example)],
handleVisibilityChange,
);
expect(callback).not.toBeNull();
expect(observedTargets).toHaveLength(1);
expect(handleVisibilityChange).not.toHaveBeenCalled();
// Simulate IntersectionObserver notification.
simulateIntersection([ref.current, rect, 0.5]);
expect(handleVisibilityChange).toHaveBeenCalledTimes(1);
expect(handleVisibilityChange).toHaveBeenCalledWith([{rect, ratio: 0.5}]);
});
// @gate www || experimental
it('should notify a listener of multiple targets when the underlying instance intersection changes', () => {
const ref1 = React.createRef(null);
const ref2 = React.createRef(null);
function Example() {
return (
<>
<div ref={ref1} />
<div ref={ref2} />
</>
);
}
render(<Example />, container);
// Stub out the size of the element this test will be observing.
const rect1 = {
x: 10,
y: 20,
width: 200,
height: 100,
};
let rect2 = {
x: 210,
y: 20,
width: 200,
height: 100,
};
setBoundingClientRect(ref1.current, rect1);
setBoundingClientRect(ref2.current, rect2);
const handleVisibilityChange = jest.fn();
observeVisibleRects(
document.body,
[createComponentSelector(Example)],
handleVisibilityChange,
);
expect(callback).not.toBeNull();
expect(observedTargets).toHaveLength(2);
expect(handleVisibilityChange).not.toHaveBeenCalled();
// Simulate IntersectionObserver notification.
simulateIntersection([ref1.current, rect1, 0.5]);
// Even though only one of the rects changed intersection,
// the test selector should describe the current state of both.
expect(handleVisibilityChange).toHaveBeenCalledTimes(1);
expect(handleVisibilityChange).toHaveBeenCalledWith([
{rect: rect1, ratio: 0.5},
{rect: rect2, ratio: 0},
]);
handleVisibilityChange.mockClear();
rect2 = {
x: 210,
y: 20,
width: 200,
height: 200,
};
// Simulate another IntersectionObserver notification.
simulateIntersection(
[ref1.current, rect1, 1],
[ref2.current, rect2, 0.25],
);
// The newly changed display rect should also be provided for the second target.
expect(handleVisibilityChange).toHaveBeenCalledTimes(1);
expect(handleVisibilityChange).toHaveBeenCalledWith([
{rect: rect1, ratio: 1},
{rect: rect2, ratio: 0.25},
]);
});
// @gate www || experimental
it('should stop listening when its disconnected', () => {
const ref = React.createRef(null);
function Example() {
return <div ref={ref} />;
}
render(<Example />, container);
// Stub out the size of the element this test will be observing.
const rect = {
x: 10,
y: 20,
width: 200,
height: 100,
};
setBoundingClientRect(ref.current, rect);
const handleVisibilityChange = jest.fn();
const {disconnect} = observeVisibleRects(
document.body,
[createComponentSelector(Example)],
handleVisibilityChange,
);
expect(callback).not.toBeNull();
expect(observedTargets).toHaveLength(1);
expect(handleVisibilityChange).not.toHaveBeenCalled();
disconnect();
expect(callback).toBeNull();
});
// This test reuires gating because it relies on the __DEV__ only commit hook to work.
// @gate www || experimental && __DEV__
it('should update which targets its listening to after a commit', () => {
const ref1 = React.createRef(null);
const ref2 = React.createRef(null);
let increment;
function Example() {
const [count, setCount] = React.useState(0);
increment = () => setCount(count + 1);
return (
<>
{count < 2 && <div ref={ref1} />}
{count > 0 && <div ref={ref2} />}
</>
);
}
render(<Example />, container);
// Stub out the size of the element this test will be observing.
const rect1 = {
x: 10,
y: 20,
width: 200,
height: 100,
};
setBoundingClientRect(ref1.current, rect1);
const handleVisibilityChange = jest.fn();
observeVisibleRects(
document.body,
[createComponentSelector(Example)],
handleVisibilityChange,
);
// Simulate IntersectionObserver notification.
simulateIntersection([ref1.current, rect1, 1]);
expect(handleVisibilityChange).toHaveBeenCalledTimes(1);
expect(handleVisibilityChange).toHaveBeenCalledWith([
{rect: rect1, ratio: 1},
]);
act(() => increment());
const rect2 = {
x: 110,
y: 20,
width: 200,
height: 100,
};
setBoundingClientRect(ref2.current, rect2);
handleVisibilityChange.mockClear();
simulateIntersection(
[ref1.current, rect1, 0.5],
[ref2.current, rect2, 0.25],
);
expect(handleVisibilityChange).toHaveBeenCalledTimes(1);
expect(handleVisibilityChange).toHaveBeenCalledWith([
{rect: rect1, ratio: 0.5},
{rect: rect2, ratio: 0.25},
]);
act(() => increment());
handleVisibilityChange.mockClear();
simulateIntersection([ref2.current, rect2, 0.75]);
expect(handleVisibilityChange).toHaveBeenCalledTimes(1);
expect(handleVisibilityChange).toHaveBeenCalledWith([
{rect: rect2, ratio: 0.75},
]);
});
// @gate www || experimental
it('should not observe components within hidden subtrees', () => {
const ref1 = React.createRef(null);
const ref2 = React.createRef(null);
function Example() {
return (
<>
<div ref={ref1} />
<div hidden={true} ref={ref2} />
</>
);
}
render(<Example />, container);
// Stub out the size of the element this test will be observing.
const rect1 = {
x: 10,
y: 20,
width: 200,
height: 100,
};
const rect2 = {
x: 210,
y: 20,
width: 200,
height: 100,
};
setBoundingClientRect(ref1.current, rect1);
setBoundingClientRect(ref2.current, rect2);
const handleVisibilityChange = jest.fn();
observeVisibleRects(
document.body,
[createComponentSelector(Example)],
handleVisibilityChange,
);
expect(callback).not.toBeNull();
expect(observedTargets).toHaveLength(1);
expect(observedTargets[0]).toBe(ref1.current);
});
});
});
| 24.870924 | 112 | 0.539692 |
null | #!/usr/bin/env node
'use strict';
const {tmpdir} = require('os');
const {join} = require('path');
const {getBuildInfo, handleError} = require('./utils');
// This script is an escape hatch!
// It exists for special case manual builds.
// The typical suggested release process is to create a "next" build from a CI artifact.
// This build script is optimized for speed and simplicity.
// It doesn't run all of the tests that the CI environment runs.
// You're expected to run those manually before publishing a release.
const addBuildInfoJSON = require('./build-release-locally-commands/add-build-info-json');
const buildArtifacts = require('./build-release-locally-commands/build-artifacts');
const confirmAutomatedTesting = require('./build-release-locally-commands/confirm-automated-testing');
const copyRepoToTempDirectory = require('./build-release-locally-commands/copy-repo-to-temp-directory');
const npmPackAndUnpack = require('./build-release-locally-commands/npm-pack-and-unpack');
const printPrereleaseSummary = require('./shared-commands/print-prerelease-summary');
const updateVersionNumbers = require('./build-release-locally-commands/update-version-numbers');
const run = async () => {
try {
const cwd = join(__dirname, '..', '..');
const {branch, checksum, commit, reactVersion, version} =
await getBuildInfo();
const tempDirectory = join(tmpdir(), `react-${commit}`);
const params = {
branch,
checksum,
commit,
cwd,
reactVersion,
tempDirectory,
version,
};
await confirmAutomatedTesting(params);
await copyRepoToTempDirectory(params);
await updateVersionNumbers(params);
await addBuildInfoJSON(params);
await buildArtifacts(params);
await npmPackAndUnpack(params);
await printPrereleaseSummary(params, false);
} catch (error) {
handleError(error);
}
};
run();
| 34.641509 | 104 | 0.716631 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Request} from 'react-server/src/ReactFlightServer';
export * from 'react-server-dom-fb/src/ReactFlightServerConfigFBBundler';
export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM';
export const supportsRequestStorage = false;
export const requestStorage: AsyncLocalStorage<Request> = (null: any);
export * from '../ReactFlightServerConfigDebugNoop';
| 30.052632 | 73 | 0.764007 |
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 assertLog;
let waitFor;
describe('ReactDOMNativeEventHeuristic-test', () => {
let container;
beforeEach(() => {
jest.resetModules();
container = document.createElement('div');
React = require('react');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
Scheduler = require('scheduler');
act = require('internal-test-utils').act;
const InternalTestUtils = require('internal-test-utils');
assertLog = InternalTestUtils.assertLog;
waitFor = InternalTestUtils.waitFor;
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
});
function dispatchAndSetCurrentEvent(el, event) {
try {
window.event = event;
el.dispatchEvent(event);
} finally {
window.event = undefined;
}
}
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);
React.useLayoutEffect(() => {
disableButtonRef.current.onclick = disableForm;
});
function disableForm() {
setActive(false);
}
return (
<div>
<button 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');
// Dispatch a click event on the Disable-button.
await act(async () => {
const firstEvent = document.createEvent('Event');
firstEvent.initEvent('click', true, true);
dispatchAndSetCurrentEvent(disableButton, firstEvent);
});
// Discrete events should be flushed in a microtask.
// Verify that the second button was removed.
expect(submitButtonRef.current).toBe(null);
// We'll assume that the browser won't let the user click it.
});
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);
React.useLayoutEffect(() => {
disableButtonRef.current.onclick = disableForm;
submitButtonRef.current.onclick = active
? submitForm
: disabledSubmitForm;
});
function disableForm() {
setActive(false);
}
function submitForm() {
formSubmitted = true; // This should not get invoked
}
function disabledSubmitForm() {
// The form is disabled.
}
return (
<div>
<button ref={disableButtonRef}>Disable</button>
<button ref={submitButtonRef}>Submit</button>
</div>
);
}
const root = ReactDOMClient.createRoot(container);
// Flush
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(() => {
dispatchAndSetCurrentEvent(disableButton, 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');
// Flush the discrete event
ReactDOM.flushSync();
// Now let's dispatch an event on the submit button.
const secondEvent = document.createEvent('Event');
secondEvent.initEvent('click', true, true);
dispatchAndSetCurrentEvent(submitButton, 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);
React.useLayoutEffect(() => {
enableButtonRef.current.onclick = enableForm;
submitButtonRef.current.onclick = active ? submitForm : null;
});
function enableForm() {
setActive(true);
}
function submitForm() {
formSubmitted = true; // This should not get invoked
}
return (
<div>
<button ref={enableButtonRef}>Enable</button>
<button 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.
await act(() => {
const firstEvent = document.createEvent('Event');
firstEvent.initEvent('click', true, true);
dispatchAndSetCurrentEvent(enableButton, 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');
// Flush discrete updates
ReactDOM.flushSync();
// Now let's dispatch an event on the submit button.
const secondEvent = document.createEvent('Event');
secondEvent.initEvent('click', true, true);
dispatchAndSetCurrentEvent(submitButton, secondEvent);
});
// Therefore the form should have been submitted.
expect(formSubmitted).toBe(true);
});
it('mouse over should be user-blocking but not discrete', async () => {
const root = ReactDOMClient.createRoot(container);
const target = React.createRef(null);
function Foo() {
const [isHover, setHover] = React.useState(false);
React.useLayoutEffect(() => {
target.current.onmouseover = () => setHover(true);
});
return <div ref={target}>{isHover ? 'hovered' : 'not hovered'}</div>;
}
await act(() => {
root.render(<Foo />);
});
expect(container.textContent).toEqual('not hovered');
await act(() => {
const mouseOverEvent = document.createEvent('MouseEvents');
mouseOverEvent.initEvent('mouseover', true, true);
dispatchAndSetCurrentEvent(target.current, mouseOverEvent);
// Flush discrete updates
ReactDOM.flushSync();
// Since mouse over is not discrete, should not have updated yet
expect(container.textContent).toEqual('not hovered');
});
expect(container.textContent).toEqual('hovered');
});
it('mouse enter should be user-blocking but not discrete', async () => {
const root = ReactDOMClient.createRoot(container);
const target = React.createRef(null);
function Foo() {
const [isHover, setHover] = React.useState(false);
React.useLayoutEffect(() => {
target.current.onmouseenter = () => setHover(true);
});
return <div ref={target}>{isHover ? 'hovered' : 'not hovered'}</div>;
}
await act(() => {
root.render(<Foo />);
});
expect(container.textContent).toEqual('not hovered');
await act(() => {
// Note: React does not use native mouseenter/mouseleave events
// but we should still correctly determine their priority.
const mouseEnterEvent = document.createEvent('MouseEvents');
mouseEnterEvent.initEvent('mouseenter', true, true);
dispatchAndSetCurrentEvent(target.current, mouseEnterEvent);
// Flush discrete updates
ReactDOM.flushSync();
// Since mouse end is not discrete, should not have updated yet
expect(container.textContent).toEqual('not hovered');
});
expect(container.textContent).toEqual('hovered');
});
it('continuous native events flush as expected', async () => {
const root = ReactDOMClient.createRoot(container);
const target = React.createRef(null);
function Foo({hovered}) {
const hoverString = hovered ? 'hovered' : 'not hovered';
Scheduler.log(hoverString);
return <div ref={target}>{hoverString}</div>;
}
await act(() => {
root.render(<Foo hovered={false} />);
});
expect(container.textContent).toEqual('not hovered');
await act(async () => {
// Note: React does not use native mouseenter/mouseleave events
// but we should still correctly determine their priority.
const mouseEnterEvent = document.createEvent('MouseEvents');
mouseEnterEvent.initEvent('mouseover', true, true);
target.current.addEventListener('mouseover', () => {
root.render(<Foo hovered={true} />);
});
dispatchAndSetCurrentEvent(target.current, mouseEnterEvent);
// Since mouse end is not discrete, should not have updated yet
assertLog(['not hovered']);
expect(container.textContent).toEqual('not hovered');
await waitFor(['hovered']);
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
expect(container.textContent).toEqual('not hovered');
} else {
expect(container.textContent).toEqual('hovered');
}
});
expect(container.textContent).toEqual('hovered');
});
it('should batch inside native events', async () => {
const root = ReactDOMClient.createRoot(container);
const target = React.createRef(null);
function Foo() {
const [count, setCount] = React.useState(0);
const countRef = React.useRef(-1);
React.useLayoutEffect(() => {
countRef.current = count;
target.current.onclick = () => {
setCount(countRef.current + 1);
// Now update again. If these updates are batched, then this should be
// a no-op, because we didn't re-render yet and `countRef` hasn't
// been mutated.
setCount(countRef.current + 1);
};
});
return <div ref={target}>Count: {count}</div>;
}
await act(() => {
root.render(<Foo />);
});
expect(container.textContent).toEqual('Count: 0');
await act(async () => {
const pressEvent = document.createEvent('Event');
pressEvent.initEvent('click', true, true);
dispatchAndSetCurrentEvent(target.current, pressEvent);
});
// If this is 2, that means the `setCount` calls were not batched.
expect(container.textContent).toEqual('Count: 1');
});
it('should not flush discrete events at the end of outermost batchedUpdates', async () => {
const root = ReactDOMClient.createRoot(container);
let target;
function Foo() {
const [count, setCount] = React.useState(0);
return (
<div
ref={el => {
target = el;
if (target !== null) {
el.onclick = () => {
ReactDOM.unstable_batchedUpdates(() => {
setCount(count + 1);
});
Scheduler.log(
container.textContent + ' [after batchedUpdates]',
);
};
}
}}>
Count: {count}
</div>
);
}
await act(() => {
root.render(<Foo />);
});
expect(container.textContent).toEqual('Count: 0');
await act(async () => {
const pressEvent = document.createEvent('Event');
pressEvent.initEvent('click', true, true);
dispatchAndSetCurrentEvent(target, pressEvent);
assertLog(['Count: 0 [after batchedUpdates]']);
expect(container.textContent).toEqual('Count: 0');
});
expect(container.textContent).toEqual('Count: 1');
});
});
| 29.92 | 93 | 0.628123 |
thieves-tools | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export * from './src/ReactFlightDOMServerNode';
| 22 | 66 | 0.702381 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireDefault(require("react"));
var _useTheme = _interopRequireDefault(require("./useTheme"));
var _jsxFileName = "";
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Component() {
const theme = (0, _useTheme.default)();
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 10
}
}, "theme: ", theme);
}
//# sourceMappingURL=ComponentWithExternalCustomHooks.js.map?foo=bar¶m=some_value | 25.423077 | 95 | 0.670554 |
owtf | var webpack = require('webpack');
module.exports = {
context: __dirname,
entry: './app.js',
module: {
loaders: [
{
loader: require.resolve('babel-loader'),
test: /\.js$/,
exclude: /node_modules/,
query: {
presets: [
require.resolve('@babel/preset-env'),
require.resolve('@babel/preset-react'),
],
plugins: [require.resolve('@babel/plugin-proposal-class-properties')],
},
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development'),
},
}),
],
resolve: {
alias: {
react: require.resolve('react'),
},
},
};
| 19.628571 | 80 | 0.499307 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
import {BatchedBridge} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
import type {ReactFabricType} from './ReactNativeTypes';
let ReactFabric;
if (__DEV__) {
ReactFabric = require('../implementations/ReactFabric-dev');
} else {
ReactFabric = require('../implementations/ReactFabric-prod');
}
global.RN$stopSurface = ReactFabric.stopSurface;
if (global.RN$Bridgeless !== true) {
BatchedBridge.registerCallableModule('ReactFabric', ReactFabric);
}
module.exports = (ReactFabric: ReactFabricType);
| 22.875 | 94 | 0.735256 |
Python-Penetration-Testing-for-Developers | let React;
let Activity;
let ReactNoop;
let act;
let log;
describe('Activity StrictMode', () => {
beforeEach(() => {
jest.resetModules();
log = [];
React = require('react');
Activity = React.unstable_Activity;
ReactNoop = require('react-noop-renderer');
act = require('internal-test-utils').act;
});
function Component({label}) {
React.useEffect(() => {
log.push(`${label}: useEffect mount`);
return () => log.push(`${label}: useEffect unmount`);
});
React.useLayoutEffect(() => {
log.push(`${label}: useLayoutEffect mount`);
return () => log.push(`${label}: useLayoutEffect unmount`);
});
log.push(`${label}: render`);
return <span>label</span>;
}
// @gate __DEV__ && enableActivity
it('should trigger strict effects when offscreen is visible', async () => {
await act(() => {
ReactNoop.render(
<React.StrictMode>
<Activity mode="visible">
<Component label="A" />
</Activity>
</React.StrictMode>,
);
});
expect(log).toEqual([
'A: render',
'A: render',
'A: useLayoutEffect mount',
'A: useEffect mount',
'A: useLayoutEffect unmount',
'A: useEffect unmount',
'A: useLayoutEffect mount',
'A: useEffect mount',
]);
});
// @gate __DEV__ && enableActivity && enableDO_NOT_USE_disableStrictPassiveEffect
it('does not trigger strict effects when disableStrictPassiveEffect is presented on StrictMode', async () => {
await act(() => {
ReactNoop.render(
<React.StrictMode DO_NOT_USE_disableStrictPassiveEffect={true}>
<Activity>
<Component label="A" />
</Activity>
</React.StrictMode>,
);
});
expect(log).toEqual([
'A: render',
'A: render',
'A: useLayoutEffect mount',
'A: useEffect mount',
'A: useLayoutEffect unmount',
'A: useLayoutEffect mount',
]);
});
// @gate __DEV__ && enableActivity && useModernStrictMode
it('should not trigger strict effects when offscreen is hidden', async () => {
await act(() => {
ReactNoop.render(
<React.StrictMode>
<Activity mode="hidden">
<Component label="A" />
</Activity>
</React.StrictMode>,
);
});
expect(log).toEqual(['A: render', 'A: render']);
log = [];
await act(() => {
ReactNoop.render(
<React.StrictMode>
<Activity mode="hidden">
<Component label="A" />
<Component label="B" />
</Activity>
</React.StrictMode>,
);
});
expect(log).toEqual(['A: render', 'A: render', 'B: render', 'B: render']);
log = [];
await act(() => {
ReactNoop.render(
<React.StrictMode>
<Activity mode="visible">
<Component label="A" />
</Activity>
</React.StrictMode>,
);
});
expect(log).toEqual([
'A: render',
'A: render',
'A: useLayoutEffect mount',
'A: useEffect mount',
'A: useLayoutEffect unmount',
'A: useEffect unmount',
'A: useLayoutEffect mount',
'A: useEffect mount',
]);
log = [];
await act(() => {
ReactNoop.render(
<React.StrictMode>
<Activity mode="hidden">
<Component label="A" />
</Activity>
</React.StrictMode>,
);
});
expect(log).toEqual([
'A: useLayoutEffect unmount',
'A: useEffect unmount',
'A: render',
'A: render',
]);
});
it('should not cause infinite render loop when StrictMode is used with Suspense and synchronous set states', async () => {
// This is a regression test, see https://github.com/facebook/react/pull/25179 for more details.
function App() {
const [state, setState] = React.useState(false);
React.useLayoutEffect(() => {
setState(true);
}, []);
React.useEffect(() => {
// Empty useEffect with empty dependency array is needed to trigger infinite render loop.
}, []);
return state;
}
await act(() => {
ReactNoop.render(
<React.StrictMode>
<React.Suspense>
<App />
</React.Suspense>
</React.StrictMode>,
);
});
});
// @gate __DEV__ && enableActivity
it('should double invoke effects on unsuspended child', async () => {
let shouldSuspend = true;
let resolve;
const suspensePromise = new Promise(_resolve => {
resolve = _resolve;
});
function Parent() {
log.push('Parent rendered');
React.useEffect(() => {
log.push('Parent mount');
return () => {
log.push('Parent unmount');
};
});
return (
<React.Suspense fallback="fallback">
<Child />
</React.Suspense>
);
}
function Child() {
log.push('Child rendered');
React.useEffect(() => {
log.push('Child mount');
return () => {
log.push('Child unmount');
};
});
if (shouldSuspend) {
log.push('Child suspended');
throw suspensePromise;
}
return null;
}
await act(() => {
ReactNoop.render(
<React.StrictMode>
<Activity mode="visible">
<Parent />
</Activity>
</React.StrictMode>,
);
});
log.push('------------------------------');
await act(() => {
resolve();
shouldSuspend = false;
});
expect(log).toEqual([
'Parent rendered',
'Parent rendered',
'Child rendered',
'Child suspended',
'Parent mount',
'Parent unmount',
'Parent mount',
'------------------------------',
'Child rendered',
'Child rendered',
'Child mount',
'Child unmount',
'Child mount',
]);
});
});
| 22.599206 | 124 | 0.517827 |
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
*/
/* globals MSApp */
import {SVG_NAMESPACE} from './DOMNamespaces';
import {enableTrustedTypesIntegration} from 'shared/ReactFeatureFlags';
// SVG temp container for IE lacking innerHTML
let reusableSVGContainer: HTMLElement;
function setInnerHTMLImpl(
node: Element,
html: {valueOf(): {toString(): string, ...}, ...},
): void {
if (node.namespaceURI === SVG_NAMESPACE) {
if (__DEV__) {
if (enableTrustedTypesIntegration) {
// TODO: reconsider the text of this warning and when it should show
// before enabling the feature flag.
if (typeof trustedTypes !== 'undefined') {
console.error(
"Using 'dangerouslySetInnerHTML' in an svg element with " +
'Trusted Types enabled in an Internet Explorer will cause ' +
'the trusted value to be converted to string. Assigning string ' +
"to 'innerHTML' will throw an error if Trusted Types are enforced. " +
"You can try to wrap your svg element inside a div and use 'dangerouslySetInnerHTML' " +
'on the enclosing div instead.',
);
}
}
}
if (!('innerHTML' in node)) {
// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
reusableSVGContainer =
reusableSVGContainer || document.createElement('div');
reusableSVGContainer.innerHTML =
'<svg>' + html.valueOf().toString() + '</svg>';
const svgNode = reusableSVGContainer.firstChild;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
// $FlowFixMe[incompatible-use]
// $FlowFixMe[incompatible-type]
while (svgNode.firstChild) {
node.appendChild(svgNode.firstChild);
}
return;
}
}
node.innerHTML = (html: any);
}
let setInnerHTML: (
node: Element,
html: {valueOf(): {toString(): string, ...}, ...},
) => void = setInnerHTMLImpl;
// $FlowFixMe[cannot-resolve-name]
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
/**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/
setInnerHTML = function (
node: Element,
html: {valueOf(): {toString(): string, ...}, ...},
): void {
// $FlowFixMe[cannot-resolve-name]
return MSApp.execUnsafeLocalFunction(function () {
return setInnerHTMLImpl(node, html);
});
};
}
export default setInnerHTML;
| 31.783133 | 102 | 0.634559 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {TEXT_NODE} from './HTMLNodeType';
/**
* Set the textContent property of a node. For text updates, it's faster
* to set the `nodeValue` of the Text node directly instead of using
* `.textContent` which will remove the existing node and create a new one.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
function setTextContent(node: Element, text: string): void {
if (text) {
const firstChild = node.firstChild;
if (
firstChild &&
firstChild === node.lastChild &&
firstChild.nodeType === TEXT_NODE
) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text;
}
export default setTextContent;
| 22.526316 | 75 | 0.665174 |
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
*/
// Modules provided by RN:
import {
deepDiffer,
flattenStyle,
} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
import isArray from 'shared/isArray';
import type {AttributeConfiguration} from './ReactNativeTypes';
const emptyObject = {};
/**
* Create a payload that contains all the updates between two sets of props.
*
* These helpers are all encapsulated into a single module, because they use
* mutation as a performance optimization which leads to subtle shared
* dependencies between the code paths. To avoid this mutable state leaking
* across modules, I've kept them isolated to this module.
*/
type NestedNode = Array<NestedNode> | Object;
// Tracks removed keys
let removedKeys: {[string]: boolean} | null = null;
let removedKeyCount = 0;
const deepDifferOptions = {
unsafelyIgnoreFunctions: true,
};
function defaultDiffer(prevProp: mixed, nextProp: mixed): boolean {
if (typeof nextProp !== 'object' || nextProp === null) {
// Scalars have already been checked for equality
return true;
} else {
// For objects and arrays, the default diffing algorithm is a deep compare
return deepDiffer(prevProp, nextProp, deepDifferOptions);
}
}
function restoreDeletedValuesInNestedArray(
updatePayload: Object,
node: NestedNode,
validAttributes: AttributeConfiguration,
) {
if (isArray(node)) {
let i = node.length;
while (i-- && removedKeyCount > 0) {
restoreDeletedValuesInNestedArray(
updatePayload,
node[i],
validAttributes,
);
}
} else if (node && removedKeyCount > 0) {
const obj = node;
for (const propKey in removedKeys) {
// $FlowFixMe[incompatible-use] found when upgrading Flow
if (!removedKeys[propKey]) {
continue;
}
let nextProp = obj[propKey];
if (nextProp === undefined) {
continue;
}
const attributeConfig = validAttributes[propKey];
if (!attributeConfig) {
continue; // not a valid native prop
}
if (typeof nextProp === 'function') {
// $FlowFixMe[incompatible-type] found when upgrading Flow
nextProp = true;
}
if (typeof nextProp === 'undefined') {
// $FlowFixMe[incompatible-type] found when upgrading Flow
nextProp = null;
}
if (typeof attributeConfig !== 'object') {
// case: !Object is the default case
updatePayload[propKey] = nextProp;
} else if (
typeof attributeConfig.diff === 'function' ||
typeof attributeConfig.process === 'function'
) {
// case: CustomAttributeConfiguration
const nextValue =
typeof attributeConfig.process === 'function'
? attributeConfig.process(nextProp)
: nextProp;
updatePayload[propKey] = nextValue;
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
removedKeys[propKey] = false;
removedKeyCount--;
}
}
}
function diffNestedArrayProperty(
updatePayload: null | Object,
prevArray: Array<NestedNode>,
nextArray: Array<NestedNode>,
validAttributes: AttributeConfiguration,
): null | Object {
const minLength =
prevArray.length < nextArray.length ? prevArray.length : nextArray.length;
let i;
for (i = 0; i < minLength; i++) {
// Diff any items in the array in the forward direction. Repeated keys
// will be overwritten by later values.
updatePayload = diffNestedProperty(
updatePayload,
prevArray[i],
nextArray[i],
validAttributes,
);
}
for (; i < prevArray.length; i++) {
// Clear out all remaining properties.
updatePayload = clearNestedProperty(
updatePayload,
prevArray[i],
validAttributes,
);
}
for (; i < nextArray.length; i++) {
// Add all remaining properties.
updatePayload = addNestedProperty(
updatePayload,
nextArray[i],
validAttributes,
);
}
return updatePayload;
}
function diffNestedProperty(
updatePayload: null | Object,
prevProp: NestedNode,
nextProp: NestedNode,
validAttributes: AttributeConfiguration,
): null | Object {
if (!updatePayload && prevProp === nextProp) {
// If no properties have been added, then we can bail out quickly on object
// equality.
return updatePayload;
}
if (!prevProp || !nextProp) {
if (nextProp) {
return addNestedProperty(updatePayload, nextProp, validAttributes);
}
if (prevProp) {
return clearNestedProperty(updatePayload, prevProp, validAttributes);
}
return updatePayload;
}
if (!isArray(prevProp) && !isArray(nextProp)) {
// Both are leaves, we can diff the leaves.
return diffProperties(updatePayload, prevProp, nextProp, validAttributes);
}
if (isArray(prevProp) && isArray(nextProp)) {
// Both are arrays, we can diff the arrays.
return diffNestedArrayProperty(
updatePayload,
prevProp,
nextProp,
validAttributes,
);
}
if (isArray(prevProp)) {
return diffProperties(
updatePayload,
flattenStyle(prevProp),
nextProp,
validAttributes,
);
}
return diffProperties(
updatePayload,
prevProp,
flattenStyle(nextProp),
validAttributes,
);
}
/**
* addNestedProperty takes a single set of props and valid attribute
* attribute configurations. It processes each prop and adds it to the
* updatePayload.
*/
function addNestedProperty(
updatePayload: null | Object,
nextProp: NestedNode,
validAttributes: AttributeConfiguration,
): $FlowFixMe {
if (!nextProp) {
return updatePayload;
}
if (!isArray(nextProp)) {
// Add each property of the leaf.
return addProperties(updatePayload, nextProp, validAttributes);
}
for (let i = 0; i < nextProp.length; i++) {
// Add all the properties of the array.
updatePayload = addNestedProperty(
updatePayload,
nextProp[i],
validAttributes,
);
}
return updatePayload;
}
/**
* clearNestedProperty takes a single set of props and valid attributes. It
* adds a null sentinel to the updatePayload, for each prop key.
*/
function clearNestedProperty(
updatePayload: null | Object,
prevProp: NestedNode,
validAttributes: AttributeConfiguration,
): null | Object {
if (!prevProp) {
return updatePayload;
}
if (!isArray(prevProp)) {
// Add each property of the leaf.
return clearProperties(updatePayload, prevProp, validAttributes);
}
for (let i = 0; i < prevProp.length; i++) {
// Add all the properties of the array.
updatePayload = clearNestedProperty(
updatePayload,
prevProp[i],
validAttributes,
);
}
return updatePayload;
}
/**
* diffProperties takes two sets of props and a set of valid attributes
* and write to updatePayload the values that changed or were deleted.
* If no updatePayload is provided, a new one is created and returned if
* anything changed.
*/
function diffProperties(
updatePayload: null | Object,
prevProps: Object,
nextProps: Object,
validAttributes: AttributeConfiguration,
): null | Object {
let attributeConfig;
let nextProp;
let prevProp;
for (const propKey in nextProps) {
attributeConfig = validAttributes[propKey];
if (!attributeConfig) {
continue; // not a valid native prop
}
prevProp = prevProps[propKey];
nextProp = nextProps[propKey];
// functions are converted to booleans as markers that the associated
// events should be sent from native.
if (typeof nextProp === 'function') {
nextProp = (true: any);
// If nextProp is not a function, then don't bother changing prevProp
// since nextProp will win and go into the updatePayload regardless.
if (typeof prevProp === 'function') {
prevProp = (true: any);
}
}
// An explicit value of undefined is treated as a null because it overrides
// any other preceding value.
if (typeof nextProp === 'undefined') {
nextProp = (null: any);
if (typeof prevProp === 'undefined') {
prevProp = (null: any);
}
}
if (removedKeys) {
removedKeys[propKey] = false;
}
if (updatePayload && updatePayload[propKey] !== undefined) {
// Something else already triggered an update to this key because another
// value diffed. Since we're now later in the nested arrays our value is
// more important so we need to calculate it and override the existing
// value. It doesn't matter if nothing changed, we'll set it anyway.
// Pattern match on: attributeConfig
if (typeof attributeConfig !== 'object') {
// case: !Object is the default case
updatePayload[propKey] = nextProp;
} else if (
typeof attributeConfig.diff === 'function' ||
typeof attributeConfig.process === 'function'
) {
// case: CustomAttributeConfiguration
const nextValue =
typeof attributeConfig.process === 'function'
? attributeConfig.process(nextProp)
: nextProp;
updatePayload[propKey] = nextValue;
}
continue;
}
if (prevProp === nextProp) {
continue; // nothing changed
}
// Pattern match on: attributeConfig
if (typeof attributeConfig !== 'object') {
// case: !Object is the default case
if (defaultDiffer(prevProp, nextProp)) {
// a normal leaf has changed
(updatePayload || (updatePayload = ({}: {[string]: $FlowFixMe})))[
propKey
] = nextProp;
}
} else if (
typeof attributeConfig.diff === 'function' ||
typeof attributeConfig.process === 'function'
) {
// case: CustomAttributeConfiguration
const shouldUpdate =
prevProp === undefined ||
(typeof attributeConfig.diff === 'function'
? attributeConfig.diff(prevProp, nextProp)
: defaultDiffer(prevProp, nextProp));
if (shouldUpdate) {
const nextValue =
typeof attributeConfig.process === 'function'
? // $FlowFixMe[incompatible-use] found when upgrading Flow
attributeConfig.process(nextProp)
: nextProp;
(updatePayload || (updatePayload = ({}: {[string]: $FlowFixMe})))[
propKey
] = nextValue;
}
} else {
// default: fallthrough case when nested properties are defined
removedKeys = null;
removedKeyCount = 0;
// We think that attributeConfig is not CustomAttributeConfiguration at
// this point so we assume it must be AttributeConfiguration.
updatePayload = diffNestedProperty(
updatePayload,
prevProp,
nextProp,
((attributeConfig: any): AttributeConfiguration),
);
if (removedKeyCount > 0 && updatePayload) {
restoreDeletedValuesInNestedArray(
updatePayload,
nextProp,
((attributeConfig: any): AttributeConfiguration),
);
removedKeys = null;
}
}
}
// Also iterate through all the previous props to catch any that have been
// removed and make sure native gets the signal so it can reset them to the
// default.
for (const propKey in prevProps) {
if (nextProps[propKey] !== undefined) {
continue; // we've already covered this key in the previous pass
}
attributeConfig = validAttributes[propKey];
if (!attributeConfig) {
continue; // not a valid native prop
}
if (updatePayload && updatePayload[propKey] !== undefined) {
// This was already updated to a diff result earlier.
continue;
}
prevProp = prevProps[propKey];
if (prevProp === undefined) {
continue; // was already empty anyway
}
// Pattern match on: attributeConfig
if (
typeof attributeConfig !== 'object' ||
typeof attributeConfig.diff === 'function' ||
typeof attributeConfig.process === 'function'
) {
// case: CustomAttributeConfiguration | !Object
// Flag the leaf property for removal by sending a sentinel.
(updatePayload || (updatePayload = ({}: {[string]: $FlowFixMe})))[
propKey
] = null;
if (!removedKeys) {
removedKeys = ({}: {[string]: boolean});
}
if (!removedKeys[propKey]) {
removedKeys[propKey] = true;
removedKeyCount++;
}
} else {
// default:
// This is a nested attribute configuration where all the properties
// were removed so we need to go through and clear out all of them.
updatePayload = clearNestedProperty(
updatePayload,
prevProp,
((attributeConfig: any): AttributeConfiguration),
);
}
}
return updatePayload;
}
/**
* addProperties adds all the valid props to the payload after being processed.
*/
function addProperties(
updatePayload: null | Object,
props: Object,
validAttributes: AttributeConfiguration,
): null | Object {
// TODO: Fast path
return diffProperties(updatePayload, emptyObject, props, validAttributes);
}
/**
* clearProperties clears all the previous props by adding a null sentinel
* to the payload for each valid key.
*/
function clearProperties(
updatePayload: null | Object,
prevProps: Object,
validAttributes: AttributeConfiguration,
): null | Object {
// TODO: Fast path
return diffProperties(updatePayload, prevProps, emptyObject, validAttributes);
}
export function create(
props: Object,
validAttributes: AttributeConfiguration,
): null | Object {
return addProperties(
null, // updatePayload
props,
validAttributes,
);
}
export function diff(
prevProps: Object,
nextProps: Object,
validAttributes: AttributeConfiguration,
): null | Object {
return diffProperties(
null, // updatePayload
prevProps,
nextProps,
validAttributes,
);
}
| 27.549696 | 80 | 0.65184 |
null | const path = require('path')
// Theme API.
module.exports = (options, ctx) => {
const { themeConfig, siteConfig } = ctx
// resolve algolia
const isAlgoliaSearch = (
themeConfig.algolia
|| Object
.keys(siteConfig.locales && themeConfig.locales || {})
.some(base => themeConfig.locales[base].algolia)
)
const enableSmoothScroll = themeConfig.smoothScroll === true
return {
alias () {
return {
'@AlgoliaSearchBox': isAlgoliaSearch
? path.resolve(__dirname, 'components/AlgoliaSearchBox.vue')
: path.resolve(__dirname, 'noopModule.js')
}
},
plugins: [
['@vuepress/active-header-links', options.activeHeaderLinks],
'@vuepress/search',
'@vuepress/plugin-nprogress',
['container', {
type: 'tip',
defaultTitle: {
'/': 'TIP',
'/zh/': '提示'
}
}],
['container', {
type: 'warning',
defaultTitle: {
'/': 'WARNING',
'/zh/': '注意'
}
}],
['container', {
type: 'danger',
defaultTitle: {
'/': 'WARNING',
'/zh/': '警告'
}
}],
['container', {
type: 'details',
before: info => `<details class="custom-block details">${info ? `<summary>${info}</summary>` : ''}\n`,
after: () => '</details>\n'
}],
['smooth-scroll', enableSmoothScroll]
]
}
}
| 23.05 | 110 | 0.504854 |
owtf | import TestCase from '../../TestCase';
import HitBox from './hit-box';
const React = window.React;
class Persistence extends React.Component {
state = {
persisted: 0,
pooled: [],
};
addPersisted = event => {
let {persisted, pooled} = this.state;
event.persist();
if (event.type === 'mousemove') {
this.setState({
persisted: persisted + 1,
pooled: pooled.filter(e => e !== event),
});
}
};
addPooled = event => {
let {pooled} = this.state;
if (event.type === 'mousemove' && pooled.indexOf(event) === -1) {
this.setState({pooled: pooled.concat(event)});
}
};
render() {
const {pooled, persisted} = this.state;
return (
<TestCase title="Persistence" description="">
<TestCase.Steps>
<li>Mouse over the pooled event box</li>
<li>Mouse over the persisted event box</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The pool size should not increase above 1, but reduce to 0 when
hovering over the persisted region.
</TestCase.ExpectedResult>
<h2>Add Pooled Event:</h2>
<HitBox onMouseMove={this.addPooled} />
<h2>Add Persisted Event:</h2>
<HitBox onMouseMove={this.addPersisted} />
<p>Pool size: {pooled.length}</p>
<p>Persisted size: {persisted}</p>
</TestCase>
);
}
}
export default Persistence;
| 21.825397 | 73 | 0.580376 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export type BoxStyle = $ReadOnly<{
bottom: number,
left: number,
right: number,
top: number,
}>;
export type Layout = {
x: number,
y: number,
width: number,
height: number,
left: number,
top: number,
margin: BoxStyle,
padding: BoxStyle,
};
export type Style = Object;
export type StyleAndLayout = {
id: number,
style: Style | null,
layout: Layout | null,
};
| 16.028571 | 66 | 0.658824 |
Python-for-Offensive-PenTest | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import styles from './NoCommitData.css';
export default function NoCommitData(_: {}): React.Node {
return (
<div className={styles.NoCommitData}>
<div className={styles.Header}>
There is no data matching the current filter criteria.
</div>
<div className={styles.FilterMessage}>
Try adjusting the commit filter in Profiler settings.
</div>
</div>
);
}
| 23.730769 | 66 | 0.661994 |
null | /**
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import ReactCurrentCache from './ReactCurrentCache';
const UNTERMINATED = 0;
const TERMINATED = 1;
const ERRORED = 2;
type UnterminatedCacheNode<T> = {
s: 0,
v: void,
o: null | WeakMap<Function | Object, CacheNode<T>>,
p: null | Map<string | number | null | void | symbol | boolean, CacheNode<T>>,
};
type TerminatedCacheNode<T> = {
s: 1,
v: T,
o: null | WeakMap<Function | Object, CacheNode<T>>,
p: null | Map<string | number | null | void | symbol | boolean, CacheNode<T>>,
};
type ErroredCacheNode<T> = {
s: 2,
v: mixed,
o: null | WeakMap<Function | Object, CacheNode<T>>,
p: null | Map<string | number | null | void | symbol | boolean, CacheNode<T>>,
};
type CacheNode<T> =
| TerminatedCacheNode<T>
| UnterminatedCacheNode<T>
| ErroredCacheNode<T>;
function createCacheRoot<T>(): WeakMap<Function | Object, CacheNode<T>> {
return new WeakMap();
}
function createCacheNode<T>(): CacheNode<T> {
return {
s: UNTERMINATED, // status, represents whether the cached computation returned a value or threw an error
v: undefined, // value, either the cached result or an error, depending on s
o: null, // object cache, a WeakMap where non-primitive arguments are stored
p: null, // primitive cache, a regular Map where primitive arguments are stored.
};
}
export function cache<A: Iterable<mixed>, T>(fn: (...A) => T): (...A) => T {
return function () {
const dispatcher = ReactCurrentCache.current;
if (!dispatcher) {
// If there is no dispatcher, then we treat this as not being cached.
// $FlowFixMe[incompatible-call]: We don't want to use rest arguments since we transpile the code.
return fn.apply(null, arguments);
}
const fnMap: WeakMap<any, CacheNode<T>> = dispatcher.getCacheForType(
createCacheRoot,
);
const fnNode = fnMap.get(fn);
let cacheNode: CacheNode<T>;
if (fnNode === undefined) {
cacheNode = createCacheNode();
fnMap.set(fn, cacheNode);
} else {
cacheNode = fnNode;
}
for (let i = 0, l = arguments.length; i < l; i++) {
const arg = arguments[i];
if (
typeof arg === 'function' ||
(typeof arg === 'object' && arg !== null)
) {
// Objects go into a WeakMap
let objectCache = cacheNode.o;
if (objectCache === null) {
cacheNode.o = objectCache = new WeakMap();
}
const objectNode = objectCache.get(arg);
if (objectNode === undefined) {
cacheNode = createCacheNode();
objectCache.set(arg, cacheNode);
} else {
cacheNode = objectNode;
}
} else {
// Primitives go into a regular Map
let primitiveCache = cacheNode.p;
if (primitiveCache === null) {
cacheNode.p = primitiveCache = new Map();
}
const primitiveNode = primitiveCache.get(arg);
if (primitiveNode === undefined) {
cacheNode = createCacheNode();
primitiveCache.set(arg, cacheNode);
} else {
cacheNode = primitiveNode;
}
}
}
if (cacheNode.s === TERMINATED) {
return cacheNode.v;
}
if (cacheNode.s === ERRORED) {
throw cacheNode.v;
}
try {
// $FlowFixMe[incompatible-call]: We don't want to use rest arguments since we transpile the code.
const result = fn.apply(null, arguments);
const terminatedNode: TerminatedCacheNode<T> = (cacheNode: any);
terminatedNode.s = TERMINATED;
terminatedNode.v = result;
return result;
} catch (error) {
// We store the first error that's thrown and rethrow it.
const erroredNode: ErroredCacheNode<T> = (cacheNode: any);
erroredNode.s = ERRORED;
erroredNode.v = error;
throw error;
}
};
}
| 30.093023 | 108 | 0.616209 |
Effective-Python-Penetration-Testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import {useCallback, useContext, useSyncExternalStore} from 'react';
import {TreeDispatcherContext, TreeStateContext} from './TreeContext';
import {BridgeContext, StoreContext, OptionsContext} from '../context';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import Icon from '../Icon';
import {ModalDialogContext} from '../ModalDialog';
import ViewElementSourceContext from './ViewElementSourceContext';
import Toggle from '../Toggle';
import {ElementTypeSuspense} from 'react-devtools-shared/src/frontend/types';
import CannotSuspendWarningMessage from './CannotSuspendWarningMessage';
import InspectedElementView from './InspectedElementView';
import {InspectedElementContext} from './InspectedElementContext';
import {getOpenInEditorURL} from '../../../utils';
import {LOCAL_STORAGE_OPEN_IN_EDITOR_URL} from '../../../constants';
import styles from './InspectedElement.css';
import type {InspectedElement} from 'react-devtools-shared/src/frontend/types';
export type Props = {};
// TODO Make edits and deletes also use transition API!
export default function InspectedElementWrapper(_: Props): React.Node {
const {inspectedElementID} = useContext(TreeStateContext);
const dispatch = useContext(TreeDispatcherContext);
const {canViewElementSourceFunction, viewElementSourceFunction} = useContext(
ViewElementSourceContext,
);
const bridge = useContext(BridgeContext);
const store = useContext(StoreContext);
const {
hideToggleErrorAction,
hideToggleSuspenseAction,
hideLogAction,
hideViewSourceAction,
} = useContext(OptionsContext);
const {dispatch: modalDialogDispatch} = useContext(ModalDialogContext);
const {hookNames, inspectedElement, parseHookNames, toggleParseHookNames} =
useContext(InspectedElementContext);
const element =
inspectedElementID !== null
? store.getElementByID(inspectedElementID)
: null;
const highlightElement = useCallback(() => {
if (element !== null && inspectedElementID !== null) {
const rendererID = store.getRendererIDForElement(inspectedElementID);
if (rendererID !== null) {
bridge.send('highlightNativeElement', {
displayName: element.displayName,
hideAfterTimeout: true,
id: inspectedElementID,
openNativeElementsPanel: true,
rendererID,
scrollIntoView: true,
});
}
}
}, [bridge, element, inspectedElementID, store]);
const logElement = useCallback(() => {
if (inspectedElementID !== null) {
const rendererID = store.getRendererIDForElement(inspectedElementID);
if (rendererID !== null) {
bridge.send('logElementToConsole', {
id: inspectedElementID,
rendererID,
});
}
}
}, [bridge, inspectedElementID, store]);
const viewSource = useCallback(() => {
if (viewElementSourceFunction != null && inspectedElement !== null) {
viewElementSourceFunction(
inspectedElement.id,
((inspectedElement: any): InspectedElement),
);
}
}, [inspectedElement, viewElementSourceFunction]);
// In some cases (e.g. FB internal usage) the standalone shell might not be able to view the source.
// To detect this case, we defer to an injected helper function (if present).
const canViewSource =
inspectedElement !== null &&
inspectedElement.canViewSource &&
viewElementSourceFunction !== null &&
(canViewElementSourceFunction === null ||
canViewElementSourceFunction(inspectedElement));
const isErrored = inspectedElement != null && inspectedElement.isErrored;
const targetErrorBoundaryID =
inspectedElement != null ? inspectedElement.targetErrorBoundaryID : null;
const isSuspended =
element !== null &&
element.type === ElementTypeSuspense &&
inspectedElement != null &&
inspectedElement.state != null;
const canToggleError =
!hideToggleErrorAction &&
inspectedElement != null &&
inspectedElement.canToggleError;
const canToggleSuspense =
!hideToggleSuspenseAction &&
inspectedElement != null &&
inspectedElement.canToggleSuspense;
const editorURL = useSyncExternalStore(
function subscribe(callback) {
window.addEventListener(LOCAL_STORAGE_OPEN_IN_EDITOR_URL, callback);
return function unsubscribe() {
window.removeEventListener(LOCAL_STORAGE_OPEN_IN_EDITOR_URL, callback);
};
},
function getState() {
return getOpenInEditorURL();
},
);
const canOpenInEditor =
editorURL && inspectedElement != null && inspectedElement.source != null;
const toggleErrored = useCallback(() => {
if (inspectedElement == null || targetErrorBoundaryID == null) {
return;
}
const rendererID = store.getRendererIDForElement(targetErrorBoundaryID);
if (rendererID !== null) {
if (targetErrorBoundaryID !== inspectedElement.id) {
// Update tree selection so that if we cause a component to error,
// the nearest error boundary will become the newly selected thing.
dispatch({
type: 'SELECT_ELEMENT_BY_ID',
payload: targetErrorBoundaryID,
});
}
// Toggle error.
bridge.send('overrideError', {
id: targetErrorBoundaryID,
rendererID,
forceError: !isErrored,
});
}
}, [bridge, dispatch, isErrored, targetErrorBoundaryID]);
// TODO (suspense toggle) Would be nice to eventually use a two setState pattern here as well.
const toggleSuspended = useCallback(() => {
let nearestSuspenseElement = null;
let currentElement = element;
while (currentElement !== null) {
if (currentElement.type === ElementTypeSuspense) {
nearestSuspenseElement = currentElement;
break;
} else if (currentElement.parentID > 0) {
currentElement = store.getElementByID(currentElement.parentID);
} else {
currentElement = null;
}
}
// If we didn't find a Suspense ancestor, we can't suspend.
// Instead we can show a warning to the user.
if (nearestSuspenseElement === null) {
modalDialogDispatch({
id: 'InspectedElement',
type: 'SHOW',
content: <CannotSuspendWarningMessage />,
});
} else {
const nearestSuspenseElementID = nearestSuspenseElement.id;
// If we're suspending from an arbitrary (non-Suspense) component, select the nearest Suspense element in the Tree.
// This way when the fallback UI is shown and the current element is hidden, something meaningful is selected.
if (nearestSuspenseElement !== element) {
dispatch({
type: 'SELECT_ELEMENT_BY_ID',
payload: nearestSuspenseElementID,
});
}
const rendererID = store.getRendererIDForElement(
nearestSuspenseElementID,
);
// Toggle suspended
if (rendererID !== null) {
bridge.send('overrideSuspense', {
id: nearestSuspenseElementID,
rendererID,
forceFallback: !isSuspended,
});
}
}
}, [bridge, dispatch, element, isSuspended, modalDialogDispatch, store]);
const onOpenInEditor = useCallback(() => {
const source = inspectedElement?.source;
if (source == null || editorURL == null) {
return;
}
const url = new URL(editorURL);
url.href = url.href
.replace('{path}', source.fileName)
.replace('{line}', String(source.lineNumber))
.replace('%7Bpath%7D', source.fileName)
.replace('%7Bline%7D', String(source.lineNumber));
window.open(url);
}, [inspectedElement, editorURL]);
if (element === null) {
return (
<div className={styles.InspectedElement}>
<div className={styles.TitleRow} />
</div>
);
}
let strictModeBadge = null;
if (element.isStrictModeNonCompliant) {
strictModeBadge = (
<a
className={styles.StrictModeNonCompliant}
href="https://react.dev/reference/react/StrictMode"
rel="noopener noreferrer"
target="_blank"
title="This component is not running in StrictMode. Click to learn more.">
<Icon type="strict-mode-non-compliant" />
</a>
);
}
return (
<div className={styles.InspectedElement}>
<div className={styles.TitleRow} data-testname="InspectedElement-Title">
{strictModeBadge}
{element.key && (
<>
<div className={styles.Key} title={`key "${element.key}"`}>
{element.key}
</div>
<div className={styles.KeyArrow} />
</>
)}
<div className={styles.SelectedComponentName}>
<div
className={
element.isStrictModeNonCompliant
? styles.StrictModeNonCompliant
: styles.Component
}
title={element.displayName}>
{element.displayName}
</div>
</div>
{canOpenInEditor && (
<Button onClick={onOpenInEditor} title="Open in editor">
<ButtonIcon type="editor" />
</Button>
)}
{canToggleError && (
<Toggle
isChecked={isErrored}
onChange={toggleErrored}
title={
isErrored
? 'Clear the forced error'
: 'Force the selected component into an errored state'
}>
<ButtonIcon type="error" />
</Toggle>
)}
{canToggleSuspense && (
<Toggle
isChecked={isSuspended}
onChange={toggleSuspended}
title={
isSuspended
? 'Unsuspend the selected component'
: 'Suspend the selected component'
}>
<ButtonIcon type="suspend" />
</Toggle>
)}
{store.supportsNativeInspection && (
<Button
onClick={highlightElement}
title="Inspect the matching DOM element">
<ButtonIcon type="view-dom" />
</Button>
)}
{!hideLogAction && (
<Button
onClick={logElement}
title="Log this component data to the console">
<ButtonIcon type="log-data" />
</Button>
)}
{!hideViewSourceAction && (
<Button
disabled={!canViewSource}
onClick={viewSource}
title="View source for this element">
<ButtonIcon type="view-source" />
</Button>
)}
</div>
{inspectedElement === null && (
<div className={styles.Loading}>Loading...</div>
)}
{inspectedElement !== null && (
<InspectedElementView
key={
inspectedElementID /* Force reset when selected Element changes */
}
element={element}
hookNames={hookNames}
inspectedElement={inspectedElement}
parseHookNames={parseHookNames}
toggleParseHookNames={toggleParseHookNames}
/>
)}
</div>
);
}
| 31.444126 | 121 | 0.628511 |
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
*/
/* eslint-disable no-for-of-loops/no-for-of-loops */
'use strict';
let React;
let ReactDOM;
let ReactFreshRuntime;
let act;
const babel = require('@babel/core');
const freshPlugin = require('react-refresh/babel');
const ts = require('typescript');
describe('ReactFreshIntegration', () => {
let container;
let exportsObj;
beforeEach(() => {
if (__DEV__) {
jest.resetModules();
React = require('react');
ReactFreshRuntime = require('react-refresh/runtime');
ReactFreshRuntime.injectIntoGlobalHook(global);
ReactDOM = require('react-dom');
act = React.unstable_act;
container = document.createElement('div');
document.body.appendChild(container);
exportsObj = undefined;
}
});
afterEach(() => {
if (__DEV__) {
ReactDOM.unmountComponentAtNode(container);
// Ensure we don't leak memory by holding onto dead roots.
expect(ReactFreshRuntime._getMountedRootCount()).toBe(0);
document.body.removeChild(container);
}
});
function executeCommon(source, compileDestructuring) {
const compiled = babel.transform(source, {
babelrc: false,
presets: ['@babel/react'],
plugins: [
[freshPlugin, {skipEnvCheck: true}],
'@babel/plugin-transform-modules-commonjs',
compileDestructuring && '@babel/plugin-transform-destructuring',
].filter(Boolean),
}).code;
return executeCompiled(compiled);
}
function executeCompiled(compiled) {
exportsObj = {};
// eslint-disable-next-line no-new-func
new Function(
'global',
'React',
'exports',
'$RefreshReg$',
'$RefreshSig$',
compiled,
)(global, React, exportsObj, $RefreshReg$, $RefreshSig$);
// Module systems will register exports as a fallback.
// This is useful for cases when e.g. a class is exported,
// and we don't want to propagate the update beyond this module.
$RefreshReg$(exportsObj.default, 'exports.default');
return exportsObj.default;
}
function $RefreshReg$(type, id) {
ReactFreshRuntime.register(type, id);
}
function $RefreshSig$() {
return ReactFreshRuntime.createSignatureFunctionForTransform();
}
describe('with compiled destructuring', () => {
runTests(executeCommon, testCommon);
});
describe('without compiled destructuring', () => {
runTests(executeCommon, testCommon);
});
describe('with typescript syntax', () => {
runTests(function (source) {
const typescriptSource = babel.transform(source, {
babelrc: false,
configFile: false,
presets: ['@babel/react'],
plugins: [
[freshPlugin, {skipEnvCheck: true}],
['@babel/plugin-syntax-typescript', {isTSX: true}],
],
}).code;
const compiled = ts.transpileModule(typescriptSource, {
module: ts.ModuleKind.CommonJS,
}).outputText;
return executeCompiled(compiled);
}, testTypescript);
});
function runTests(execute, test) {
function render(source) {
const Component = execute(source);
act(() => {
ReactDOM.render(<Component />, container);
});
// Module initialization shouldn't be counted as a hot update.
expect(ReactFreshRuntime.performReactRefresh()).toBe(null);
}
function patch(source) {
const prevExports = exportsObj;
execute(source);
const nextExports = exportsObj;
// Check if exported families have changed.
// (In a real module system we'd do this for *all* exports.)
// For example, this can happen if you convert a class to a function.
// Or if you wrap something in a HOC.
const didExportsChange =
ReactFreshRuntime.getFamilyByType(prevExports.default) !==
ReactFreshRuntime.getFamilyByType(nextExports.default);
if (didExportsChange) {
// In a real module system, we would propagate such updates upwards,
// and re-execute modules that imported this one. (Just like if we edited them.)
// This makes adding/removing/renaming exports re-render references to them.
// Here, we'll just force a re-render using the newer type to emulate this.
const NextComponent = nextExports.default;
act(() => {
ReactDOM.render(<NextComponent />, container);
});
}
act(() => {
const result = ReactFreshRuntime.performReactRefresh();
if (!didExportsChange) {
// Normally we expect that some components got updated in our tests.
expect(result).not.toBe(null);
} else {
// However, we have tests where we convert functions to classes,
// and in those cases it's expected nothing would get updated.
// (Instead, the export change branch above would take care of it.)
}
});
expect(ReactFreshRuntime._getMountedRootCount()).toBe(1);
}
test(render, patch);
}
function testCommon(render, patch) {
it('reloads function declarations', () => {
if (__DEV__) {
render(`
function Parent() {
return <Child prop="A" />;
};
function Child({prop}) {
return <h1>{prop}1</h1>;
};
export default Parent;
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
function Parent() {
return <Child prop="B" />;
};
function Child({prop}) {
return <h1>{prop}2</h1>;
};
export default Parent;
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
}
});
it('reloads arrow functions', () => {
if (__DEV__) {
render(`
const Parent = () => {
return <Child prop="A" />;
};
const Child = ({prop}) => {
return <h1>{prop}1</h1>;
};
export default Parent;
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const Parent = () => {
return <Child prop="B" />;
};
const Child = ({prop}) => {
return <h1>{prop}2</h1>;
};
export default Parent;
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
}
});
it('reloads a combination of memo and forwardRef', () => {
if (__DEV__) {
render(`
const {memo} = React;
const Parent = memo(React.forwardRef(function (props, ref) {
return <Child prop="A" ref={ref} />;
}));
const Child = React.memo(({prop}) => {
return <h1>{prop}1</h1>;
});
export default React.memo(Parent);
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {memo} = React;
const Parent = memo(React.forwardRef(function (props, ref) {
return <Child prop="B" ref={ref} />;
}));
const Child = React.memo(({prop}) => {
return <h1>{prop}2</h1>;
});
export default React.memo(Parent);
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
}
});
it('reloads default export with named memo', () => {
if (__DEV__) {
render(`
const {memo} = React;
const Child = React.memo(({prop}) => {
return <h1>{prop}1</h1>;
});
export default memo(React.forwardRef(function Parent(props, ref) {
return <Child prop="A" ref={ref} />;
}));
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {memo} = React;
const Child = React.memo(({prop}) => {
return <h1>{prop}2</h1>;
});
export default memo(React.forwardRef(function Parent(props, ref) {
return <Child prop="B" ref={ref} />;
}));
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
}
});
it('reloads HOCs if they return functions', () => {
if (__DEV__) {
render(`
function hoc(letter) {
return function() {
return <h1>{letter}1</h1>;
}
}
export default function Parent() {
return <Child />;
}
const Child = hoc('A');
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
function hoc(letter) {
return function() {
return <h1>{letter}2</h1>;
}
}
export default function Parent() {
return React.createElement(Child);
}
const Child = hoc('B');
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
}
});
it('resets state when renaming a state variable', () => {
if (__DEV__) {
render(`
const {useState} = React;
const S = 1;
export default function App() {
const [foo, setFoo] = useState(S);
return <h1>A{foo}</h1>;
}
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {useState} = React;
const S = 2;
export default function App() {
const [foo, setFoo] = useState(S);
return <h1>B{foo}</h1>;
}
`);
// Same state variable name, so state is preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
patch(`
const {useState} = React;
const S = 3;
export default function App() {
const [bar, setBar] = useState(S);
return <h1>C{bar}</h1>;
}
`);
// Different state variable name, so state is reset.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('C3');
}
});
it('resets state when renaming a state variable in a HOC', () => {
if (__DEV__) {
render(`
const {useState} = React;
const S = 1;
function hoc(Wrapped) {
return function Generated() {
const [foo, setFoo] = useState(S);
return <Wrapped value={foo} />;
};
}
export default hoc(({ value }) => {
return <h1>A{value}</h1>;
});
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {useState} = React;
const S = 2;
function hoc(Wrapped) {
return function Generated() {
const [foo, setFoo] = useState(S);
return <Wrapped value={foo} />;
};
}
export default hoc(({ value }) => {
return <h1>B{value}</h1>;
});
`);
// Same state variable name, so state is preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
patch(`
const {useState} = React;
const S = 3;
function hoc(Wrapped) {
return function Generated() {
const [bar, setBar] = useState(S);
return <Wrapped value={bar} />;
};
}
export default hoc(({ value }) => {
return <h1>C{value}</h1>;
});
`);
// Different state variable name, so state is reset.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('C3');
}
});
it('resets state when renaming a state variable in a HOC with indirection', () => {
if (__DEV__) {
render(`
const {useState} = React;
const S = 1;
function hoc(Wrapped) {
return function Generated() {
const [foo, setFoo] = useState(S);
return <Wrapped value={foo} />;
};
}
function Indirection({ value }) {
return <h1>A{value}</h1>;
}
export default hoc(Indirection);
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {useState} = React;
const S = 2;
function hoc(Wrapped) {
return function Generated() {
const [foo, setFoo] = useState(S);
return <Wrapped value={foo} />;
};
}
function Indirection({ value }) {
return <h1>B{value}</h1>;
}
export default hoc(Indirection);
`);
// Same state variable name, so state is preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
patch(`
const {useState} = React;
const S = 3;
function hoc(Wrapped) {
return function Generated() {
const [bar, setBar] = useState(S);
return <Wrapped value={bar} />;
};
}
function Indirection({ value }) {
return <h1>C{value}</h1>;
}
export default hoc(Indirection);
`);
// Different state variable name, so state is reset.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('C3');
}
});
it('resets state when renaming a state variable inside a HOC with direct call', () => {
if (__DEV__) {
render(`
const {useState} = React;
const S = 1;
function hocWithDirectCall(Wrapped) {
return function Generated() {
return Wrapped();
};
}
export default hocWithDirectCall(() => {
const [foo, setFoo] = useState(S);
return <h1>A{foo}</h1>;
});
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {useState} = React;
const S = 2;
function hocWithDirectCall(Wrapped) {
return function Generated() {
return Wrapped();
};
}
export default hocWithDirectCall(() => {
const [foo, setFoo] = useState(S);
return <h1>B{foo}</h1>;
});
`);
// Same state variable name, so state is preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
patch(`
const {useState} = React;
const S = 3;
function hocWithDirectCall(Wrapped) {
return function Generated() {
return Wrapped();
};
}
export default hocWithDirectCall(() => {
const [bar, setBar] = useState(S);
return <h1>C{bar}</h1>;
});
`);
// Different state variable name, so state is reset.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('C3');
}
});
it('does not crash when changing Hook order inside a HOC with direct call', () => {
if (__DEV__) {
render(`
const {useEffect} = React;
function hocWithDirectCall(Wrapped) {
return function Generated() {
return Wrapped();
};
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
return <h1>A</h1>;
});
`);
const el = container.firstChild;
expect(el.textContent).toBe('A');
patch(`
const {useEffect} = React;
function hocWithDirectCall(Wrapped) {
return function Generated() {
return Wrapped();
};
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
useEffect(() => {}, []);
return <h1>B</h1>;
});
`);
// Hook order changed, so we remount.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('B');
}
});
it('does not crash when changing Hook order inside a memo-ed HOC with direct call', () => {
if (__DEV__) {
render(`
const {useEffect, memo} = React;
function hocWithDirectCall(Wrapped) {
return memo(function Generated() {
return Wrapped();
});
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
return <h1>A</h1>;
});
`);
const el = container.firstChild;
expect(el.textContent).toBe('A');
patch(`
const {useEffect, memo} = React;
function hocWithDirectCall(Wrapped) {
return memo(function Generated() {
return Wrapped();
});
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
useEffect(() => {}, []);
return <h1>B</h1>;
});
`);
// Hook order changed, so we remount.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('B');
}
});
it('does not crash when changing Hook order inside a memo+forwardRef-ed HOC with direct call', () => {
if (__DEV__) {
render(`
const {useEffect, memo, forwardRef} = React;
function hocWithDirectCall(Wrapped) {
return memo(forwardRef(function Generated() {
return Wrapped();
}));
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
return <h1>A</h1>;
});
`);
const el = container.firstChild;
expect(el.textContent).toBe('A');
patch(`
const {useEffect, memo, forwardRef} = React;
function hocWithDirectCall(Wrapped) {
return memo(forwardRef(function Generated() {
return Wrapped();
}));
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
useEffect(() => {}, []);
return <h1>B</h1>;
});
`);
// Hook order changed, so we remount.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('B');
}
});
it('does not crash when changing Hook order inside a HOC returning an object', () => {
if (__DEV__) {
render(`
const {useEffect} = React;
function hocWithDirectCall(Wrapped) {
return {Wrapped: Wrapped};
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
return <h1>A</h1>;
}).Wrapped;
`);
const el = container.firstChild;
expect(el.textContent).toBe('A');
patch(`
const {useEffect} = React;
function hocWithDirectCall(Wrapped) {
return {Wrapped: Wrapped};
}
export default hocWithDirectCall(() => {
useEffect(() => {}, []);
useEffect(() => {}, []);
return <h1>B</h1>;
}).Wrapped;
`);
// Hook order changed, so we remount.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('B');
}
});
it('resets effects while preserving state', () => {
if (__DEV__) {
render(`
const {useState} = React;
export default function App() {
const [value, setValue] = useState(0);
return <h1>A{value}</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A0');
// Add an effect.
patch(`
const {useState} = React;
export default function App() {
const [value, setValue] = useState(0);
React.useEffect(() => {
const id = setInterval(() => {
setValue(v => v + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>B{value}</h1>;
}
`);
// We added an effect, thereby changing Hook order.
// This causes a remount.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('B0');
act(() => {
jest.advanceTimersByTime(1000);
});
expect(el.textContent).toBe('B1');
patch(`
const {useState} = React;
export default function App() {
const [value, setValue] = useState(0);
React.useEffect(() => {
const id = setInterval(() => {
setValue(v => v + 10);
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>C{value}</h1>;
}
`);
// Same Hooks are called, so state is preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('C1');
// Effects are always reset, so timer was reinstalled.
// The new version increments by 10 rather than 1.
act(() => {
jest.advanceTimersByTime(1000);
});
expect(el.textContent).toBe('C11');
patch(`
const {useState} = React;
export default function App() {
const [value, setValue] = useState(0);
return <h1>D{value}</h1>;
}
`);
// Removing the effect changes the signature
// and causes the component to remount.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('D0');
}
});
it('does not get confused when custom hooks are reordered', () => {
if (__DEV__) {
render(`
function useFancyState(initialState) {
return React.useState(initialState);
}
const App = () => {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>A{x}{y}</h1>;
};
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AXY');
patch(`
function useFancyState(initialState) {
return React.useState(initialState);
}
const App = () => {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>B{x}{y}</h1>;
};
export default App;
`);
// Same state variables, so no remount.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('BXY');
patch(`
function useFancyState(initialState) {
return React.useState(initialState);
}
const App = () => {
const [y, setY] = useFancyState('Y');
const [x, setX] = useFancyState('X');
return <h1>B{x}{y}</h1>;
};
export default App;
`);
// Hooks were re-ordered. This causes a remount.
// Therefore, Hook calls don't accidentally share state.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('BXY');
}
});
it('does not get confused when component is called early', () => {
if (__DEV__) {
render(`
// This isn't really a valid pattern but it's close enough
// to simulate what happens when you call ReactDOM.render
// in the same file. We want to ensure this doesn't confuse
// the runtime.
App();
function App() {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>A{x}{y}</h1>;
};
function useFancyState(initialState) {
// No real Hook calls to avoid triggering invalid call invariant.
// We only want to verify that we can still call this function early.
return initialState;
}
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AXY');
patch(`
// This isn't really a valid pattern but it's close enough
// to simulate what happens when you call ReactDOM.render
// in the same file. We want to ensure this doesn't confuse
// the runtime.
App();
function App() {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>B{x}{y}</h1>;
};
function useFancyState(initialState) {
// No real Hook calls to avoid triggering invalid call invariant.
// We only want to verify that we can still call this function early.
return initialState;
}
export default App;
`);
// Same state variables, so no remount.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('BXY');
patch(`
// This isn't really a valid pattern but it's close enough
// to simulate what happens when you call ReactDOM.render
// in the same file. We want to ensure this doesn't confuse
// the runtime.
App();
function App() {
const [y, setY] = useFancyState('Y');
const [x, setX] = useFancyState('X');
return <h1>B{x}{y}</h1>;
};
function useFancyState(initialState) {
// No real Hook calls to avoid triggering invalid call invariant.
// We only want to verify that we can still call this function early.
return initialState;
}
export default App;
`);
// Hooks were re-ordered. This causes a remount.
// Therefore, Hook calls don't accidentally share state.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('BXY');
}
});
it('does not get confused by Hooks defined inline', () => {
// This is not a recommended pattern but at least it shouldn't break.
if (__DEV__) {
render(`
const App = () => {
const useFancyState = (initialState) => {
const result = React.useState(initialState);
return result;
};
const [x, setX] = useFancyState('X1');
const [y, setY] = useFancyState('Y1');
return <h1>A{x}{y}</h1>;
};
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AX1Y1');
patch(`
const App = () => {
const useFancyState = (initialState) => {
const result = React.useState(initialState);
return result;
};
const [x, setX] = useFancyState('X2');
const [y, setY] = useFancyState('Y2');
return <h1>B{x}{y}</h1>;
};
export default App;
`);
// Remount even though nothing changed because
// the custom Hook is inside -- and so we don't
// really know whether its signature has changed.
// We could potentially make it work, but for now
// let's assert we don't crash with confusing errors.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('BX2Y2');
}
});
it('remounts component if custom hook it uses changes order', () => {
if (__DEV__) {
render(`
const App = () => {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>A{x}{y}</h1>;
};
const useFancyState = (initialState) => {
const result = useIndirection(initialState);
return result;
};
function useIndirection(initialState) {
return React.useState(initialState);
}
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AXY');
patch(`
const App = () => {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>B{x}{y}</h1>;
};
const useFancyState = (initialState) => {
const result = useIndirection();
return result;
};
function useIndirection(initialState) {
return React.useState(initialState);
}
export default App;
`);
// We didn't change anything except the header text.
// So we don't expect a remount.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('BXY');
patch(`
const App = () => {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>C{x}{y}</h1>;
};
const useFancyState = (initialState) => {
const result = useIndirection(initialState);
return result;
};
function useIndirection(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
}
export default App;
`);
// The useIndirection Hook added an affect,
// so we had to remount the component.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('CXY');
patch(`
const App = () => {
const [x, setX] = useFancyState('X');
const [y, setY] = useFancyState('Y');
return <h1>D{x}{y}</h1>;
};
const useFancyState = (initialState) => {
const result = useIndirection();
return result;
};
function useIndirection(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
}
export default App;
`);
// We didn't change anything except the header text.
// So we don't expect a remount.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('DXY');
}
});
it('does not lose the inferred arrow names', () => {
if (__DEV__) {
render(`
const Parent = () => {
return <Child/>;
};
const Child = () => {
useMyThing();
return <h1>{Parent.name} {Child.name} {useMyThing.name}</h1>;
};
const useMyThing = () => {
React.useState();
};
export default Parent;
`);
expect(container.textContent).toBe('Parent Child useMyThing');
}
});
it('does not lose the inferred function names', () => {
if (__DEV__) {
render(`
var Parent = function() {
return <Child/>;
};
var Child = function() {
useMyThing();
return <h1>{Parent.name} {Child.name} {useMyThing.name}</h1>;
};
var useMyThing = function() {
React.useState();
};
export default Parent;
`);
expect(container.textContent).toBe('Parent Child useMyThing');
}
});
it('resets state on every edit with @refresh reset annotation', () => {
if (__DEV__) {
render(`
const {useState} = React;
const S = 1;
export default function App() {
const [foo, setFoo] = useState(S);
return <h1>A{foo}</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {useState} = React;
const S = 2;
export default function App() {
const [foo, setFoo] = useState(S);
return <h1>B{foo}</h1>;
}
`);
// Same state variable name, so state is preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
patch(`
const {useState} = React;
const S = 3;
/* @refresh reset */
export default function App() {
const [foo, setFoo] = useState(S);
return <h1>C{foo}</h1>;
}
`);
// Found remount annotation, so state is reset.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C3');
patch(`
const {useState} = React;
const S = 4;
export default function App() {
// @refresh reset
const [foo, setFoo] = useState(S);
return <h1>D{foo}</h1>;
}
`);
// Found remount annotation, so state is reset.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('D4');
patch(`
const {useState} = React;
const S = 5;
export default function App() {
const [foo, setFoo] = useState(S);
return <h1>E{foo}</h1>;
}
`);
// There is no remount annotation anymore,
// so preserve the previous state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('E4');
patch(`
const {useState} = React;
const S = 6;
export default function App() {
const [foo, setFoo] = useState(S);
return <h1>F{foo}</h1>;
}
`);
// Continue editing.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('F4');
patch(`
const {useState} = React;
const S = 7;
export default function App() {
/* @refresh reset */
const [foo, setFoo] = useState(S);
return <h1>G{foo}</h1>;
}
`);
// Force remount one last time.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('G7');
}
});
// This is best effort for simple cases.
// We won't attempt to resolve identifiers.
it('resets state when useState initial state is edited', () => {
if (__DEV__) {
render(`
const {useState} = React;
export default function App() {
const [foo, setFoo] = useState(1);
return <h1>A{foo}</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {useState} = React;
export default function App() {
const [foo, setFoo] = useState(1);
return <h1>B{foo}</h1>;
}
`);
// Same initial state, so it's preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
patch(`
const {useState} = React;
export default function App() {
const [foo, setFoo] = useState(2);
return <h1>C{foo}</h1>;
}
`);
// Different initial state, so state is reset.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C2');
}
});
// This is best effort for simple cases.
// We won't attempt to resolve identifiers.
it('resets state when useReducer initial state is edited', () => {
if (__DEV__) {
render(`
const {useReducer} = React;
export default function App() {
const [foo, setFoo] = useReducer(x => x, 1);
return <h1>A{foo}</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
const {useReducer} = React;
export default function App() {
const [foo, setFoo] = useReducer(x => x, 1);
return <h1>B{foo}</h1>;
}
`);
// Same initial state, so it's preserved.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B1');
patch(`
const {useReducer} = React;
export default function App() {
const [foo, setFoo] = useReducer(x => x, 2);
return <h1>C{foo}</h1>;
}
`);
// Different initial state, so state is reset.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C2');
}
});
it('remounts when switching export from function to class', () => {
if (__DEV__) {
render(`
export default function App() {
return <h1>A1</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
export default function App() {
return <h1>A2</h1>;
}
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('A2');
patch(`
export default class App extends React.Component {
render() {
return <h1>B1</h1>
}
}
`);
// Reset (function -> class).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('B1');
patch(`
export default class App extends React.Component {
render() {
return <h1>B2</h1>
}
}
`);
// Reset (classes always do).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('B2');
patch(`
export default function App() {
return <h1>C1</h1>;
}
`);
// Reset (class -> function).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C1');
patch(`
export default function App() {
return <h1>C2</h1>;
}
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('C2');
patch(`
export default function App() {
return <h1>D1</h1>;
}
`);
el = container.firstChild;
expect(el.textContent).toBe('D1');
patch(`
export default function App() {
return <h1>D2</h1>;
}
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('D2');
}
});
it('remounts when switching export from class to function', () => {
if (__DEV__) {
render(`
export default class App extends React.Component {
render() {
return <h1>A1</h1>
}
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
export default class App extends React.Component {
render() {
return <h1>A2</h1>
}
}
`);
// Reset (classes always do).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('A2');
patch(`
export default function App() {
return <h1>B1</h1>;
}
`);
// Reset (class -> function).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('B1');
patch(`
export default function App() {
return <h1>B2</h1>;
}
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
patch(`
export default class App extends React.Component {
render() {
return <h1>C1</h1>
}
}
`);
// Reset (function -> class).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C1');
}
});
it('remounts when wrapping export in a HOC', () => {
if (__DEV__) {
render(`
export default function App() {
return <h1>A1</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
export default function App() {
return <h1>A2</h1>;
}
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('A2');
patch(`
function hoc(Inner) {
return function Wrapper() {
return <Inner />;
}
}
function App() {
return <h1>B1</h1>;
}
export default hoc(App);
`);
// Reset (wrapped in HOC).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('B1');
patch(`
function hoc(Inner) {
return function Wrapper() {
return <Inner />;
}
}
function App() {
return <h1>B2</h1>;
}
export default hoc(App);
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
patch(`
export default function App() {
return <h1>C1</h1>;
}
`);
// Reset (unwrapped).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C1');
patch(`
export default function App() {
return <h1>C2</h1>;
}
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('C2');
}
});
it('remounts when wrapping export in memo()', () => {
if (__DEV__) {
render(`
export default function App() {
return <h1>A1</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
export default function App() {
return <h1>A2</h1>;
}
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('A2');
patch(`
function App() {
return <h1>B1</h1>;
}
export default React.memo(App);
`);
// Reset (wrapped in HOC).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('B1');
patch(`
function App() {
return <h1>B2</h1>;
}
export default React.memo(App);
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
patch(`
export default function App() {
return <h1>C1</h1>;
}
`);
// Reset (unwrapped).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C1');
patch(`
export default function App() {
return <h1>C2</h1>;
}
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('C2');
}
});
it('remounts when wrapping export in forwardRef()', () => {
if (__DEV__) {
render(`
export default function App() {
return <h1>A1</h1>;
}
`);
let el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
export default function App() {
return <h1>A2</h1>;
}
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('A2');
patch(`
function App() {
return <h1>B1</h1>;
}
export default React.forwardRef(App);
`);
// Reset (wrapped in HOC).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('B1');
patch(`
function App() {
return <h1>B2</h1>;
}
export default React.forwardRef(App);
`);
// Keep state.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
patch(`
export default function App() {
return <h1>C1</h1>;
}
`);
// Reset (unwrapped).
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('C1');
patch(`
export default function App() {
return <h1>C2</h1>;
}
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('C2');
}
});
if (!require('shared/ReactFeatureFlags').disableModulePatternComponents) {
it('remounts deprecated factory components', () => {
if (__DEV__) {
expect(() => {
render(`
function Parent() {
return {
render() {
return <Child prop="A" />;
}
};
};
function Child({prop}) {
return <h1>{prop}1</h1>;
};
export default Parent;
`);
}).toErrorDev(
'The <Parent /> component appears to be a function component ' +
'that returns a class instance.',
);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
function Parent() {
return {
render() {
return <Child prop="B" />;
}
};
};
function Child({prop}) {
return <h1>{prop}2</h1>;
};
export default Parent;
`);
// Like classes, factory components always remount.
expect(container.firstChild).not.toBe(el);
const newEl = container.firstChild;
expect(newEl.textContent).toBe('B2');
}
});
}
describe('with inline requires', () => {
beforeEach(() => {
global.FakeModuleSystem = {};
});
afterEach(() => {
delete global.FakeModuleSystem;
});
it('remounts component if custom hook it uses changes order on first edit', () => {
// This test verifies that remounting works even if calls to custom Hooks
// were transformed with an inline requires transform, like we have on RN.
// Inline requires make it harder to compare previous and next signatures
// because useFancyState inline require always resolves to the newest version.
// We're not actually using inline requires in the test, but it has similar semantics.
if (__DEV__) {
render(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>A{x}{y}</h1>;
};
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AXY');
patch(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>B{x}{y}</h1>;
};
export default App;
`);
// The useFancyState Hook added an effect,
// so we had to remount the component.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('BXY');
patch(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>C{x}{y}</h1>;
};
export default App;
`);
// We didn't change anything except the header text.
// So we don't expect a remount.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('CXY');
}
});
it('remounts component if custom hook it uses changes order on second edit', () => {
if (__DEV__) {
render(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>A{x}{y}</h1>;
};
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AXY');
patch(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>B{x}{y}</h1>;
};
export default App;
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('BXY');
patch(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>C{x}{y}</h1>;
};
export default App;
`);
// The useFancyState Hook added an effect,
// so we had to remount the component.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('CXY');
patch(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>D{x}{y}</h1>;
};
export default App;
`);
// We didn't change anything except the header text.
// So we don't expect a remount.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('DXY');
}
});
it('recovers if evaluating Hook list throws', () => {
if (__DEV__) {
render(`
let FakeModuleSystem = null;
global.FakeModuleSystem.useFancyState = function(initialState) {
return React.useState(initialState);
};
const App = () => {
FakeModuleSystem = global.FakeModuleSystem;
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>A{x}{y}</h1>;
};
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AXY');
patch(`
let FakeModuleSystem = null;
global.FakeModuleSystem.useFancyState = function(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
};
const App = () => {
FakeModuleSystem = global.FakeModuleSystem;
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>B{x}{y}</h1>;
};
export default App;
`);
// We couldn't evaluate the Hook signatures
// so we had to remount the component.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('BXY');
}
});
it('remounts component if custom hook it uses changes order behind an indirection', () => {
if (__DEV__) {
render(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
return FakeModuleSystem.useIndirection(initialState);
};
FakeModuleSystem.useIndirection = function(initialState) {
return FakeModuleSystem.useOtherIndirection(initialState);
};
FakeModuleSystem.useOtherIndirection = function(initialState) {
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>A{x}{y}</h1>;
};
export default App;
`);
let el = container.firstChild;
expect(el.textContent).toBe('AXY');
patch(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
return FakeModuleSystem.useIndirection(initialState);
};
FakeModuleSystem.useIndirection = function(initialState) {
return FakeModuleSystem.useOtherIndirection(initialState);
};
FakeModuleSystem.useOtherIndirection = function(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>B{x}{y}</h1>;
};
export default App;
`);
// The useFancyState Hook added an effect,
// so we had to remount the component.
expect(container.firstChild).not.toBe(el);
el = container.firstChild;
expect(el.textContent).toBe('BXY');
patch(`
const FakeModuleSystem = global.FakeModuleSystem;
FakeModuleSystem.useFancyState = function(initialState) {
return FakeModuleSystem.useIndirection(initialState);
};
FakeModuleSystem.useIndirection = function(initialState) {
return FakeModuleSystem.useOtherIndirection(initialState);
};
FakeModuleSystem.useOtherIndirection = function(initialState) {
React.useEffect(() => {});
return React.useState(initialState);
};
const App = () => {
const [x, setX] = FakeModuleSystem.useFancyState('X');
const [y, setY] = FakeModuleSystem.useFancyState('Y');
return <h1>C{x}{y}</h1>;
};
export default App;
`);
// We didn't change anything except the header text.
// So we don't expect a remount.
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('CXY');
}
});
});
}
function testTypescript(render, patch) {
it('reloads component exported in typescript namespace', () => {
if (__DEV__) {
render(`
namespace Foo {
export namespace Bar {
export const Child = ({prop}) => {
return <h1>{prop}1</h1>
};
}
}
export default function Parent() {
return <Foo.Bar.Child prop={'A'} />;
}
`);
const el = container.firstChild;
expect(el.textContent).toBe('A1');
patch(`
namespace Foo {
export namespace Bar {
export const Child = ({prop}) => {
return <h1>{prop}2</h1>
};
}
}
export default function Parent() {
return <Foo.Bar.Child prop={'B'} />;
}
`);
expect(container.firstChild).toBe(el);
expect(el.textContent).toBe('B2');
}
});
}
});
| 28.437717 | 106 | 0.504232 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.