import type {
Thenable,
ReactDebugInfo,
ReactDebugInfoEntry,
ReactComponentInfo,
ReactAsyncInfo,
ReactIOInfo,
ReactStackTrace,
ReactFunctionLocation,
ReactErrorInfoDev,
} from 'shared/ReactTypes';
import type {LazyComponent} from 'react/src/ReactLazy';
import type {
ClientReference,
ClientReferenceMetadata,
ServerConsumerModuleMap,
ServerManifest,
StringDecoder,
ModuleLoading,
} from './ReactFlightClientConfig';
import type {
HintCode,
HintModel,
} from 'react-server/src/ReactFlightServerConfig';
import type {
CallServerCallback,
EncodeFormActionCallback,
} from './ReactFlightReplyClient';
import type {TemporaryReferenceSet} from './ReactFlightTemporaryReferences';
import {
enableProfilerTimer,
enableComponentPerformanceTrack,
enableAsyncDebugInfo,
} from 'shared/ReactFeatureFlags';
import {
resolveClientReference,
resolveServerReference,
preloadModule,
requireModule,
getModuleDebugInfo,
dispatchHint,
readPartialStringChunk,
readFinalStringChunk,
createStringDecoder,
prepareDestinationForModule,
bindToConsole,
rendererVersion,
rendererPackageName,
checkEvalAvailabilityOnceDev,
} from './ReactFlightClientConfig';
import {
createBoundServerReference,
registerBoundServerReference,
} from './ReactFlightReplyClient';
import {readTemporaryReference} from './ReactFlightTemporaryReferences';
import {
markAllTracksInOrder,
logComponentRender,
logDedupedComponentRender,
logComponentAborted,
logComponentErrored,
logIOInfo,
logIOInfoErrored,
logComponentAwait,
logComponentAwaitAborted,
logComponentAwaitErrored,
} from './ReactFlightPerformanceTrack';
import {
REACT_LAZY_TYPE,
REACT_ELEMENT_TYPE,
ASYNC_ITERATOR,
REACT_FRAGMENT_TYPE,
} from 'shared/ReactSymbols';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import {getOwnerStackByComponentInfoInDev} from 'shared/ReactComponentInfoStack';
import hasOwnProperty from 'shared/hasOwnProperty';
import {injectInternals} from './ReactFlightClientDevToolsHook';
import {OMITTED_PROP_ERROR} from 'shared/ReactFlightPropertyAccess';
import ReactVersion from 'shared/ReactVersion';
import isArray from 'shared/isArray';
import * as React from 'react';
import type {SharedStateServer} from 'react/src/ReactSharedInternalsServer';
import type {SharedStateClient} from 'react/src/ReactSharedInternalsClient';
const ReactSharedInteralsServer: void | SharedStateServer = (React: any)
.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
const ReactSharedInternals: SharedStateServer | SharedStateClient =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE ||
ReactSharedInteralsServer;
export type {CallServerCallback, EncodeFormActionCallback};
interface FlightStreamController {
enqueueValue(value: any): void;
enqueueModel(json: UninitializedModel): void;
close(json: UninitializedModel): void;
error(error: Error): void;
}
type UninitializedModel = string;
export type JSONValue =
| number
| null
| boolean
| string
| {+[key: string]: JSONValue}
| $ReadOnlyArray<JSONValue>;
type ProfilingResult = {
track: number,
endTime: number,
component: null | ReactComponentInfo,
};
const ROW_ID = 0;
const ROW_TAG = 1;
const ROW_LENGTH = 2;
const ROW_CHUNK_BY_NEWLINE = 3;
const ROW_CHUNK_BY_LENGTH = 4;
type RowParserState = 0 | 1 | 2 | 3 | 4;
const PENDING = 'pending';
const BLOCKED = 'blocked';
const RESOLVED_MODEL = 'resolved_model';
const RESOLVED_MODULE = 'resolved_module';
const INITIALIZED = 'fulfilled';
const ERRORED = 'rejected';
const HALTED = 'halted';
const __PROTO__ = '__proto__';
type PendingChunk<T> = {
status: 'pending',
value: null | Array<InitializationReference | (T => mixed)>,
reason: null | Array<InitializationReference | (mixed => mixed)>,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null | SomeChunk<ReactDebugInfoEntry>,
_debugInfo: ReactDebugInfo,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type BlockedChunk<T> = {
status: 'blocked',
value: null | Array<InitializationReference | (T => mixed)>,
reason: null | Array<InitializationReference | (mixed => mixed)>,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null,
_debugInfo: ReactDebugInfo,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type ResolvedModelChunk<T> = {
status: 'resolved_model',
value: UninitializedModel,
reason: Response,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null | SomeChunk<ReactDebugInfoEntry>,
_debugInfo: ReactDebugInfo,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type ResolvedModuleChunk<T> = {
status: 'resolved_module',
value: ClientReference<T>,
reason: null,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null,
_debugInfo: ReactDebugInfo,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type InitializedChunk<T> = {
status: 'fulfilled',
value: T,
reason: null | FlightStreamController,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null,
_debugInfo: ReactDebugInfo,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type InitializedStreamChunk<
T: ReadableStream | $AsyncIterable<any, any, void>,
> = {
status: 'fulfilled',
value: T,
reason: FlightStreamController,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null,
_debugInfo: ReactDebugInfo,
then(resolve: (ReadableStream) => mixed, reject?: (mixed) => mixed): void,
};
type ErroredChunk<T> = {
status: 'rejected',
value: null,
reason: mixed,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null,
_debugInfo: ReactDebugInfo,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type HaltedChunk<T> = {
status: 'halted',
value: null,
reason: null,
_children: Array<SomeChunk<any>> | ProfilingResult,
_debugChunk: null,
_debugInfo: ReactDebugInfo,
then(resolve: (T) => mixed, reject?: (mixed) => mixed): void,
};
type SomeChunk<T> =
| PendingChunk<T>
| BlockedChunk<T>
| ResolvedModelChunk<T>
| ResolvedModuleChunk<T>
| InitializedChunk<T>
| ErroredChunk<T>
| HaltedChunk<T>;
function ReactPromise(status: any, value: any, reason: any) {
this.status = status;
this.value = value;
this.reason = reason;
if (enableProfilerTimer && enableComponentPerformanceTrack) {
this._children = [];
}
if (__DEV__) {
this._debugChunk = null;
this._debugInfo = [];
}
}
ReactPromise.prototype = (Object.create(Promise.prototype): any);
ReactPromise.prototype.then = function <T>(
this: SomeChunk<T>,
resolve: (value: T) => mixed,
reject?: (reason: mixed) => mixed,
) {
const chunk: SomeChunk<T> = this;
switch (chunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(chunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(chunk);
break;
}
if (__DEV__ && enableAsyncDebugInfo) {
const resolveCallback = resolve;
const rejectCallback = reject;
const wrapperPromise: Promise<T> = new Promise((res, rej) => {
resolve = value => {
wrapperPromise._debugInfo = this._debugInfo;
res(value);
};
reject = reason => {
wrapperPromise._debugInfo = this._debugInfo;
rej(reason);
};
});
wrapperPromise.then(resolveCallback, rejectCallback);
}
switch (chunk.status) {
case INITIALIZED:
if (typeof resolve === 'function') {
resolve(chunk.value);
}
break;
case PENDING:
case BLOCKED:
if (typeof resolve === 'function') {
if (chunk.value === null) {
chunk.value = ([]: Array<InitializationReference | (T => mixed)>);
}
chunk.value.push(resolve);
}
if (typeof reject === 'function') {
if (chunk.reason === null) {
chunk.reason = ([]: Array<
InitializationReference | (mixed => mixed),
>);
}
chunk.reason.push(reject);
}
break;
case HALTED: {
break;
}
default:
if (typeof reject === 'function') {
reject(chunk.reason);
}
break;
}
};
export type FindSourceMapURLCallback = (
fileName: string,
environmentName: string,
) => null | string;
export type DebugChannelCallback = (message: string) => void;
export type DebugChannel = {
hasReadable: boolean,
callback: DebugChannelCallback | null,
};
type Response = {
_bundlerConfig: ServerConsumerModuleMap,
_serverReferenceConfig: null | ServerManifest,
_moduleLoading: ModuleLoading,
_callServer: CallServerCallback,
_encodeFormAction: void | EncodeFormActionCallback,
_nonce: ?string,
_chunks: Map<number, SomeChunk<any>>,
_fromJSON: (key: string, value: JSONValue) => any,
_stringDecoder: StringDecoder,
_closed: boolean,
_closedReason: mixed,
_tempRefs: void | TemporaryReferenceSet,
_timeOrigin: number,
_pendingInitialRender: null | TimeoutID,
_pendingChunks: number,
_weakResponse: WeakResponse,
_debugRootOwner?: null | ReactComponentInfo,
_debugRootStack?: null | Error,
_debugRootTask?: null | ConsoleTask,
_debugStartTime: number,
_debugEndTime?: number,
_debugIOStarted: boolean,
_debugFindSourceMapURL?: void | FindSourceMapURLCallback,
_debugChannel?: void | DebugChannel,
_blockedConsole?: null | SomeChunk<ConsoleEntry>,
_replayConsole: boolean,
_rootEnvironmentName: string,
};
type WeakResponse = {
weak: WeakRef<Response>,
response: null | Response,
};
export type {WeakResponse as Response};
function hasGCedResponse(weakResponse: WeakResponse): boolean {
return __DEV__ && weakResponse.weak.deref() === undefined;
}
function unwrapWeakResponse(weakResponse: WeakResponse): Response {
if (__DEV__) {
const response = weakResponse.weak.deref();
if (response === undefined) {
throw new Error(
'We did not expect to receive new data after GC:ing the response.',
);
}
return response;
} else {
return (weakResponse: any);
}
}
function getWeakResponse(response: Response): WeakResponse {
if (__DEV__) {
return response._weakResponse;
} else {
return (response: any);
}
}
function closeDebugChannel(debugChannel: DebugChannel): void {
if (debugChannel.callback) {
debugChannel.callback('');
}
}
const debugChannelRegistry =
__DEV__ && typeof FinalizationRegistry === 'function'
? new FinalizationRegistry(closeDebugChannel)
: null;
function readChunk<T>(chunk: SomeChunk<T>): T {
switch (chunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(chunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(chunk);
break;
}
switch (chunk.status) {
case INITIALIZED:
return chunk.value;
case PENDING:
case BLOCKED:
case HALTED:
throw ((chunk: any): Thenable<T>);
default:
throw chunk.reason;
}
}
export function getRoot<T>(weakResponse: WeakResponse): Thenable<T> {
const response = unwrapWeakResponse(weakResponse);
const chunk = getChunk(response, 0);
return (chunk: any);
}
function createPendingChunk<T>(response: Response): PendingChunk<T> {
if (__DEV__) {
if (response._pendingChunks++ === 0) {
response._weakResponse.response = response;
if (response._pendingInitialRender !== null) {
clearTimeout(response._pendingInitialRender);
response._pendingInitialRender = null;
}
}
}
return new ReactPromise(PENDING, null, null);
}
function releasePendingChunk(response: Response, chunk: SomeChunk<any>): void {
if (__DEV__ && chunk.status === PENDING) {
if (--response._pendingChunks === 0) {
response._weakResponse.response = null;
response._pendingInitialRender = setTimeout(
flushInitialRenderPerformance.bind(null, response),
100,
);
}
}
}
function createBlockedChunk<T>(response: Response): BlockedChunk<T> {
return new ReactPromise(BLOCKED, null, null);
}
function createErrorChunk<T>(
response: Response,
error: mixed,
): ErroredChunk<T> {
return new ReactPromise(ERRORED, null, error);
}
function filterDebugInfo(
response: Response,
value: {_debugInfo: ReactDebugInfo, ...},
) {
if (response._debugEndTime === null) {
return;
}
const relativeEndTime =
response._debugEndTime -
performance.timeOrigin;
const debugInfo = [];
for (let i = 0; i < value._debugInfo.length; i++) {
const info = value._debugInfo[i];
if (typeof info.time === 'number' && info.time > relativeEndTime) {
break;
}
debugInfo.push(info);
}
value._debugInfo = debugInfo;
}
function moveDebugInfoFromChunkToInnerValue<T>(
chunk: InitializedChunk<T> | InitializedStreamChunk<any>,
value: T,
): void {
const resolvedValue = resolveLazy(value);
if (
typeof resolvedValue === 'object' &&
resolvedValue !== null &&
(isArray(resolvedValue) ||
typeof resolvedValue[ASYNC_ITERATOR] === 'function' ||
resolvedValue.$$typeof === REACT_ELEMENT_TYPE ||
resolvedValue.$$typeof === REACT_LAZY_TYPE)
) {
const debugInfo = chunk._debugInfo.splice(0);
if (isArray(resolvedValue._debugInfo)) {
resolvedValue._debugInfo.unshift.apply(
resolvedValue._debugInfo,
debugInfo,
);
} else {
Object.defineProperty((resolvedValue: any), '_debugInfo', {
configurable: false,
enumerable: false,
writable: true,
value: debugInfo,
});
}
}
}
function processChunkDebugInfo<T>(
response: Response,
chunk: InitializedChunk<T> | InitializedStreamChunk<any>,
value: T,
): void {
filterDebugInfo(response, chunk);
moveDebugInfoFromChunkToInnerValue(chunk, value);
}
function wakeChunk<T>(
response: Response,
listeners: Array<InitializationReference | (T => mixed)>,
value: T,
chunk: InitializedChunk<T>,
): void {
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i];
if (typeof listener === 'function') {
listener(value);
} else {
fulfillReference(response, listener, value, chunk);
}
}
if (__DEV__) {
processChunkDebugInfo(response, chunk, value);
}
}
function rejectChunk(
response: Response,
listeners: Array<InitializationReference | (mixed => mixed)>,
error: mixed,
): void {
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i];
if (typeof listener === 'function') {
listener(error);
} else {
rejectReference(response, listener.handler, error);
}
}
}
function resolveBlockedCycle<T>(
resolvedChunk: SomeChunk<T>,
reference: InitializationReference,
): null | InitializationHandler {
const referencedChunk = reference.handler.chunk;
if (referencedChunk === null) {
return null;
}
if (referencedChunk === resolvedChunk) {
return reference.handler;
}
const resolveListeners = referencedChunk.value;
if (resolveListeners !== null) {
for (let i = 0; i < resolveListeners.length; i++) {
const listener = resolveListeners[i];
if (typeof listener !== 'function') {
const foundHandler = resolveBlockedCycle(resolvedChunk, listener);
if (foundHandler !== null) {
return foundHandler;
}
}
}
}
return null;
}
function wakeChunkIfInitialized<T>(
response: Response,
chunk: SomeChunk<T>,
resolveListeners: Array<InitializationReference | (T => mixed)>,
rejectListeners: null | Array<InitializationReference | (mixed => mixed)>,
): void {
switch (chunk.status) {
case INITIALIZED:
wakeChunk(response, resolveListeners, chunk.value, chunk);
break;
case BLOCKED:
for (let i = 0; i < resolveListeners.length; i++) {
const listener = resolveListeners[i];
if (typeof listener !== 'function') {
const reference: InitializationReference = listener;
const cyclicHandler = resolveBlockedCycle(chunk, reference);
if (cyclicHandler !== null) {
fulfillReference(response, reference, cyclicHandler.value, chunk);
resolveListeners.splice(i, 1);
i--;
if (rejectListeners !== null) {
const rejectionIdx = rejectListeners.indexOf(reference);
if (rejectionIdx !== -1) {
rejectListeners.splice(rejectionIdx, 1);
}
}
switch ((chunk: SomeChunk<T>).status) {
case INITIALIZED:
const initializedChunk: InitializedChunk<T> = (chunk: any);
wakeChunk(
response,
resolveListeners,
initializedChunk.value,
initializedChunk,
);
return;
case ERRORED:
if (rejectListeners !== null) {
rejectChunk(response, rejectListeners, chunk.reason);
}
return;
}
}
}
}
case PENDING:
if (chunk.value) {
for (let i = 0; i < resolveListeners.length; i++) {
chunk.value.push(resolveListeners[i]);
}
} else {
chunk.value = resolveListeners;
}
if (chunk.reason) {
if (rejectListeners) {
for (let i = 0; i < rejectListeners.length; i++) {
chunk.reason.push(rejectListeners[i]);
}
}
} else {
chunk.reason = rejectListeners;
}
break;
case ERRORED:
if (rejectListeners) {
rejectChunk(response, rejectListeners, chunk.reason);
}
break;
}
}
function triggerErrorOnChunk<T>(
response: Response,
chunk: SomeChunk<T>,
error: mixed,
): void {
if (chunk.status !== PENDING && chunk.status !== BLOCKED) {
const streamChunk: InitializedStreamChunk<any> = (chunk: any);
const controller = streamChunk.reason;
controller.error(error);
return;
}
releasePendingChunk(response, chunk);
const listeners = chunk.reason;
if (__DEV__ && chunk.status === PENDING) {
if (chunk._debugChunk != null) {
const prevHandler = initializingHandler;
const prevChunk = initializingChunk;
initializingHandler = null;
const cyclicChunk: BlockedChunk<T> = (chunk: any);
cyclicChunk.status = BLOCKED;
cyclicChunk.value = null;
cyclicChunk.reason = null;
if ((enableProfilerTimer && enableComponentPerformanceTrack) || __DEV__) {
initializingChunk = cyclicChunk;
}
try {
initializeDebugChunk(response, chunk);
if (initializingHandler !== null) {
if (initializingHandler.errored) {
} else if (initializingHandler.deps > 0) {
}
}
} finally {
initializingHandler = prevHandler;
initializingChunk = prevChunk;
}
}
}
const erroredChunk: ErroredChunk<T> = (chunk: any);
erroredChunk.status = ERRORED;
erroredChunk.reason = error;
if (listeners !== null) {
rejectChunk(response, listeners, error);
}
}
function createResolvedModelChunk<T>(
response: Response,
value: UninitializedModel,
): ResolvedModelChunk<T> {
return new ReactPromise(RESOLVED_MODEL, value, response);
}
function createResolvedModuleChunk<T>(
response: Response,
value: ClientReference<T>,
): ResolvedModuleChunk<T> {
return new ReactPromise(RESOLVED_MODULE, value, null);
}
function createInitializedTextChunk(
response: Response,
value: string,
): InitializedChunk<string> {
return new ReactPromise(INITIALIZED, value, null);
}
function createInitializedBufferChunk(
response: Response,
value: $ArrayBufferView | ArrayBuffer,
): InitializedChunk<Uint8Array> {
return new ReactPromise(INITIALIZED, value, null);
}
function createInitializedIteratorResultChunk<T>(
response: Response,
value: T,
done: boolean,
): InitializedChunk<IteratorResult<T, T>> {
return new ReactPromise(INITIALIZED, {done: done, value: value}, null);
}
function createInitializedStreamChunk<
T: ReadableStream | $AsyncIterable<any, any, void>,
>(
response: Response,
value: T,
controller: FlightStreamController,
): InitializedChunk<T> {
if (__DEV__) {
if (response._pendingChunks++ === 0) {
response._weakResponse.response = response;
}
}
return new ReactPromise(INITIALIZED, value, controller);
}
function createResolvedIteratorResultChunk<T>(
response: Response,
value: UninitializedModel,
done: boolean,
): ResolvedModelChunk<IteratorResult<T, T>> {
const iteratorResultJSON =
(done ? '{"done":true,"value":' : '{"done":false,"value":') + value + '}';
return new ReactPromise(RESOLVED_MODEL, iteratorResultJSON, response);
}
function resolveIteratorResultChunk<T>(
response: Response,
chunk: SomeChunk<IteratorResult<T, T>>,
value: UninitializedModel,
done: boolean,
): void {
const iteratorResultJSON =
(done ? '{"done":true,"value":' : '{"done":false,"value":') + value + '}';
resolveModelChunk(response, chunk, iteratorResultJSON);
}
function resolveModelChunk<T>(
response: Response,
chunk: SomeChunk<T>,
value: UninitializedModel,
): void {
if (chunk.status !== PENDING) {
const streamChunk: InitializedStreamChunk<any> = (chunk: any);
const controller = streamChunk.reason;
controller.enqueueModel(value);
return;
}
releasePendingChunk(response, chunk);
const resolveListeners = chunk.value;
const rejectListeners = chunk.reason;
const resolvedChunk: ResolvedModelChunk<T> = (chunk: any);
resolvedChunk.status = RESOLVED_MODEL;
resolvedChunk.value = value;
resolvedChunk.reason = response;
if (resolveListeners !== null) {
initializeModelChunk(resolvedChunk);
wakeChunkIfInitialized(response, chunk, resolveListeners, rejectListeners);
}
}
function resolveModuleChunk<T>(
response: Response,
chunk: SomeChunk<T>,
value: ClientReference<T>,
): void {
if (chunk.status !== PENDING && chunk.status !== BLOCKED) {
return;
}
releasePendingChunk(response, chunk);
const resolveListeners = chunk.value;
const rejectListeners = chunk.reason;
const resolvedChunk: ResolvedModuleChunk<T> = (chunk: any);
resolvedChunk.status = RESOLVED_MODULE;
resolvedChunk.value = value;
resolvedChunk.reason = null;
if (__DEV__) {
const debugInfo = getModuleDebugInfo(value);
if (debugInfo !== null) {
resolvedChunk._debugInfo.push.apply(resolvedChunk._debugInfo, debugInfo);
}
}
if (resolveListeners !== null) {
initializeModuleChunk(resolvedChunk);
wakeChunkIfInitialized(response, chunk, resolveListeners, rejectListeners);
}
}
type InitializationReference = {
handler: InitializationHandler,
parentObject: Object,
key: string,
map: (
response: Response,
model: any,
parentObject: Object,
key: string,
) => any,
path: Array<string>,
isDebug?: boolean,
};
type InitializationHandler = {
parent: null | InitializationHandler,
chunk: null | BlockedChunk<any>,
value: any,
reason: any,
deps: number,
errored: boolean,
};
let initializingHandler: null | InitializationHandler = null;
let initializingChunk: null | BlockedChunk<any> = null;
function initializeDebugChunk(
response: Response,
chunk: ResolvedModelChunk<any> | PendingChunk<any>,
): void {
const debugChunk = chunk._debugChunk;
if (debugChunk !== null) {
const debugInfo = chunk._debugInfo;
try {
if (debugChunk.status === RESOLVED_MODEL) {
let idx = debugInfo.length;
let c = debugChunk._debugChunk;
while (c !== null) {
if (c.status !== INITIALIZED) {
idx++;
}
c = c._debugChunk;
}
initializeModelChunk(debugChunk);
const initializedChunk = ((debugChunk: any): SomeChunk<any>);
switch (initializedChunk.status) {
case INITIALIZED: {
debugInfo[idx] = initializeDebugInfo(
response,
initializedChunk.value,
);
break;
}
case BLOCKED:
case PENDING: {
waitForReference(
initializedChunk,
debugInfo,
'' + idx,
response,
initializeDebugInfo,
[''],
true,
);
break;
}
default:
throw initializedChunk.reason;
}
} else {
switch (debugChunk.status) {
case INITIALIZED: {
break;
}
case BLOCKED:
case PENDING: {
waitForReference(
debugChunk,
{},
'debug',
response,
initializeDebugInfo,
[''],
true,
);
break;
}
default:
throw debugChunk.reason;
}
}
} catch (error) {
triggerErrorOnChunk(response, chunk, error);
}
}
}
function initializeModelChunk<T>(chunk: ResolvedModelChunk<T>): void {
const prevHandler = initializingHandler;
const prevChunk = initializingChunk;
initializingHandler = null;
const resolvedModel = chunk.value;
const response = chunk.reason;
const cyclicChunk: BlockedChunk<T> = (chunk: any);
cyclicChunk.status = BLOCKED;
cyclicChunk.value = null;
cyclicChunk.reason = null;
if ((enableProfilerTimer && enableComponentPerformanceTrack) || __DEV__) {
initializingChunk = cyclicChunk;
}
if (__DEV__) {
initializeDebugChunk(response, chunk);
}
try {
const value: T = parseModel(response, resolvedModel);
const resolveListeners = cyclicChunk.value;
if (resolveListeners !== null) {
cyclicChunk.value = null;
cyclicChunk.reason = null;
for (let i = 0; i < resolveListeners.length; i++) {
const listener = resolveListeners[i];
if (typeof listener === 'function') {
listener(value);
} else {
fulfillReference(response, listener, value, cyclicChunk);
}
}
}
if (initializingHandler !== null) {
if (initializingHandler.errored) {
throw initializingHandler.reason;
}
if (initializingHandler.deps > 0) {
initializingHandler.value = value;
initializingHandler.chunk = cyclicChunk;
return;
}
}
const initializedChunk: InitializedChunk<T> = (chunk: any);
initializedChunk.status = INITIALIZED;
initializedChunk.value = value;
if (__DEV__) {
processChunkDebugInfo(response, initializedChunk, value);
}
} catch (error) {
const erroredChunk: ErroredChunk<T> = (chunk: any);
erroredChunk.status = ERRORED;
erroredChunk.reason = error;
} finally {
initializingHandler = prevHandler;
if ((enableProfilerTimer && enableComponentPerformanceTrack) || __DEV__) {
initializingChunk = prevChunk;
}
}
}
function initializeModuleChunk<T>(chunk: ResolvedModuleChunk<T>): void {
try {
const value: T = requireModule(chunk.value);
const initializedChunk: InitializedChunk<T> = (chunk: any);
initializedChunk.status = INITIALIZED;
initializedChunk.value = value;
} catch (error) {
const erroredChunk: ErroredChunk<T> = (chunk: any);
erroredChunk.status = ERRORED;
erroredChunk.reason = error;
}
}
export function reportGlobalError(
weakResponse: WeakResponse,
error: Error,
): void {
if (hasGCedResponse(weakResponse)) {
return;
}
const response = unwrapWeakResponse(weakResponse);
response._closed = true;
response._closedReason = error;
response._chunks.forEach(chunk => {
if (chunk.status === PENDING) {
triggerErrorOnChunk(response, chunk, error);
} else if (chunk.status === INITIALIZED && chunk.reason !== null) {
chunk.reason.error(error);
}
});
if (__DEV__) {
const debugChannel = response._debugChannel;
if (debugChannel !== undefined) {
closeDebugChannel(debugChannel);
response._debugChannel = undefined;
if (debugChannelRegistry !== null) {
debugChannelRegistry.unregister(response);
}
}
}
}
function nullRefGetter() {
if (__DEV__) {
return null;
}
}
function getIOInfoTaskName(ioInfo: ReactIOInfo): string {
return ioInfo.name || 'unknown';
}
function getAsyncInfoTaskName(asyncInfo: ReactAsyncInfo): string {
return 'await ' + getIOInfoTaskName(asyncInfo.awaited);
}
function getServerComponentTaskName(componentInfo: ReactComponentInfo): string {
return '<' + (componentInfo.name || '...') + '>';
}
function getTaskName(type: mixed): string {
if (type === REACT_FRAGMENT_TYPE) {
return '<>';
}
if (typeof type === 'function') {
return '"use client"';
}
if (
typeof type === 'object' &&
type !== null &&
type.$$typeof === REACT_LAZY_TYPE
) {
if (type._init === readChunk) {
return '"use client"';
}
return '<...>';
}
try {
const name = getComponentNameFromType(type);
return name ? '<' + name + '>' : '<...>';
} catch (x) {
return '<...>';
}
}
function initializeElement(
response: Response,
element: any,
lazyNode: null | LazyComponent<
React$Element<any>,
SomeChunk<React$Element<any>>,
>,
): void {
if (!__DEV__) {
return;
}
const stack = element._debugStack;
const owner = element._owner;
if (owner === null) {
element._owner = response._debugRootOwner;
}
let env = response._rootEnvironmentName;
if (owner !== null && owner.env != null) {
env = owner.env;
}
let normalizedStackTrace: null | Error = null;
if (owner === null && response._debugRootStack != null) {
normalizedStackTrace = response._debugRootStack;
} else if (stack !== null) {
normalizedStackTrace = createFakeJSXCallStackInDEV(response, stack, env);
}
element._debugStack = normalizedStackTrace;
let task: null | ConsoleTask = null;
if (supportsCreateTask && stack !== null) {
const createTaskFn = (console: any).createTask.bind(
console,
getTaskName(element.type),
);
const callStack = buildFakeCallStack(
response,
stack,
env,
false,
createTaskFn,
);
const ownerTask =
owner === null ? null : initializeFakeTask(response, owner);
if (ownerTask === null) {
const rootTask = response._debugRootTask;
if (rootTask != null) {
task = rootTask.run(callStack);
} else {
task = callStack();
}
} else {
task = ownerTask.run(callStack);
}
}
element._debugTask = task;
if (owner !== null) {
initializeFakeStack(response, owner);
}
if (lazyNode !== null) {
if (
lazyNode._store &&
lazyNode._store.validated &&
!element._store.validated
) {
element._store.validated = lazyNode._store.validated;
}
if (lazyNode._payload.status === INITIALIZED && lazyNode._debugInfo) {
const debugInfo = lazyNode._debugInfo.splice(0);
if (element._debugInfo) {
element._debugInfo.unshift.apply(element._debugInfo, debugInfo);
} else {
Object.defineProperty(element, '_debugInfo', {
configurable: false,
enumerable: false,
writable: true,
value: debugInfo,
});
}
}
}
Object.freeze(element.props);
}
function createElement(
response: Response,
type: mixed,
key: mixed,
props: mixed,
owner: ?ReactComponentInfo,
stack: ?ReactStackTrace,
validated: 0 | 1 | 2,
):
| React$Element<any>
| LazyComponent<React$Element<any>, SomeChunk<React$Element<any>>> {
let element: any;
if (__DEV__) {
element = ({
$$typeof: REACT_ELEMENT_TYPE,
type,
key,
props,
_owner: owner === undefined ? null : owner,
}: any);
Object.defineProperty(element, 'ref', {
enumerable: false,
get: nullRefGetter,
});
} else {
element = ({
$$typeof: REACT_ELEMENT_TYPE,
type,
key,
ref: null,
props,
}: any);
}
if (__DEV__) {
element._store = ({}: {
validated?: number,
});
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: validated,
});
Object.defineProperty(element, '_debugInfo', {
configurable: false,
enumerable: false,
writable: true,
value: null,
});
Object.defineProperty(element, '_debugStack', {
configurable: false,
enumerable: false,
writable: true,
value: stack === undefined ? null : stack,
});
Object.defineProperty(element, '_debugTask', {
configurable: false,
enumerable: false,
writable: true,
value: null,
});
}
if (initializingHandler !== null) {
const handler = initializingHandler;
initializingHandler = handler.parent;
if (handler.errored) {
const erroredChunk: ErroredChunk<React$Element<any>> = createErrorChunk(
response,
handler.reason,
);
if (__DEV__) {
initializeElement(response, element, null);
const erroredComponent: ReactComponentInfo = {
name: getComponentNameFromType(element.type) || '',
owner: element._owner,
};
erroredComponent.debugStack = element._debugStack;
if (supportsCreateTask) {
erroredComponent.debugTask = element._debugTask;
}
erroredChunk._debugInfo = [erroredComponent];
}
return createLazyChunkWrapper(erroredChunk, validated);
}
if (handler.deps > 0) {
const blockedChunk: BlockedChunk<React$Element<any>> =
createBlockedChunk(response);
handler.value = element;
handler.chunk = blockedChunk;
const lazyNode = createLazyChunkWrapper(blockedChunk, validated);
if (__DEV__) {
const init = initializeElement.bind(null, response, element, lazyNode);
blockedChunk.then(init, init);
}
return lazyNode;
}
}
if (__DEV__) {
initializeElement(response, element, null);
}
return element;
}
function createLazyChunkWrapper<T>(
chunk: SomeChunk<T>,
validated: 0 | 1 | 2,
): LazyComponent<T, SomeChunk<T>> {
const lazyType: LazyComponent<T, SomeChunk<T>> = {
$$typeof: REACT_LAZY_TYPE,
_payload: chunk,
_init: readChunk,
};
if (__DEV__) {
lazyType._debugInfo = chunk._debugInfo;
lazyType._store = {validated: validated};
}
return lazyType;
}
function getChunk(response: Response, id: number): SomeChunk<any> {
const chunks = response._chunks;
let chunk = chunks.get(id);
if (!chunk) {
if (response._closed) {
chunk = createErrorChunk(response, response._closedReason);
} else {
chunk = createPendingChunk(response);
}
chunks.set(id, chunk);
}
return chunk;
}
function fulfillReference(
response: Response,
reference: InitializationReference,
value: any,
fulfilledChunk: SomeChunk<any>,
): void {
const {handler, parentObject, key, map, path} = reference;
try {
for (let i = 1; i < path.length; i++) {
while (
typeof value === 'object' &&
value !== null &&
value.$$typeof === REACT_LAZY_TYPE
) {
const referencedChunk: SomeChunk<any> = value._payload;
if (referencedChunk === handler.chunk) {
value = handler.value;
continue;
} else {
switch (referencedChunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(referencedChunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(referencedChunk);
break;
}
switch (referencedChunk.status) {
case INITIALIZED: {
value = referencedChunk.value;
continue;
}
case BLOCKED: {
const cyclicHandler = resolveBlockedCycle(
referencedChunk,
reference,
);
if (cyclicHandler !== null) {
value = cyclicHandler.value;
continue;
}
}
case PENDING: {
path.splice(0, i - 1);
if (referencedChunk.value === null) {
referencedChunk.value = [reference];
} else {
referencedChunk.value.push(reference);
}
if (referencedChunk.reason === null) {
referencedChunk.reason = [reference];
} else {
referencedChunk.reason.push(reference);
}
return;
}
case HALTED: {
return;
}
default: {
rejectReference(
response,
reference.handler,
referencedChunk.reason,
);
return;
}
}
}
}
const name = path[i];
if (
typeof value === 'object' &&
value !== null &&
hasOwnProperty.call(value, name)
) {
value = value[name];
} else {
throw new Error('Invalid reference.');
}
}
while (
typeof value === 'object' &&
value !== null &&
value.$$typeof === REACT_LAZY_TYPE
) {
const referencedChunk: SomeChunk<any> = value._payload;
if (referencedChunk === handler.chunk) {
value = handler.value;
continue;
} else {
switch (referencedChunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(referencedChunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(referencedChunk);
break;
}
switch (referencedChunk.status) {
case INITIALIZED: {
value = referencedChunk.value;
continue;
}
}
}
break;
}
const mappedValue = map(response, value, parentObject, key);
if (key !== __PROTO__) {
parentObject[key] = mappedValue;
}
if (key === '' && handler.value === null) {
handler.value = mappedValue;
}
if (
parentObject[0] === REACT_ELEMENT_TYPE &&
typeof handler.value === 'object' &&
handler.value !== null &&
handler.value.$$typeof === REACT_ELEMENT_TYPE
) {
const element: any = handler.value;
switch (key) {
case '3':
transferReferencedDebugInfo(handler.chunk, fulfilledChunk);
element.props = mappedValue;
break;
case '4':
if (__DEV__) {
element._owner = mappedValue;
}
break;
case '5':
if (__DEV__) {
element._debugStack = mappedValue;
}
break;
default:
transferReferencedDebugInfo(handler.chunk, fulfilledChunk);
break;
}
} else if (__DEV__ && !reference.isDebug) {
transferReferencedDebugInfo(handler.chunk, fulfilledChunk);
}
} catch (error) {
rejectReference(response, reference.handler, error);
return;
}
handler.deps--;
if (handler.deps === 0) {
const chunk = handler.chunk;
if (chunk === null || chunk.status !== BLOCKED) {
return;
}
const resolveListeners = chunk.value;
const initializedChunk: InitializedChunk<any> = (chunk: any);
initializedChunk.status = INITIALIZED;
initializedChunk.value = handler.value;
initializedChunk.reason = handler.reason;
if (resolveListeners !== null) {
wakeChunk(response, resolveListeners, handler.value, initializedChunk);
} else {
if (__DEV__) {
processChunkDebugInfo(response, initializedChunk, handler.value);
}
}
}
}
function rejectReference(
response: Response,
handler: InitializationHandler,
error: mixed,
): void {
if (handler.errored) {
return;
}
const blockedValue = handler.value;
handler.errored = true;
handler.value = null;
handler.reason = error;
const chunk = handler.chunk;
if (chunk === null || chunk.status !== BLOCKED) {
return;
}
if (__DEV__) {
if (
typeof blockedValue === 'object' &&
blockedValue !== null &&
blockedValue.$$typeof === REACT_ELEMENT_TYPE
) {
const element = blockedValue;
const erroredComponent: ReactComponentInfo = {
name: getComponentNameFromType(element.type) || '',
owner: element._owner,
};
erroredComponent.debugStack = element._debugStack;
if (supportsCreateTask) {
erroredComponent.debugTask = element._debugTask;
}
chunk._debugInfo.push(erroredComponent);
}
}
triggerErrorOnChunk(response, chunk, error);
}
function waitForReference<T>(
referencedChunk: PendingChunk<T> | BlockedChunk<T>,
parentObject: Object,
key: string,
response: Response,
map: (response: Response, model: any, parentObject: Object, key: string) => T,
path: Array<string>,
isAwaitingDebugInfo: boolean,
): T {
if (
__DEV__ &&
(response._debugChannel === undefined ||
!response._debugChannel.hasReadable)
) {
if (
referencedChunk.status === PENDING &&
parentObject[0] === REACT_ELEMENT_TYPE &&
(key === '4' || key === '5')
) {
return (null: any);
}
}
let handler: InitializationHandler;
if (initializingHandler) {
handler = initializingHandler;
handler.deps++;
} else {
handler = initializingHandler = {
parent: null,
chunk: null,
value: null,
reason: null,
deps: 1,
errored: false,
};
}
const reference: InitializationReference = {
handler,
parentObject,
key,
map,
path,
};
if (__DEV__) {
reference.isDebug = isAwaitingDebugInfo;
}
if (referencedChunk.value === null) {
referencedChunk.value = [reference];
} else {
referencedChunk.value.push(reference);
}
if (referencedChunk.reason === null) {
referencedChunk.reason = [reference];
} else {
referencedChunk.reason.push(reference);
}
return (null: any);
}
function loadServerReference<A: Iterable<any>, T>(
response: Response,
metaData: {
id: any,
bound: null | Thenable<Array<any>>,
name?: string, // DEV-only
env?: string, // DEV-only
location?: ReactFunctionLocation, // DEV-only
},
parentObject: Object,
key: string,
): (...A) => Promise<T> {
if (!response._serverReferenceConfig) {
return createBoundServerReference(
metaData,
response._callServer,
response._encodeFormAction,
__DEV__ ? response._debugFindSourceMapURL : undefined,
);
}
const serverReference: ClientReference<T> =
resolveServerReference<$FlowFixMe>(
response._serverReferenceConfig,
metaData.id,
);
let promise: null | Thenable<any> = preloadModule(serverReference);
if (!promise) {
if (!metaData.bound) {
const resolvedValue = (requireModule(serverReference): any);
registerBoundServerReference(
resolvedValue,
metaData.id,
metaData.bound,
response._encodeFormAction,
);
return resolvedValue;
} else {
promise = Promise.resolve(metaData.bound);
}
} else if (metaData.bound) {
promise = Promise.all([promise, metaData.bound]);
}
let handler: InitializationHandler;
if (initializingHandler) {
handler = initializingHandler;
handler.deps++;
} else {
handler = initializingHandler = {
parent: null,
chunk: null,
value: null,
reason: null,
deps: 1,
errored: false,
};
}
function fulfill(): void {
let resolvedValue = (requireModule(serverReference): any);
if (metaData.bound) {
const boundArgs: Array<any> = (metaData.bound: any).value.slice(0);
boundArgs.unshift(null);
resolvedValue = resolvedValue.bind.apply(resolvedValue, boundArgs);
}
registerBoundServerReference(
resolvedValue,
metaData.id,
metaData.bound,
response._encodeFormAction,
);
if (key !== __PROTO__) {
parentObject[key] = resolvedValue;
}
if (key === '' && handler.value === null) {
handler.value = resolvedValue;
}
if (
parentObject[0] === REACT_ELEMENT_TYPE &&
typeof handler.value === 'object' &&
handler.value !== null &&
handler.value.$$typeof === REACT_ELEMENT_TYPE
) {
const element: any = handler.value;
switch (key) {
case '3':
element.props = resolvedValue;
break;
case '4':
if (__DEV__) {
element._owner = resolvedValue;
}
break;
}
}
handler.deps--;
if (handler.deps === 0) {
const chunk = handler.chunk;
if (chunk === null || chunk.status !== BLOCKED) {
return;
}
const resolveListeners = chunk.value;
const initializedChunk: InitializedChunk<T> = (chunk: any);
initializedChunk.status = INITIALIZED;
initializedChunk.value = handler.value;
initializedChunk.reason = null;
if (resolveListeners !== null) {
wakeChunk(response, resolveListeners, handler.value, initializedChunk);
} else {
if (__DEV__) {
processChunkDebugInfo(response, initializedChunk, handler.value);
}
}
}
}
function reject(error: mixed): void {
if (handler.errored) {
return;
}
const blockedValue = handler.value;
handler.errored = true;
handler.value = null;
handler.reason = error;
const chunk = handler.chunk;
if (chunk === null || chunk.status !== BLOCKED) {
return;
}
if (__DEV__) {
if (
typeof blockedValue === 'object' &&
blockedValue !== null &&
blockedValue.$$typeof === REACT_ELEMENT_TYPE
) {
const element = blockedValue;
const erroredComponent: ReactComponentInfo = {
name: getComponentNameFromType(element.type) || '',
owner: element._owner,
};
erroredComponent.debugStack = element._debugStack;
if (supportsCreateTask) {
erroredComponent.debugTask = element._debugTask;
}
chunk._debugInfo.push(erroredComponent);
}
}
triggerErrorOnChunk(response, chunk, error);
}
promise.then(fulfill, reject);
return (null: any);
}
function resolveLazy(value: any): mixed {
while (
typeof value === 'object' &&
value !== null &&
value.$$typeof === REACT_LAZY_TYPE
) {
const payload: SomeChunk<any> = value._payload;
if (payload.status === INITIALIZED) {
value = payload.value;
continue;
}
break;
}
return value;
}
function transferReferencedDebugInfo(
parentChunk: null | SomeChunk<any>,
referencedChunk: SomeChunk<any>,
): void {
if (__DEV__) {
if (parentChunk !== null) {
const referencedDebugInfo = referencedChunk._debugInfo;
const parentDebugInfo = parentChunk._debugInfo;
for (let i = 0; i < referencedDebugInfo.length; ++i) {
const debugInfoEntry = referencedDebugInfo[i];
if (debugInfoEntry.name != null) {
(debugInfoEntry: ReactComponentInfo);
} else {
parentDebugInfo.push(debugInfoEntry);
}
}
}
}
}
function getOutlinedModel<T>(
response: Response,
reference: string,
parentObject: Object,
key: string,
map: (response: Response, model: any, parentObject: Object, key: string) => T,
): T {
const path = reference.split(':');
const id = parseInt(path[0], 16);
const chunk = getChunk(response, id);
if (enableProfilerTimer && enableComponentPerformanceTrack) {
if (initializingChunk !== null && isArray(initializingChunk._children)) {
initializingChunk._children.push(chunk);
}
}
switch (chunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(chunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(chunk);
break;
}
switch (chunk.status) {
case INITIALIZED:
let value = chunk.value;
for (let i = 1; i < path.length; i++) {
while (
typeof value === 'object' &&
value !== null &&
value.$$typeof === REACT_LAZY_TYPE
) {
const referencedChunk: SomeChunk<any> = value._payload;
switch (referencedChunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(referencedChunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(referencedChunk);
break;
}
switch (referencedChunk.status) {
case INITIALIZED: {
value = referencedChunk.value;
break;
}
case BLOCKED:
case PENDING: {
return waitForReference(
referencedChunk,
parentObject,
key,
response,
map,
path.slice(i - 1),
false,
);
}
case HALTED: {
let handler: InitializationHandler;
if (initializingHandler) {
handler = initializingHandler;
handler.deps++;
} else {
handler = initializingHandler = {
parent: null,
chunk: null,
value: null,
reason: null,
deps: 1,
errored: false,
};
}
return (null: any);
}
default: {
if (initializingHandler) {
initializingHandler.errored = true;
initializingHandler.value = null;
initializingHandler.reason = referencedChunk.reason;
} else {
initializingHandler = {
parent: null,
chunk: null,
value: null,
reason: referencedChunk.reason,
deps: 0,
errored: true,
};
}
return (null: any);
}
}
}
value = value[path[i]];
}
while (
typeof value === 'object' &&
value !== null &&
value.$$typeof === REACT_LAZY_TYPE
) {
const referencedChunk: SomeChunk<any> = value._payload;
switch (referencedChunk.status) {
case RESOLVED_MODEL:
initializeModelChunk(referencedChunk);
break;
case RESOLVED_MODULE:
initializeModuleChunk(referencedChunk);
break;
}
switch (referencedChunk.status) {
case INITIALIZED: {
value = referencedChunk.value;
continue;
}
}
break;
}
const chunkValue = map(response, value, parentObject, key);
if (
parentObject[0] === REACT_ELEMENT_TYPE &&
(key === '4' || key === '5')
) {
} else {
transferReferencedDebugInfo(initializingChunk, chunk);
}
return chunkValue;
case PENDING:
case BLOCKED:
return waitForReference(
chunk,
parentObject,
key,
response,
map,
path,
false,
);
case HALTED: {
let handler: InitializationHandler;
if (initializingHandler) {
handler = initializingHandler;
handler.deps++;
} else {
handler = initializingHandler = {
parent: null,
chunk: null,
value: null,
reason: null,
deps: 1,
errored: false,
};
}
return (null: any);
}
default:
if (initializingHandler) {
initializingHandler.errored = true;
initializingHandler.value = null;
initializingHandler.reason = chunk.reason;
} else {
initializingHandler = {
parent: null,
chunk: null,
value: null,
reason: chunk.reason,
deps: 0,
errored: true,
};
}
return (null: any);
}
}
function createMap(
response: Response,
model: Array<[any, any]>,
): Map<any, any> {
return new Map(model);
}
function createSet(response: Response, model: Array<any>): Set<any> {
return new Set(model);
}
function createBlob(response: Response, model: Array<any>): Blob {
return new Blob(model.slice(1), {type: model[0]});
}
function createFormData(
response: Response,
model: Array<[any, any]>,
): FormData {
const formData = new FormData();
for (let i = 0; i < model.length; i++) {
formData.append(model[i][0], model[i][1]);
}
return formData;
}
function applyConstructor(
response: Response,
model: Function,
parentObject: Object,
key: string,
): void {
Object.setPrototypeOf(parentObject, model.prototype);
return undefined;
}
function defineLazyGetter<T>(
response: Response,
chunk: SomeChunk<T>,
parentObject: Object,
key: string,
): any {
if (key !== __PROTO__) {
Object.defineProperty(parentObject, key, {
get: function () {
if (chunk.status === RESOLVED_MODEL) {
initializeModelChunk(chunk);
}
switch (chunk.status) {
case INITIALIZED: {
return chunk.value;
}
case ERRORED:
throw chunk.reason;
}
return OMITTED_PROP_ERROR;
},
enumerable: true,
configurable: false,
});
}
return null;
}
function extractIterator(response: Response, model: Array<any>): Iterator<any> {
return model[Symbol.iterator]();
}
function createModel(response: Response, model: any): any {
return model;
}
const mightHaveStaticConstructor = /\bclass\b.*\bstatic\b/;
function getInferredFunctionApproximate(code: string): () => void {
let slicedCode;
if (code.startsWith('Object.defineProperty(')) {
slicedCode = code.slice('Object.defineProperty('.length);
} else if (code.startsWith('(')) {
slicedCode = code.slice(1);
} else {
slicedCode = code;
}
if (slicedCode.startsWith('async function')) {
const idx = slicedCode.indexOf('(', 14);
if (idx !== -1) {
const name = slicedCode.slice(14, idx).trim();
return (0, eval)('({' + JSON.stringify(name) + ':async function(){}})')[
name
];
}
} else if (slicedCode.startsWith('function')) {
const idx = slicedCode.indexOf('(', 8);
if (idx !== -1) {
const name = slicedCode.slice(8, idx).trim();
return (0, eval)('({' + JSON.stringify(name) + ':function(){}})')[name];
}
} else if (slicedCode.startsWith('class')) {
const idx = slicedCode.indexOf('{', 5);
if (idx !== -1) {
const name = slicedCode.slice(5, idx).trim();
return (0, eval)('({' + JSON.stringify(name) + ':class{}})')[name];
}
}
return function () {};
}
function parseModelString(
response: Response,
parentObject: Object,
key: string,
value: string,
): any {
if (value[0] === '$') {
if (value === '$') {
if (initializingHandler !== null && key === '0') {
initializingHandler = {
parent: initializingHandler,
chunk: null,
value: null,
reason: null,
deps: 0,
errored: false,
};
}
return REACT_ELEMENT_TYPE;
}
switch (value[1]) {
case '$': {
return value.slice(1);
}
case 'L': {
const id = parseInt(value.slice(2), 16);
const chunk = getChunk(response, id);
if (enableProfilerTimer && enableComponentPerformanceTrack) {
if (
initializingChunk !== null &&
isArray(initializingChunk._children)
) {
initializingChunk._children.push(chunk);
}
}
return createLazyChunkWrapper(chunk, 0);
}
case '@': {
const id = parseInt(value.slice(2), 16);
const chunk = getChunk(response, id);
if (enableProfilerTimer && enableComponentPerformanceTrack) {
if (
initializingChunk !== null &&
isArray(initializingChunk._children)
) {
initializingChunk._children.push(chunk);
}
}
return chunk;
}
case 'S': {
return Symbol.for(value.slice(2));
}
case 'h': {
const ref = value.slice(2);
return getOutlinedModel(
response,
ref,
parentObject,
key,
loadServerReference,
);
}
case 'T': {
const reference = '$' + value.slice(2);
const temporaryReferences = response._tempRefs;
if (temporaryReferences == null) {
throw new Error(
'Missing a temporary reference set but the RSC response returned a temporary reference. ' +
'Pass a temporaryReference option with the set that was used with the reply.',
);
}
return readTemporaryReference(temporaryReferences, reference);
}
case 'Q': {
const ref = value.slice(2);
return getOutlinedModel(response, ref, parentObject, key, createMap);
}
case 'W': {
const ref = value.slice(2);
return getOutlinedModel(response, ref, parentObject, key, createSet);
}
case 'B': {
const ref = value.slice(2);
return getOutlinedModel(response, ref, parentObject, key, createBlob);
}
case 'K': {
const ref = value.slice(2);
return getOutlinedModel(
response,
ref,
parentObject,
key,
createFormData,
);
}
case 'Z': {
if (__DEV__) {
const ref = value.slice(2);
return getOutlinedModel(
response,
ref,
parentObject,
key,
resolveErrorDev,
);
} else {
return resolveErrorProd(response);
}
}
case 'i': {
const ref = value.slice(2);
return getOutlinedModel(
response,
ref,
parentObject,
key,
extractIterator,
);
}
case 'I': {
return Infinity;
}
case '-': {
if (value === '$-0') {
return -0;
} else {
return -Infinity;
}
}
case 'N': {
return NaN;
}
case 'u': {
return undefined;
}
case 'D': {
return new Date(Date.parse(value.slice(2)));
}
case 'n': {
return BigInt(value.slice(2));
}
case 'P': {
if (__DEV__) {
const ref = value.slice(2);
return getOutlinedModel(
response,
ref,
parentObject,
key,
applyConstructor,
);
}
}
case 'E': {
if (__DEV__) {
const code = value.slice(2);
try {
if (!mightHaveStaticConstructor.test(code)) {
return (0, eval)(code);
}
} catch (x) {
}
let fn;
try {
fn = getInferredFunctionApproximate(code);
if (code.startsWith('Object.defineProperty(')) {
const DESCRIPTOR = ',"name",{value:"';
const idx = code.lastIndexOf(DESCRIPTOR);
if (idx !== -1) {
const name = JSON.parse(
code.slice(idx + DESCRIPTOR.length - 1, code.length - 2),
);
Object.defineProperty(fn, 'name', {value: name});
}
}
} catch (_) {
fn = function () {};
}
return fn;
}
}
case 'Y': {
if (__DEV__) {
if (value.length > 2) {
const debugChannelCallback =
response._debugChannel && response._debugChannel.callback;
if (debugChannelCallback) {
if (value[2] === '@') {
const ref = value.slice(3);
const id = parseInt(ref, 16);
if (!response._chunks.has(id)) {
debugChannelCallback('P:' + ref);
}
return getChunk(response, id);
}
const ref = value.slice(2);
const id = parseInt(ref, 16);
if (!response._chunks.has(id)) {
debugChannelCallback('Q:' + ref);
}
const chunk = getChunk(response, id);
if (chunk.status === INITIALIZED) {
return chunk.value;
}
return defineLazyGetter(response, chunk, parentObject, key);
}
}
if (key !== __PROTO__) {
Object.defineProperty(parentObject, key, {
get: function () {
return OMITTED_PROP_ERROR;
},
enumerable: true,
configurable: false,
});
}
return null;
}
}
default: {
const ref = value.slice(1);
return getOutlinedModel(response, ref, parentObject, key, createModel);
}
}
}
return value;
}
function parseModelTuple(
response: Response,
value: {+[key: string]: JSONValue} | $ReadOnlyArray<JSONValue>,
): any {
const tuple: [mixed, mixed, mixed, mixed] = (value: any);
if (tuple[0] === REACT_ELEMENT_TYPE) {
return createElement(
response,
tuple[1],
tuple[2],
tuple[3],
__DEV__ ? (tuple: any)[4] : null,
__DEV__ ? (tuple: any)[5] : null,
__DEV__ ? (tuple: any)[6] : 0,
);
}
return value;
}
function missingCall() {
throw new Error(
'Trying to call a function from "use server" but the callServer option ' +
'was not implemented in your router runtime.',
);
}
function markIOStarted(this: Response) {
this._debugIOStarted = true;
}
function ResponseInstance(
this: $FlowFixMe,
bundlerConfig: ServerConsumerModuleMap,
serverReferenceConfig: null | ServerManifest,
moduleLoading: ModuleLoading,
callServer: void | CallServerCallback,
encodeFormAction: void | EncodeFormActionCallback,
nonce: void | string,
temporaryReferences: void | TemporaryReferenceSet,
findSourceMapURL: void | FindSourceMapURLCallback,
replayConsole: boolean,
environmentName: void | string,
debugStartTime: void | number,
debugEndTime: void | number,
debugChannel: void | DebugChannel,
) {
const chunks: Map<number, SomeChunk<any>> = new Map();
this._bundlerConfig = bundlerConfig;
this._serverReferenceConfig = serverReferenceConfig;
this._moduleLoading = moduleLoading;
this._callServer = callServer !== undefined ? callServer : missingCall;
this._encodeFormAction = encodeFormAction;
this._nonce = nonce;
this._chunks = chunks;
this._stringDecoder = createStringDecoder();
this._fromJSON = (null: any);
this._closed = false;
this._closedReason = null;
this._tempRefs = temporaryReferences;
if (enableProfilerTimer && enableComponentPerformanceTrack) {
this._timeOrigin = 0;
this._pendingInitialRender = null;
}
if (__DEV__) {
this._pendingChunks = 0;
this._weakResponse = {
weak: new WeakRef(this),
response: this,
};
const rootOwner: null | ReactComponentInfo =
ReactSharedInteralsServer === undefined ||
ReactSharedInteralsServer.A === null
? null
: (ReactSharedInteralsServer.A.getOwner(): any);
this._debugRootOwner = rootOwner;
this._debugRootStack =
rootOwner !== null
?
new Error('react-stack-top-frame')
: null;
const rootEnv = environmentName === undefined ? 'Server' : environmentName;
if (supportsCreateTask) {
this._debugRootTask = (console: any).createTask(
'"use ' + rootEnv.toLowerCase() + '"',
);
}
if (enableAsyncDebugInfo) {
this._debugStartTime =
debugStartTime == null ? performance.now() : debugStartTime;
this._debugIOStarted = false;
setTimeout(markIOStarted.bind(this), 0);
}
this._debugEndTime = debugEndTime == null ? null : debugEndTime;
this._debugFindSourceMapURL = findSourceMapURL;
this._debugChannel = debugChannel;
this._blockedConsole = null;
this._replayConsole = replayConsole;
this._rootEnvironmentName = rootEnv;
if (debugChannel) {
if (debugChannelRegistry === null) {
closeDebugChannel(debugChannel);
this._debugChannel = undefined;
} else {
debugChannelRegistry.register(this, debugChannel, this);
}
}
}
if (enableProfilerTimer && enableComponentPerformanceTrack) {
if (replayConsole) {
markAllTracksInOrder();
}
}
this._fromJSON = createFromJSONCallback(this);
}
export function createResponse(
bundlerConfig: ServerConsumerModuleMap,
serverReferenceConfig: null | ServerManifest,
moduleLoading: ModuleLoading,
callServer: void | CallServerCallback,
encodeFormAction: void | EncodeFormActionCallback,
nonce: void | string,
temporaryReferences: void | TemporaryReferenceSet,
findSourceMapURL: void | FindSourceMapURLCallback,
replayConsole: boolean,
environmentName: void | string,
debugStartTime: void | number,
debugEndTime: void | number,
debugChannel: void | DebugChannel,
): WeakResponse {
if (__DEV__) {
checkEvalAvailabilityOnceDev();
}
return getWeakResponse(
new ResponseInstance(
bundlerConfig,
serverReferenceConfig,
moduleLoading,
callServer,
encodeFormAction,
nonce,
temporaryReferences,
findSourceMapURL,
replayConsole,
environmentName,
debugStartTime,
debugEndTime,
debugChannel,
),
);
}
export type StreamState = {
_rowState: RowParserState,
_rowID: number,
_rowTag: number,
_rowLength: number,
_buffer: Array<Uint8Array>,
_debugInfo: ReactIOInfo,
_debugTargetChunkSize: number,
};
export function createStreamState(
weakResponse: WeakResponse,
streamDebugValue: mixed,
): StreamState {
const streamState: StreamState = (({
_rowState: 0,
_rowID: 0,
_rowTag: 0,
_rowLength: 0,
_buffer: [],
}: Omit<StreamState, '_debugInfo' | '_debugTargetChunkSize'>): any);
if (__DEV__ && enableAsyncDebugInfo) {
const response = unwrapWeakResponse(weakResponse);
const debugValuePromise = Promise.resolve(streamDebugValue);
(debugValuePromise: any).status = 'fulfilled';
(debugValuePromise: any).value = streamDebugValue;
streamState._debugInfo = {
name: 'rsc stream',
start: response._debugStartTime,
end: response._debugStartTime,
byteSize: 0,
value: debugValuePromise,
owner: response._debugRootOwner,
debugStack: response._debugRootStack,
debugTask: response._debugRootTask,
};
streamState._debugTargetChunkSize = MIN_CHUNK_SIZE;
}
return streamState;
}
const MIN_CHUNK_SIZE = 65536;
function incrementChunkDebugInfo(
streamState: StreamState,
chunkLength: number,
): void {
if (__DEV__ && enableAsyncDebugInfo) {
const debugInfo: ReactIOInfo = streamState._debugInfo;
const endTime = performance.now();
const previousEndTime = debugInfo.end;
const newByteLength = ((debugInfo.byteSize: any): number) + chunkLength;
if (
newByteLength > streamState._debugTargetChunkSize ||
endTime > previousEndTime + 10
) {
streamState._debugInfo = {
name: debugInfo.name,
start: debugInfo.start,
end: endTime,
byteSize: newByteLength,
value: debugInfo.value,
owner: debugInfo.owner,
debugStack: debugInfo.debugStack,
debugTask: debugInfo.debugTask,
};
streamState._debugTargetChunkSize = newByteLength + MIN_CHUNK_SIZE;
} else {
debugInfo.end = endTime;
debugInfo.byteSize = newByteLength;
}
}
}
function addAsyncInfo(chunk: SomeChunk<any>, asyncInfo: ReactAsyncInfo): void {
const value = resolveLazy(chunk.value);
if (
typeof value === 'object' &&
value !== null &&
(isArray(value) ||
typeof value[ASYNC_ITERATOR] === 'function' ||
value.$$typeof === REACT_ELEMENT_TYPE ||
value.$$typeof === REACT_LAZY_TYPE)
) {
if (isArray(value._debugInfo)) {
value._debugInfo.push(asyncInfo);
} else {
Object.defineProperty((value: any), '_debugInfo', {
configurable: false,
enumerable: false,
writable: true,
value: [asyncInfo],
});
}
} else {
chunk._debugInfo.push(asyncInfo);
}
}
function resolveChunkDebugInfo(
response: Response,
streamState: StreamState,
chunk: SomeChunk<any>,
): void {
if (__DEV__ && enableAsyncDebugInfo) {
if (response._debugIOStarted) {
const asyncInfo: ReactAsyncInfo = {awaited: streamState._debugInfo};
if (chunk.status === PENDING || chunk.status === BLOCKED) {
const boundAddAsyncInfo = addAsyncInfo.bind(null, chunk, asyncInfo);
chunk.then(boundAddAsyncInfo, boundAddAsyncInfo);
} else {
addAsyncInfo(chunk, asyncInfo);
}
}
}
}
function resolveDebugHalt(response: Response, id: number): void {
const chunks = response._chunks;
let chunk = chunks.get(id);
if (!chunk) {
chunks.set(id, (chunk = createPendingChunk(response)));
} else {
}
if (chunk.status !== PENDING && chunk.status !== BLOCKED) {
return;
}
releasePendingChunk(response, chunk);
const haltedChunk: HaltedChunk<any> = (chunk: any);
haltedChunk.status = HALTED;
haltedChunk.value = null;
haltedChunk.reason = null;
}
function resolveModel(
response: Response,
id: number,
model: UninitializedModel,
streamState: StreamState,
): void {
const chunks = response._chunks;
const chunk = chunks.get(id);
if (!chunk) {
const newChunk: ResolvedModelChunk<any> = createResolvedModelChunk(
response,
model,
);
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, newChunk);
}
chunks.set(id, newChunk);
} else {
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, chunk);
}
resolveModelChunk(response, chunk, model);
}
}
function resolveText(
response: Response,
id: number,
text: string,
streamState: StreamState,
): void {
const chunks = response._chunks;
const chunk = chunks.get(id);
if (chunk && chunk.status !== PENDING) {
const streamChunk: InitializedStreamChunk<any> = (chunk: any);
const controller = streamChunk.reason;
controller.enqueueValue(text);
return;
}
if (chunk) {
releasePendingChunk(response, chunk);
}
const newChunk = createInitializedTextChunk(response, text);
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, newChunk);
}
chunks.set(id, newChunk);
}
function resolveBuffer(
response: Response,
id: number,
buffer: $ArrayBufferView | ArrayBuffer,
streamState: StreamState,
): void {
const chunks = response._chunks;
const chunk = chunks.get(id);
if (chunk && chunk.status !== PENDING) {
const streamChunk: InitializedStreamChunk<any> = (chunk: any);
const controller = streamChunk.reason;
controller.enqueueValue(buffer);
return;
}
if (chunk) {
releasePendingChunk(response, chunk);
}
const newChunk = createInitializedBufferChunk(response, buffer);
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, newChunk);
}
chunks.set(id, newChunk);
}
function resolveModule(
response: Response,
id: number,
model: UninitializedModel,
streamState: StreamState,
): void {
const chunks = response._chunks;
const chunk = chunks.get(id);
const clientReferenceMetadata: ClientReferenceMetadata = parseModel(
response,
model,
);
const clientReference = resolveClientReference<$FlowFixMe>(
response._bundlerConfig,
clientReferenceMetadata,
);
prepareDestinationForModule(
response._moduleLoading,
response._nonce,
clientReferenceMetadata,
);
const promise = preloadModule(clientReference);
if (promise) {
let blockedChunk: BlockedChunk<any>;
if (!chunk) {
blockedChunk = createBlockedChunk(response);
chunks.set(id, blockedChunk);
} else {
releasePendingChunk(response, chunk);
blockedChunk = (chunk: any);
blockedChunk.status = BLOCKED;
}
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, blockedChunk);
}
promise.then(
() => resolveModuleChunk(response, blockedChunk, clientReference),
error => triggerErrorOnChunk(response, blockedChunk, error),
);
} else {
if (!chunk) {
const newChunk = createResolvedModuleChunk(response, clientReference);
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, newChunk);
}
chunks.set(id, newChunk);
} else {
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, chunk);
}
resolveModuleChunk(response, chunk, clientReference);
}
}
}
function resolveStream<T: ReadableStream | $AsyncIterable<any, any, void>>(
response: Response,
id: number,
stream: T,
controller: FlightStreamController,
streamState: StreamState,
): void {
const chunks = response._chunks;
const chunk = chunks.get(id);
if (!chunk) {
const newChunk = createInitializedStreamChunk(response, stream, controller);
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, newChunk);
}
chunks.set(id, newChunk);
return;
}
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, chunk);
}
if (chunk.status !== PENDING) {
return;
}
const resolveListeners = chunk.value;
if (__DEV__) {
if (chunk._debugChunk != null) {
const prevHandler = initializingHandler;
const prevChunk = initializingChunk;
initializingHandler = null;
const cyclicChunk: BlockedChunk<T> = (chunk: any);
cyclicChunk.status = BLOCKED;
cyclicChunk.value = null;
cyclicChunk.reason = null;
if ((enableProfilerTimer && enableComponentPerformanceTrack) || __DEV__) {
initializingChunk = cyclicChunk;
}
try {
initializeDebugChunk(response, chunk);
if (initializingHandler !== null) {
if (initializingHandler.errored) {
} else if (initializingHandler.deps > 0) {
initializingHandler.value = stream;
initializingHandler.reason = controller;
initializingHandler.chunk = cyclicChunk;
return;
}
}
} finally {
initializingHandler = prevHandler;
initializingChunk = prevChunk;
}
}
}
const resolvedChunk: InitializedStreamChunk<T> = (chunk: any);
resolvedChunk.status = INITIALIZED;
resolvedChunk.value = stream;
resolvedChunk.reason = controller;
if (resolveListeners !== null) {
wakeChunk(response, resolveListeners, chunk.value, (chunk: any));
} else {
if (__DEV__) {
processChunkDebugInfo(response, resolvedChunk, stream);
}
}
}
function startReadableStream<T>(
response: Response,
id: number,
type: void | 'bytes',
streamState: StreamState,
): void {
let controller: ReadableStreamController = (null: any);
let closed = false;
const stream = new ReadableStream({
type: type,
start(c) {
controller = c;
},
});
let previousBlockedChunk: SomeChunk<T> | null = null;
const flightController = {
enqueueValue(value: T): void {
if (previousBlockedChunk === null) {
controller.enqueue(value);
} else {
previousBlockedChunk.then(function () {
controller.enqueue(value);
});
}
},
enqueueModel(json: UninitializedModel): void {
if (previousBlockedChunk === null) {
const chunk: ResolvedModelChunk<T> = createResolvedModelChunk(
response,
json,
);
initializeModelChunk(chunk);
const initializedChunk: SomeChunk<T> = chunk;
if (initializedChunk.status === INITIALIZED) {
controller.enqueue(initializedChunk.value);
} else {
chunk.then(
v => controller.enqueue(v),
e => controller.error((e: any)),
);
previousBlockedChunk = chunk;
}
} else {
const blockedChunk = previousBlockedChunk;
const chunk: SomeChunk<T> = createPendingChunk(response);
chunk.then(
v => controller.enqueue(v),
e => controller.error((e: any)),
);
previousBlockedChunk = chunk;
blockedChunk.then(function () {
if (previousBlockedChunk === chunk) {
previousBlockedChunk = null;
}
resolveModelChunk(response, chunk, json);
});
}
},
close(json: UninitializedModel): void {
if (closed) {
return;
}
closed = true;
if (previousBlockedChunk === null) {
controller.close();
} else {
const blockedChunk = previousBlockedChunk;
previousBlockedChunk = null;
blockedChunk.then(() => controller.close());
}
},
error(error: mixed): void {
if (closed) {
return;
}
closed = true;
if (previousBlockedChunk === null) {
controller.error(error);
} else {
const blockedChunk = previousBlockedChunk;
previousBlockedChunk = null;
blockedChunk.then(() => controller.error((error: any)));
}
},
};
resolveStream(response, id, stream, flightController, streamState);
}
function asyncIterator(this: $AsyncIterator<any, any, void>) {
return this;
}
function createIterator<T>(
next: (arg: void) => SomeChunk<IteratorResult<T, T>>,
): $AsyncIterator<T, T, void> {
const iterator: any = {
next: next,
};
(iterator: any)[ASYNC_ITERATOR] = asyncIterator;
return iterator;
}
function startAsyncIterable<T>(
response: Response,
id: number,
iterator: boolean,
streamState: StreamState,
): void {
const buffer: Array<SomeChunk<IteratorResult<T, T>>> = [];
let closed = false;
let nextWriteIndex = 0;
const flightController = {
enqueueValue(value: T): void {
if (nextWriteIndex === buffer.length) {
buffer[nextWriteIndex] = createInitializedIteratorResultChunk(
response,
value,
false,
);
} else {
const chunk: PendingChunk<IteratorResult<T, T>> = (buffer[
nextWriteIndex
]: any);
const resolveListeners = chunk.value;
const rejectListeners = chunk.reason;
const initializedChunk: InitializedChunk<IteratorResult<T, T>> =
(chunk: any);
initializedChunk.status = INITIALIZED;
initializedChunk.value = {done: false, value: value};
initializedChunk.reason = null;
if (resolveListeners !== null) {
wakeChunkIfInitialized(
response,
chunk,
resolveListeners,
rejectListeners,
);
}
}
nextWriteIndex++;
},
enqueueModel(value: UninitializedModel): void {
if (nextWriteIndex === buffer.length) {
buffer[nextWriteIndex] = createResolvedIteratorResultChunk(
response,
value,
false,
);
} else {
resolveIteratorResultChunk(
response,
buffer[nextWriteIndex],
value,
false,
);
}
nextWriteIndex++;
},
close(value: UninitializedModel): void {
if (closed) {
return;
}
closed = true;
if (nextWriteIndex === buffer.length) {
buffer[nextWriteIndex] = createResolvedIteratorResultChunk(
response,
value,
true,
);
} else {
resolveIteratorResultChunk(
response,
buffer[nextWriteIndex],
value,
true,
);
}
nextWriteIndex++;
while (nextWriteIndex < buffer.length) {
resolveIteratorResultChunk(
response,
buffer[nextWriteIndex++],
'"$undefined"',
true,
);
}
},
error(error: Error): void {
if (closed) {
return;
}
closed = true;
if (nextWriteIndex === buffer.length) {
buffer[nextWriteIndex] =
createPendingChunk<IteratorResult<T, T>>(response);
}
while (nextWriteIndex < buffer.length) {
triggerErrorOnChunk(response, buffer[nextWriteIndex++], error);
}
},
};
const iterable: $AsyncIterable<T, T, void> = ({}: any);
iterable[ASYNC_ITERATOR] = (): $AsyncIterator<T, T, void> => {
let nextReadIndex = 0;
return createIterator(arg => {
if (arg !== undefined) {
throw new Error(
'Values cannot be passed to next() of AsyncIterables passed to Client Components.',
);
}
if (nextReadIndex === buffer.length) {
if (closed) {
return new ReactPromise(
INITIALIZED,
{done: true, value: undefined},
null,
);
}
buffer[nextReadIndex] =
createPendingChunk<IteratorResult<T, T>>(response);
}
return buffer[nextReadIndex++];
});
};
resolveStream(
response,
id,
iterator ? iterable[ASYNC_ITERATOR]() : iterable,
flightController,
streamState,
);
}
function stopStream(
response: Response,
id: number,
row: UninitializedModel,
): void {
const chunks = response._chunks;
const chunk = chunks.get(id);
if (!chunk || chunk.status !== INITIALIZED) {
return;
}
if (__DEV__) {
if (--response._pendingChunks === 0) {
response._weakResponse.response = null;
}
}
const streamChunk: InitializedStreamChunk<any> = (chunk: any);
const controller = streamChunk.reason;
controller.close(row === '' ? '"$undefined"' : row);
}
type ErrorWithDigest = Error & {digest?: string};
function resolveErrorProd(response: Response): Error {
if (__DEV__) {
throw new Error(
'resolveErrorProd should never be called in development mode. Use resolveErrorDev instead. This is a bug in React.',
);
}
const error = new Error(
'An error occurred in the Server Components render. The specific message is omitted in production' +
' builds to avoid leaking sensitive details. A digest property is included on this error instance which' +
' may provide additional details about the nature of the error.',
);
error.stack = 'Error: ' + error.message;
return error;
}
function resolveErrorDev(
response: Response,
errorInfo: ReactErrorInfoDev,
): Error {
const name = errorInfo.name;
const message = errorInfo.message;
const stack = errorInfo.stack;
const env = errorInfo.env;
if (!__DEV__) {
throw new Error(
'resolveErrorDev should never be called in production mode. Use resolveErrorProd instead. This is a bug in React.',
);
}
let error;
const callStack = buildFakeCallStack(
response,
stack,
env,
false,
Error.bind(
null,
message ||
'An error occurred in the Server Components render but no message was provided',
),
);
let ownerTask: null | ConsoleTask = null;
if (errorInfo.owner != null) {
const ownerRef = errorInfo.owner.slice(1);
const owner = getOutlinedModel(response, ownerRef, {}, '', createModel);
if (owner !== null) {
ownerTask = initializeFakeTask(response, owner);
}
}
if (ownerTask === null) {
const rootTask = getRootTask(response, env);
if (rootTask != null) {
error = rootTask.run(callStack);
} else {
error = callStack();
}
} else {
error = ownerTask.run(callStack);
}
(error: any).name = name;
(error: any).environmentName = env;
return error;
}
function resolveErrorModel(
response: Response,
id: number,
row: UninitializedModel,
streamState: StreamState,
): void {
const chunks = response._chunks;
const chunk = chunks.get(id);
const errorInfo = JSON.parse(row);
let error;
if (__DEV__) {
error = resolveErrorDev(response, errorInfo);
} else {
error = resolveErrorProd(response);
}
(error: any).digest = errorInfo.digest;
const errorWithDigest: ErrorWithDigest = (error: any);
if (!chunk) {
const newChunk: ErroredChunk<any> = createErrorChunk(
response,
errorWithDigest,
);
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, newChunk);
}
chunks.set(id, newChunk);
} else {
if (__DEV__) {
resolveChunkDebugInfo(response, streamState, chunk);
}
triggerErrorOnChunk(response, chunk, errorWithDigest);
}
}
function resolveHint<Code: HintCode>(
response: Response,
code: Code,
model: UninitializedModel,
): void {
const hintModel: HintModel<Code> = parseModel(response, model);
dispatchHint(code, hintModel);
}
const supportsCreateTask = __DEV__ && !!(console: any).createTask;
type FakeFunction<T> = (() => T) => T;
const fakeFunctionCache: Map<string, FakeFunction<any>> = __DEV__
? new Map()
: (null: any);
let fakeFunctionIdx = 0;
function createFakeFunction<T>(
name: string,
filename: string,
sourceMap: null | string,
line: number,
col: number,
enclosingLine: number,
enclosingCol: number,
environmentName: string,
): FakeFunction<T> {
const comment =
'/* This module was rendered by a Server Component. Turn on Source Maps to see the server source. */';
if (!name) {
name = '<anonymous>';
}
const encodedName = JSON.stringify(name);
let code;
if (enclosingLine < 1) {
enclosingLine = 0;
} else {
enclosingLine--;
}
if (enclosingCol < 1) {
enclosingCol = 0;
} else {
enclosingCol--;
}
if (line < 1) {
line = 0;
} else {
line--;
}
if (col < 1) {
col = 0;
} else {
col--;
}
if (line < enclosingLine || (line === enclosingLine && col < enclosingCol)) {
enclosingLine = 0;
enclosingCol = 0;
}
if (line < 1) {
const minCol = encodedName.length + 3;
let enclosingColDistance = enclosingCol - minCol;
if (enclosingColDistance < 0) {
enclosingColDistance = 0;
}
let colDistance = col - enclosingColDistance - minCol - 3;
if (colDistance < 0) {
colDistance = 0;
}
code =
'({' +
encodedName +
':' +
' '.repeat(enclosingColDistance) +
'_=>' +
' '.repeat(colDistance) +
'_()})';
} else if (enclosingLine < 1) {
const minCol = encodedName.length + 3;
let enclosingColDistance = enclosingCol - minCol;
if (enclosingColDistance < 0) {
enclosingColDistance = 0;
}
code =
'({' +
encodedName +
':' +
' '.repeat(enclosingColDistance) +
'_=>' +
'\n'.repeat(line - enclosingLine) +
' '.repeat(col) +
'_()})';
} else if (enclosingLine === line) {
let colDistance = col - enclosingCol - 3;
if (colDistance < 0) {
colDistance = 0;
}
code =
'\n'.repeat(enclosingLine - 1) +
'({' +
encodedName +
':\n' +
' '.repeat(enclosingCol) +
'_=>' +
' '.repeat(colDistance) +
'_()})';
} else {
code =
'\n'.repeat(enclosingLine - 1) +
'({' +
encodedName +
':\n' +
' '.repeat(enclosingCol) +
'_=>' +
'\n'.repeat(line - enclosingLine) +
' '.repeat(col) +
'_()})';
}
if (enclosingLine < 1) {
code = code + '\n' + comment;
} else {
code = comment + code;
}
if (filename.startsWith('/')) {
filename = 'file://' + filename;
}
if (sourceMap) {
code +=
'\n//# sourceURL=about://React/' +
encodeURIComponent(environmentName) +
'/' +
encodeURI(filename) +
'?' +
fakeFunctionIdx++;
code += '\n//# sourceMappingURL=' + sourceMap;
} else if (filename) {
code += '\n//# sourceURL=' + encodeURI(filename);
} else {
code += '\n//# sourceURL=<anonymous>';
}
let fn: FakeFunction<T>;
try {
fn = (0, eval)(code)[name];
} catch (x) {
fn = function (_) {
return _();
};
Object.defineProperty(
fn,
'name',
{value: name},
);
}
return fn;
}
function buildFakeCallStack<T>(
response: Response,
stack: ReactStackTrace,
environmentName: string,
useEnclosingLine: boolean,
innerCall: () => T,
): () => T {
let callStack = innerCall;
for (let i = 0; i < stack.length; i++) {
const frame = stack[i];
const frameKey =
frame.join('-') +
'-' +
environmentName +
(useEnclosingLine ? '-e' : '-n');
let fn = fakeFunctionCache.get(frameKey);
if (fn === undefined) {
const [name, filename, line, col, enclosingLine, enclosingCol] = frame;
const findSourceMapURL = response._debugFindSourceMapURL;
const sourceMap = findSourceMapURL
? findSourceMapURL(filename, environmentName)
: null;
fn = createFakeFunction(
name,
filename,
sourceMap,
line,
col,
useEnclosingLine ? line : enclosingLine,
useEnclosingLine ? col : enclosingCol,
environmentName,
);
fakeFunctionCache.set(frameKey, fn);
}
callStack = fn.bind(null, callStack);
}
return callStack;
}
function getRootTask(
response: Response,
childEnvironmentName: string,
): null | ConsoleTask {
const rootTask = response._debugRootTask;
if (!rootTask) {
return null;
}
if (response._rootEnvironmentName !== childEnvironmentName) {
const createTaskFn = (console: any).createTask.bind(
console,
'"use ' + childEnvironmentName.toLowerCase() + '"',
);
return rootTask.run(createTaskFn);
}
return rootTask;
}
function initializeFakeTask(
response: Response,
debugInfo: ReactComponentInfo | ReactAsyncInfo | ReactIOInfo,
): null | ConsoleTask {
if (!supportsCreateTask) {
return null;
}
if (debugInfo.stack == null) {
return null;
}
const cachedEntry = debugInfo.debugTask;
if (cachedEntry !== undefined) {
return cachedEntry;
}
const useEnclosingLine = debugInfo.key === undefined;
const stack = debugInfo.stack;
const env: string =
debugInfo.env == null ? response._rootEnvironmentName : debugInfo.env;
const ownerEnv: string =
debugInfo.owner == null || debugInfo.owner.env == null
? response._rootEnvironmentName
: debugInfo.owner.env;
const ownerTask =
debugInfo.owner == null
? null
: initializeFakeTask(response, debugInfo.owner);
const taskName =
env !== ownerEnv
? '"use ' + env.toLowerCase() + '"'
:
debugInfo.key !== undefined
? getServerComponentTaskName(((debugInfo: any): ReactComponentInfo))
: debugInfo.name !== undefined
? getIOInfoTaskName(((debugInfo: any): ReactIOInfo))
: getAsyncInfoTaskName(((debugInfo: any): ReactAsyncInfo));
return (debugInfo.debugTask = buildFakeTask(
response,
ownerTask,
stack,
taskName,
ownerEnv,
useEnclosingLine,
));
}
function buildFakeTask(
response: Response,
ownerTask: null | ConsoleTask,
stack: ReactStackTrace,
taskName: string,
env: string,
useEnclosingLine: boolean,
): ConsoleTask {
const createTaskFn = (console: any).createTask.bind(console, taskName);
const callStack = buildFakeCallStack(
response,
stack,
env,
useEnclosingLine,
createTaskFn,
);
if (ownerTask === null) {
const rootTask = getRootTask(response, env);
if (rootTask != null) {
return rootTask.run(callStack);
} else {
return callStack();
}
} else {
return ownerTask.run(callStack);
}
}
const createFakeJSXCallStack = {
react_stack_bottom_frame: function (
response: Response,
stack: ReactStackTrace,
environmentName: string,
): Error {
const callStackForError = buildFakeCallStack(
response,
stack,
environmentName,
false,
fakeJSXCallSite,
);
return callStackForError();
},
};
const createFakeJSXCallStackInDEV: (
response: Response,
stack: ReactStackTrace,
environmentName: string,
) => Error = __DEV__
?
(createFakeJSXCallStack.react_stack_bottom_frame.bind(
createFakeJSXCallStack,
): any)
: (null: any);
function fakeJSXCallSite() {
return new Error('react-stack-top-frame');
}
function initializeFakeStack(
response: Response,
debugInfo: ReactComponentInfo | ReactAsyncInfo | ReactIOInfo,
): void {
const cachedEntry = debugInfo.debugStack;
if (cachedEntry !== undefined) {
return;
}
if (debugInfo.stack != null) {
const stack = debugInfo.stack;
const env = debugInfo.env == null ? '' : debugInfo.env;
debugInfo.debugStack = createFakeJSXCallStackInDEV(response, stack, env);
}
const owner = debugInfo.owner;
if (owner != null) {
initializeFakeStack(response, owner);
if (owner.debugLocation === undefined && debugInfo.debugStack != null) {
owner.debugLocation = debugInfo.debugStack;
}
}
}
function initializeDebugInfo(
response: Response,
debugInfo: ReactDebugInfoEntry,
): ReactDebugInfoEntry {
if (!__DEV__) {
throw new Error(
'initializeDebugInfo should never be called in production mode. This is a bug in React.',
);
}
if (debugInfo.stack !== undefined) {
const componentInfoOrAsyncInfo: ReactComponentInfo | ReactAsyncInfo =
debugInfo;
initializeFakeTask(response, componentInfoOrAsyncInfo);
}
if (debugInfo.owner == null && response._debugRootOwner != null) {
const componentInfoOrAsyncInfo: ReactComponentInfo | ReactAsyncInfo =
debugInfo;
componentInfoOrAsyncInfo.owner = response._debugRootOwner;
componentInfoOrAsyncInfo.stack = null;
componentInfoOrAsyncInfo.debugStack = response._debugRootStack;
componentInfoOrAsyncInfo.debugTask = response._debugRootTask;
} else if (debugInfo.stack !== undefined) {
const componentInfoOrAsyncInfo: ReactComponentInfo | ReactAsyncInfo =
debugInfo;
initializeFakeStack(response, componentInfoOrAsyncInfo);
}
if (enableProfilerTimer && enableComponentPerformanceTrack) {
if (typeof debugInfo.time === 'number') {
debugInfo = {
time: debugInfo.time + response._timeOrigin,
};
}
}
return debugInfo;
}
function resolveDebugModel(
response: Response,
id: number,
json: UninitializedModel,
): void {
const parentChunk = getChunk(response, id);
if (
parentChunk.status === INITIALIZED ||
parentChunk.status === ERRORED ||
parentChunk.status === HALTED ||
parentChunk.status === BLOCKED
) {
return;
}
if (parentChunk.status === RESOLVED_MODULE) {
return;
}
const previousChunk = parentChunk._debugChunk;
const debugChunk: ResolvedModelChunk<ReactDebugInfoEntry> =
createResolvedModelChunk(response, json);
debugChunk._debugChunk = previousChunk;
parentChunk._debugChunk = debugChunk;
initializeDebugChunk(response, parentChunk);
if (
__DEV__ &&
((debugChunk: any): SomeChunk<any>).status === BLOCKED &&
(response._debugChannel === undefined ||
!response._debugChannel.hasReadable)
) {
if (json[0] === '"' && json[1] === '$') {
const path = json.slice(2, json.length - 1).split(':');
const outlinedId = parseInt(path[0], 16);
const chunk = getChunk(response, outlinedId);
if (chunk.status === PENDING) {
parentChunk._debugChunk = null;
}
}
}
}
let currentOwnerInDEV: null | ReactComponentInfo = null;
function getCurrentStackInDEV(): string {
if (__DEV__) {
const owner: null | ReactComponentInfo = currentOwnerInDEV;
if (owner === null) {
return '';
}
return getOwnerStackByComponentInfoInDev(owner);
}
return '';
}
const replayConsoleWithCallStack = {
react_stack_bottom_frame: function (
response: Response,
payload: ConsoleEntry,
): void {
const methodName = payload[0];
const stackTrace = payload[1];
const owner = payload[2];
const env = payload[3];
const args = payload.slice(4);
const prevStack = ReactSharedInternals.getCurrentStack;
ReactSharedInternals.getCurrentStack = getCurrentStackInDEV;
currentOwnerInDEV =
owner === null ? (response._debugRootOwner: any) : owner;
try {
const callStack = buildFakeCallStack(
response,
stackTrace,
env,
false,
bindToConsole(methodName, args, env),
);
if (owner != null) {
const task = initializeFakeTask(response, owner);
initializeFakeStack(response, owner);
if (task !== null) {
task.run(callStack);
return;
}
}
const rootTask = getRootTask(response, env);
if (rootTask != null) {
rootTask.run(callStack);
return;
}
callStack();
} finally {
currentOwnerInDEV = null;
ReactSharedInternals.getCurrentStack = prevStack;
}
},
};
const replayConsoleWithCallStackInDEV: (
response: Response,
payload: ConsoleEntry,
) => void = __DEV__
?
(replayConsoleWithCallStack.react_stack_bottom_frame.bind(
replayConsoleWithCallStack,
): any)
: (null: any);
type ConsoleEntry = [
string,
ReactStackTrace,
null | ReactComponentInfo,
string,
mixed,
];
function resolveConsoleEntry(
response: Response,
json: UninitializedModel,
): void {
if (!__DEV__) {
throw new Error(
'resolveConsoleEntry should never be called in production mode. This is a bug in React.',
);
}
if (!response._replayConsole) {
return;
}
const blockedChunk = response._blockedConsole;
if (blockedChunk == null) {
const chunk: ResolvedModelChunk<ConsoleEntry> = createResolvedModelChunk(
response,
json,
);
initializeModelChunk(chunk);
const initializedChunk: SomeChunk<ConsoleEntry> = chunk;
if (initializedChunk.status === INITIALIZED) {
replayConsoleWithCallStackInDEV(response, initializedChunk.value);
} else {
chunk.then(
v => replayConsoleWithCallStackInDEV(response, v),
e => {
},
);
response._blockedConsole = chunk;
}
} else {
const chunk: SomeChunk<ConsoleEntry> = createPendingChunk(response);
chunk.then(
v => replayConsoleWithCallStackInDEV(response, v),
e => {
},
);
response._blockedConsole = chunk;
const unblock = () => {
if (response._blockedConsole === chunk) {
response._blockedConsole = null;
}
resolveModelChunk(response, chunk, json);
};
blockedChunk.then(unblock, unblock);
}
}
function initializeIOInfo(response: Response, ioInfo: ReactIOInfo): void {
if (ioInfo.stack !== undefined) {
initializeFakeTask(response, ioInfo);
initializeFakeStack(response, ioInfo);
}
ioInfo.start += response._timeOrigin;
ioInfo.end += response._timeOrigin;
if (enableComponentPerformanceTrack && response._replayConsole) {
const env = response._rootEnvironmentName;
const promise = ioInfo.value;
if (promise) {
const thenable: Thenable<mixed> = (promise: any);
switch (thenable.status) {
case INITIALIZED:
logIOInfo(ioInfo, env, thenable.value);
break;
case ERRORED:
logIOInfoErrored(ioInfo, env, thenable.reason);
break;
default:
promise.then(
logIOInfo.bind(null, ioInfo, env),
logIOInfoErrored.bind(null, ioInfo, env),
);
break;
}
} else {
logIOInfo(ioInfo, env, undefined);
}
}
}
function resolveIOInfo(
response: Response,
id: number,
model: UninitializedModel,
): void {
const chunks = response._chunks;
let chunk = chunks.get(id);
if (!chunk) {
chunk = createResolvedModelChunk(response, model);
chunks.set(id, chunk);
initializeModelChunk(chunk);
} else {
resolveModelChunk(response, chunk, model);
if (chunk.status === RESOLVED_MODEL) {
initializeModelChunk(chunk);
}
}
if (chunk.status === INITIALIZED) {
initializeIOInfo(response, chunk.value);
} else {
chunk.then(
v => {
initializeIOInfo(response, v);
},
e => {
},
);
}
}
function mergeBuffer(
buffer: Array<Uint8Array>,
lastChunk: Uint8Array,
): Uint8Array {
const l = buffer.length;
let byteLength = lastChunk.length;
for (let i = 0; i < l; i++) {
byteLength += buffer[i].byteLength;
}
const result = new Uint8Array(byteLength);
let offset = 0;
for (let i = 0; i < l; i++) {
const chunk = buffer[i];
result.set(chunk, offset);
offset += chunk.byteLength;
}
result.set(lastChunk, offset);
return result;
}
function resolveTypedArray(
response: Response,
id: number,
buffer: Array<Uint8Array>,
lastChunk: Uint8Array,
constructor: any,
bytesPerElement: number,
streamState: StreamState,
): void {
const chunk =
buffer.length === 0 && lastChunk.byteOffset % bytesPerElement === 0
? lastChunk
: mergeBuffer(buffer, lastChunk);
const view: $ArrayBufferView = new constructor(
chunk.buffer,
chunk.byteOffset,
chunk.byteLength / bytesPerElement,
);
resolveBuffer(response, id, view, streamState);
}
function logComponentInfo(
response: Response,
root: SomeChunk<any>,
componentInfo: ReactComponentInfo,
trackIdx: number,
startTime: number,
componentEndTime: number,
childrenEndTime: number,
isLastComponent: boolean,
): void {
if (
isLastComponent &&
root.status === ERRORED &&
root.reason !== response._closedReason
) {
logComponentErrored(
componentInfo,
trackIdx,
startTime,
componentEndTime,
childrenEndTime,
response._rootEnvironmentName,
root.reason,
);
} else {
logComponentRender(
componentInfo,
trackIdx,
startTime,
componentEndTime,
childrenEndTime,
response._rootEnvironmentName,
);
}
}
function flushComponentPerformance(
response: Response,
root: SomeChunk<any>,
trackIdx: number,
trackTime: number,
parentEndTime: number,
): ProfilingResult {
if (!enableProfilerTimer || !enableComponentPerformanceTrack) {
throw new Error(
'flushComponentPerformance should never be called in production mode. This is a bug in React.',
);
}
if (!isArray(root._children)) {
const previousResult: ProfilingResult = root._children;
const previousEndTime = previousResult.endTime;
if (
parentEndTime > -Infinity &&
parentEndTime < previousEndTime &&
previousResult.component !== null
) {
logDedupedComponentRender(
previousResult.component,
trackIdx,
parentEndTime,
previousEndTime,
response._rootEnvironmentName,
);
}
previousResult.track = trackIdx;
return previousResult;
}
const children = root._children;
let debugInfo = null;
if (__DEV__) {
debugInfo = root._debugInfo;
if (debugInfo.length === 0 && root.status === 'fulfilled') {
const resolvedValue = resolveLazy(root.value);
if (
typeof resolvedValue === 'object' &&
resolvedValue !== null &&
(isArray(resolvedValue) ||
typeof resolvedValue[ASYNC_ITERATOR] === 'function' ||
resolvedValue.$$typeof === REACT_ELEMENT_TYPE ||
resolvedValue.$$typeof === REACT_LAZY_TYPE) &&
isArray(resolvedValue._debugInfo)
) {
debugInfo = resolvedValue._debugInfo;
}
}
}
if (debugInfo) {
let startTime = 0;
for (let i = 0; i < debugInfo.length; i++) {
const info = debugInfo[i];
if (typeof info.time === 'number') {
startTime = info.time;
}
if (typeof info.name === 'string') {
if (startTime < trackTime) {
trackIdx++;
}
trackTime = startTime;
break;
}
}
for (let i = debugInfo.length - 1; i >= 0; i--) {
const info = debugInfo[i];
if (typeof info.time === 'number') {
if (info.time > parentEndTime) {
parentEndTime = info.time;
break;
}
}
}
}
const result: ProfilingResult = {
track: trackIdx,
endTime: -Infinity,
component: null,
};
root._children = result;
let childrenEndTime = -Infinity;
let childTrackIdx = trackIdx;
let childTrackTime = trackTime;
for (let i = 0; i < children.length; i++) {
const childResult = flushComponentPerformance(
response,
children[i],
childTrackIdx,
childTrackTime,
parentEndTime,
);
if (childResult.component !== null) {
result.component = childResult.component;
}
childTrackIdx = childResult.track;
const childEndTime = childResult.endTime;
if (childEndTime > childTrackTime) {
childTrackTime = childEndTime;
}
if (childEndTime > childrenEndTime) {
childrenEndTime = childEndTime;
}
}
if (debugInfo) {
let componentEndTime = 0;
let isLastComponent = true;
let endTime = -1;
let endTimeIdx = -1;
for (let i = debugInfo.length - 1; i >= 0; i--) {
const info = debugInfo[i];
if (typeof info.time !== 'number') {
continue;
}
if (componentEndTime === 0) {
componentEndTime = info.time;
}
const time = info.time;
if (endTimeIdx > -1) {
for (let j = endTimeIdx - 1; j > i; j--) {
const candidateInfo = debugInfo[j];
if (typeof candidateInfo.name === 'string') {
if (componentEndTime > childrenEndTime) {
childrenEndTime = componentEndTime;
}
const componentInfo: ReactComponentInfo = candidateInfo;
logComponentInfo(
response,
root,
componentInfo,
trackIdx,
time,
componentEndTime,
childrenEndTime,
isLastComponent,
);
componentEndTime = time;
result.component = componentInfo;
isLastComponent = false;
} else if (
candidateInfo.awaited &&
candidateInfo.awaited.env != null
) {
if (endTime > childrenEndTime) {
childrenEndTime = endTime;
}
const asyncInfo: ReactAsyncInfo = candidateInfo;
const env = response._rootEnvironmentName;
const promise = asyncInfo.awaited.value;
if (promise) {
const thenable: Thenable<mixed> = (promise: any);
switch (thenable.status) {
case INITIALIZED:
logComponentAwait(
asyncInfo,
trackIdx,
time,
endTime,
env,
thenable.value,
);
break;
case ERRORED:
logComponentAwaitErrored(
asyncInfo,
trackIdx,
time,
endTime,
env,
thenable.reason,
);
break;
default:
logComponentAwait(
asyncInfo,
trackIdx,
time,
endTime,
env,
undefined,
);
break;
}
} else {
logComponentAwait(
asyncInfo,
trackIdx,
time,
endTime,
env,
undefined,
);
}
}
}
} else {
endTime = time;
for (let j = debugInfo.length - 1; j > i; j--) {
const candidateInfo = debugInfo[j];
if (typeof candidateInfo.name === 'string') {
if (componentEndTime > childrenEndTime) {
childrenEndTime = componentEndTime;
}
const componentInfo: ReactComponentInfo = candidateInfo;
const env = response._rootEnvironmentName;
logComponentAborted(
componentInfo,
trackIdx,
time,
componentEndTime,
childrenEndTime,
env,
);
componentEndTime = time;
result.component = componentInfo;
isLastComponent = false;
} else if (
candidateInfo.awaited &&
candidateInfo.awaited.env != null
) {
const asyncInfo: ReactAsyncInfo = candidateInfo;
const env = response._rootEnvironmentName;
if (asyncInfo.awaited.end > endTime) {
endTime = asyncInfo.awaited.end;
}
if (endTime > childrenEndTime) {
childrenEndTime = endTime;
}
logComponentAwaitAborted(asyncInfo, trackIdx, time, endTime, env);
}
}
}
endTime = time;
endTimeIdx = i;
}
}
result.endTime = childrenEndTime;
return result;
}
function flushInitialRenderPerformance(response: Response): void {
if (
enableProfilerTimer &&
enableComponentPerformanceTrack &&
response._replayConsole
) {
const rootChunk = getChunk(response, 0);
if (isArray(rootChunk._children)) {
markAllTracksInOrder();
flushComponentPerformance(response, rootChunk, 0, -Infinity, -Infinity);
}
}
}
function processFullBinaryRow(
response: Response,
streamState: StreamState,
id: number,
tag: number,
buffer: Array<Uint8Array>,
chunk: Uint8Array,
): void {
switch (tag) {
case 65 :
resolveBuffer(
response,
id,
mergeBuffer(buffer, chunk).buffer,
streamState,
);
return;
case 79 :
resolveTypedArray(response, id, buffer, chunk, Int8Array, 1, streamState);
return;
case 111 :
resolveBuffer(
response,
id,
buffer.length === 0 ? chunk : mergeBuffer(buffer, chunk),
streamState,
);
return;
case 85 :
resolveTypedArray(
response,
id,
buffer,
chunk,
Uint8ClampedArray,
1,
streamState,
);
return;
case 83 :
resolveTypedArray(
response,
id,
buffer,
chunk,
Int16Array,
2,
streamState,
);
return;
case 115 :
resolveTypedArray(
response,
id,
buffer,
chunk,
Uint16Array,
2,
streamState,
);
return;
case 76 :
resolveTypedArray(
response,
id,
buffer,
chunk,
Int32Array,
4,
streamState,
);
return;
case 108 :
resolveTypedArray(
response,
id,
buffer,
chunk,
Uint32Array,
4,
streamState,
);
return;
case 71 :
resolveTypedArray(
response,
id,
buffer,
chunk,
Float32Array,
4,
streamState,
);
return;
case 103 :
resolveTypedArray(
response,
id,
buffer,
chunk,
Float64Array,
8,
streamState,
);
return;
case 77 :
resolveTypedArray(
response,
id,
buffer,
chunk,
BigInt64Array,
8,
streamState,
);
return;
case 109 :
resolveTypedArray(
response,
id,
buffer,
chunk,
BigUint64Array,
8,
streamState,
);
return;
case 86 :
resolveTypedArray(response, id, buffer, chunk, DataView, 1, streamState);
return;
}
const stringDecoder = response._stringDecoder;
let row = '';
for (let i = 0; i < buffer.length; i++) {
row += readPartialStringChunk(stringDecoder, buffer[i]);
}
row += readFinalStringChunk(stringDecoder, chunk);
processFullStringRow(response, streamState, id, tag, row);
}
function processFullStringRow(
response: Response,
streamState: StreamState,
id: number,
tag: number,
row: string,
): void {
switch (tag) {
case 73 : {
resolveModule(response, id, row, streamState);
return;
}
case 72 : {
const code: HintCode = (row[0]: any);
resolveHint(response, code, row.slice(1));
return;
}
case 69 : {
resolveErrorModel(response, id, row, streamState);
return;
}
case 84 : {
resolveText(response, id, row, streamState);
return;
}
case 78 : {
if (
enableProfilerTimer &&
(enableComponentPerformanceTrack || enableAsyncDebugInfo)
) {
const timeOrigin: number = +row;
response._timeOrigin =
timeOrigin -
performance.timeOrigin;
return;
}
}
case 68 : {
if (__DEV__) {
resolveDebugModel(response, id, row);
return;
}
}
case 74 : {
if (enableProfilerTimer && enableAsyncDebugInfo) {
resolveIOInfo(response, id, row);
return;
}
}
case 87 : {
if (__DEV__) {
resolveConsoleEntry(response, row);
return;
}
throw new Error(
'Failed to read a RSC payload created by a development version of React ' +
'on the server while using a production version on the client. Always use ' +
'matching versions on the server and the client.',
);
}
case 82 : {
startReadableStream(response, id, undefined, streamState);
return;
}
case 114 : {
startReadableStream(response, id, 'bytes', streamState);
return;
}
case 88 : {
startAsyncIterable(response, id, false, streamState);
return;
}
case 120 : {
startAsyncIterable(response, id, true, streamState);
return;
}
case 67 : {
stopStream(response, id, row);
return;
}
default: {
if (__DEV__ && row === '') {
resolveDebugHalt(response, id);
return;
}
resolveModel(response, id, row, streamState);
return;
}
}
}
export function processBinaryChunk(
weakResponse: WeakResponse,
streamState: StreamState,
chunk: Uint8Array,
): void {
if (hasGCedResponse(weakResponse)) {
return;
}
const response = unwrapWeakResponse(weakResponse);
let i = 0;
let rowState = streamState._rowState;
let rowID = streamState._rowID;
let rowTag = streamState._rowTag;
let rowLength = streamState._rowLength;
const buffer = streamState._buffer;
const chunkLength = chunk.length;
incrementChunkDebugInfo(streamState, chunkLength);
while (i < chunkLength) {
let lastIdx = -1;
switch (rowState) {
case ROW_ID: {
const byte = chunk[i++];
if (byte === 58 ) {
rowState = ROW_TAG;
} else {
rowID = (rowID << 4) | (byte > 96 ? byte - 87 : byte - 48);
}
continue;
}
case ROW_TAG: {
const resolvedRowTag = chunk[i];
if (
resolvedRowTag === 84 ||
resolvedRowTag === 65 ||
resolvedRowTag === 79 ||
resolvedRowTag === 111 ||
resolvedRowTag === 98 ||
resolvedRowTag === 85 ||
resolvedRowTag === 83 ||
resolvedRowTag === 115 ||
resolvedRowTag === 76 ||
resolvedRowTag === 108 ||
resolvedRowTag === 71 ||
resolvedRowTag === 103 ||
resolvedRowTag === 77 ||
resolvedRowTag === 109 ||
resolvedRowTag === 86
) {
rowTag = resolvedRowTag;
rowState = ROW_LENGTH;
i++;
} else if (
(resolvedRowTag > 64 && resolvedRowTag < 91) ||
resolvedRowTag === 35 ||
resolvedRowTag === 114 ||
resolvedRowTag === 120
) {
rowTag = resolvedRowTag;
rowState = ROW_CHUNK_BY_NEWLINE;
i++;
} else {
rowTag = 0;
rowState = ROW_CHUNK_BY_NEWLINE;
}
continue;
}
case ROW_LENGTH: {
const byte = chunk[i++];
if (byte === 44 ) {
rowState = ROW_CHUNK_BY_LENGTH;
} else {
rowLength = (rowLength << 4) | (byte > 96 ? byte - 87 : byte - 48);
}
continue;
}
case ROW_CHUNK_BY_NEWLINE: {
lastIdx = chunk.indexOf(10 , i);
break;
}
case ROW_CHUNK_BY_LENGTH: {
lastIdx = i + rowLength;
if (lastIdx > chunk.length) {
lastIdx = -1;
}
break;
}
}
const offset = chunk.byteOffset + i;
if (lastIdx > -1) {
const length = lastIdx - i;
const lastChunk = new Uint8Array(chunk.buffer, offset, length);
if (rowTag === 98 ) {
resolveBuffer(
response,
rowID,
lastIdx === chunkLength ? lastChunk : lastChunk.slice(),
streamState,
);
} else {
processFullBinaryRow(
response,
streamState,
rowID,
rowTag,
buffer,
lastChunk,
);
}
i = lastIdx;
if (rowState === ROW_CHUNK_BY_NEWLINE) {
i++;
}
rowState = ROW_ID;
rowTag = 0;
rowID = 0;
rowLength = 0;
buffer.length = 0;
} else {
const length = chunk.byteLength - i;
const remainingSlice = new Uint8Array(chunk.buffer, offset, length);
if (rowTag === 98 ) {
rowLength -= remainingSlice.byteLength;
resolveBuffer(response, rowID, remainingSlice, streamState);
} else {
buffer.push(remainingSlice);
rowLength -= remainingSlice.byteLength;
}
break;
}
}
streamState._rowState = rowState;
streamState._rowID = rowID;
streamState._rowTag = rowTag;
streamState._rowLength = rowLength;
}
export function processStringChunk(
weakResponse: WeakResponse,
streamState: StreamState,
chunk: string,
): void {
if (hasGCedResponse(weakResponse)) {
return;
}
const response = unwrapWeakResponse(weakResponse);
let i = 0;
let rowState = streamState._rowState;
let rowID = streamState._rowID;
let rowTag = streamState._rowTag;
let rowLength = streamState._rowLength;
const buffer = streamState._buffer;
const chunkLength = chunk.length;
incrementChunkDebugInfo(streamState, chunkLength);
while (i < chunkLength) {
let lastIdx = -1;
switch (rowState) {
case ROW_ID: {
const byte = chunk.charCodeAt(i++);
if (byte === 58 ) {
rowState = ROW_TAG;
} else {
rowID = (rowID << 4) | (byte > 96 ? byte - 87 : byte - 48);
}
continue;
}
case ROW_TAG: {
const resolvedRowTag = chunk.charCodeAt(i);
if (
resolvedRowTag === 84 ||
resolvedRowTag === 65 ||
resolvedRowTag === 79 ||
resolvedRowTag === 111 ||
resolvedRowTag === 85 ||
resolvedRowTag === 83 ||
resolvedRowTag === 115 ||
resolvedRowTag === 76 ||
resolvedRowTag === 108 ||
resolvedRowTag === 71 ||
resolvedRowTag === 103 ||
resolvedRowTag === 77 ||
resolvedRowTag === 109 ||
resolvedRowTag === 86
) {
rowTag = resolvedRowTag;
rowState = ROW_LENGTH;
i++;
} else if (
(resolvedRowTag > 64 && resolvedRowTag < 91) ||
resolvedRowTag === 114 ||
resolvedRowTag === 120
) {
rowTag = resolvedRowTag;
rowState = ROW_CHUNK_BY_NEWLINE;
i++;
} else {
rowTag = 0;
rowState = ROW_CHUNK_BY_NEWLINE;
}
continue;
}
case ROW_LENGTH: {
const byte = chunk.charCodeAt(i++);
if (byte === 44 ) {
rowState = ROW_CHUNK_BY_LENGTH;
} else {
rowLength = (rowLength << 4) | (byte > 96 ? byte - 87 : byte - 48);
}
continue;
}
case ROW_CHUNK_BY_NEWLINE: {
lastIdx = chunk.indexOf('\n', i);
break;
}
case ROW_CHUNK_BY_LENGTH: {
if (rowTag !== 84) {
throw new Error(
'Binary RSC chunks cannot be encoded as strings. ' +
'This is a bug in the wiring of the React streams.',
);
}
if (rowLength < chunk.length || chunk.length > rowLength * 3) {
throw new Error(
'String chunks need to be passed in their original shape. ' +
'Not split into smaller string chunks. ' +
'This is a bug in the wiring of the React streams.',
);
}
lastIdx = chunk.length;
break;
}
}
if (lastIdx > -1) {
if (buffer.length > 0) {
throw new Error(
'String chunks need to be passed in their original shape. ' +
'Not split into smaller string chunks. ' +
'This is a bug in the wiring of the React streams.',
);
}
const lastChunk = chunk.slice(i, lastIdx);
processFullStringRow(response, streamState, rowID, rowTag, lastChunk);
i = lastIdx;
if (rowState === ROW_CHUNK_BY_NEWLINE) {
i++;
}
rowState = ROW_ID;
rowTag = 0;
rowID = 0;
rowLength = 0;
buffer.length = 0;
} else if (chunk.length !== i) {
throw new Error(
'String chunks need to be passed in their original shape. ' +
'Not split into smaller string chunks. ' +
'This is a bug in the wiring of the React streams.',
);
}
}
streamState._rowState = rowState;
streamState._rowID = rowID;
streamState._rowTag = rowTag;
streamState._rowLength = rowLength;
}
function parseModel<T>(response: Response, json: UninitializedModel): T {
return JSON.parse(json, response._fromJSON);
}
function createFromJSONCallback(response: Response) {
return function (key: string, value: JSONValue) {
if (key === __PROTO__) {
return undefined;
}
if (typeof value === 'string') {
return parseModelString(response, this, key, value);
}
if (typeof value === 'object' && value !== null) {
return parseModelTuple(response, value);
}
return value;
};
}
export function close(weakResponse: WeakResponse): void {
reportGlobalError(weakResponse, new Error('Connection closed.'));
}
function getCurrentOwnerInDEV(): null | ReactComponentInfo {
return currentOwnerInDEV;
}
export function injectIntoDevTools(): boolean {
const internals: Object = {
bundleType: __DEV__ ? 1 : 0,
version: rendererVersion,
rendererPackageName: rendererPackageName,
currentDispatcherRef: ReactSharedInternals,
reconcilerVersion: ReactVersion,
getCurrentComponentInfo: getCurrentOwnerInDEV,
};
return injectInternals(internals);
}