From 5bc1e65efd5e9fa6ab16b63adbb080756f853766 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Mon, 1 May 2023 15:49:10 +0200 Subject: [PATCH] Add flag to switch to the experimental channel (#48896) This PR does three things: - Vendors the package `react-server-dom-webpack@experimental` as `react-server-dom-webpack-experimental` similar to React and React DOM - Upgrades all vendored React packages - Re-lands the `experimentalReact` flag to switch between `@next` and `@experimental` channels of React for app dir. Fix NEXT-926. --- package.json | 1 + .../crates/next-core/src/next_import_map.rs | 9 + packages/next/src/build/index.ts | 8 +- packages/next/src/build/utils.ts | 2 +- packages/next/src/build/webpack-config.ts | 75 +- .../build/webpack/loaders/next-app-loader.ts | 2 +- .../action-client-wrapper.ts | 6 +- .../nextjs-require-cache-hot-reloader.ts | 5 +- packages/next/src/client/app-call-server.ts | 4 +- packages/next/src/client/app-index.tsx | 4 +- .../router-reducer/fetch-server-response.ts | 4 +- .../LICENSE | 21 + ...-dom-webpack-client.browser.development.js | 1735 +++++++++ ...m-webpack-client.browser.production.min.js | 34 + ...ver-dom-webpack-client.edge.development.js | 1041 ++++++ ...-dom-webpack-client.edge.production.min.js | 28 + ...ver-dom-webpack-client.node.development.js | 1029 ++++++ ...-dom-webpack-client.node.production.min.js | 28 + ...bpack-client.node.unbundled.development.js | 978 ++++++ ...ck-client.node.unbundled.production.min.js | 26 + .../react-server-dom-webpack-node-register.js | 20 + .../cjs/react-server-dom-webpack-plugin.js | 21 + ...-dom-webpack-server.browser.development.js | 2908 +++++++++++++++ ...m-webpack-server.browser.production.min.js | 62 + ...ver-dom-webpack-server.edge.development.js | 2920 ++++++++++++++++ ...-dom-webpack-server.edge.production.min.js | 62 + ...ver-dom-webpack-server.node.development.js | 3109 +++++++++++++++++ ...-dom-webpack-server.node.production.min.js | 67 + ...bpack-server.node.unbundled.development.js | 3041 ++++++++++++++++ ...ck-server.node.unbundled.production.min.js | 65 + .../client.browser.js | 7 + .../client.edge.js | 7 + .../client.js | 3 + .../client.node.js | 7 + .../client.node.unbundled.js | 7 + .../index.js | 12 + .../node-register.js | 3 + .../package.json | 54 + .../plugin.js | 3 + .../server.browser.js | 7 + .../server.edge.js | 7 + .../server.js | 6 + .../server.node.js | 7 + .../server.node.unbundled.js | 7 + .../react-server-dom-webpack/package.json | 53 +- packages/next/src/lib/metadata/metadata.tsx | 5 +- .../src/server/app-render/action-handler.ts | 2 +- .../next/src/server/app-render/app-render.tsx | 61 +- ...te-flight-router-state-from-loader-tree.ts | 6 +- .../create-server-components-renderer.tsx | 7 +- .../server/app-render/render-to-string.tsx | 12 +- .../server/app-render/use-flight-response.tsx | 13 +- packages/next/src/server/config-schema.ts | 3 + packages/next/src/server/config-shared.ts | 5 + .../src/server/lib/incremental-cache/index.ts | 2 +- packages/next/src/server/lib/server-ipc.ts | 8 +- packages/next/src/server/next-server.ts | 3 +- packages/next/src/server/render.tsx | 4 +- packages/next/src/server/require-hook.ts | 154 +- .../src/server/stream-utils/encode-decode.ts | 10 + .../node-web-streams-helper.ts | 25 +- packages/next/taskfile.js | 10 +- packages/next/types/misc.d.ts | 1 + pnpm-lock.yaml | 18 + 64 files changed, 17659 insertions(+), 195 deletions(-) create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/LICENSE create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.edge.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.edge.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.unbundled.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-node-register.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-plugin.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.browser.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.browser.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.edge.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.edge.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.unbundled.development.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/client.browser.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/client.edge.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/client.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/client.node.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/client.node.unbundled.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/index.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/node-register.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/package.json create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/plugin.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/server.browser.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/server.edge.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/server.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/server.node.js create mode 100644 packages/next/src/compiled/react-server-dom-webpack-experimental/server.node.unbundled.js create mode 100644 packages/next/src/server/stream-utils/encode-decode.ts rename packages/next/src/server/{ => stream-utils}/node-web-streams-helper.ts (95%) diff --git a/package.json b/package.json index f5fc9776f01df..b8e618cf6b711 100644 --- a/package.json +++ b/package.json @@ -204,6 +204,7 @@ "react-dom-builtin": "npm:react-dom@18.3.0-next-6eadbe0c4-20230425", "react-dom-experimental-builtin": "npm:react-dom@0.0.0-experimental-6eadbe0c4-20230425", "react-server-dom-webpack": "18.3.0-next-6eadbe0c4-20230425", + "react-server-dom-webpack-experimental": "npm:react-server-dom-webpack@0.0.0-experimental-6eadbe0c4-20230425", "react-ssr-prepass": "1.0.8", "react-virtualized": "9.22.3", "relay-compiler": "13.0.2", diff --git a/packages/next-swc/crates/next-core/src/next_import_map.rs b/packages/next-swc/crates/next-core/src/next_import_map.rs index 116c65691817f..7c4e6c9bd7051 100644 --- a/packages/next-swc/crates/next-core/src/next_import_map.rs +++ b/packages/next-swc/crates/next-core/src/next_import_map.rs @@ -97,6 +97,10 @@ pub async fn get_next_client_import_map( "react-dom/", request_to_import_mapping(app_dir, "next/dist/compiled/react-dom/*"), ); + import_map.insert_wildcard_alias( + "react-server-dom-webpack/", + request_to_import_mapping(app_dir, "next/dist/compiled/react-server-dom-webpack/*"), + ); } ClientContextType::Fallback => {} ClientContextType::Other => {} @@ -210,6 +214,7 @@ pub async fn get_next_server_import_map( import_map.insert_wildcard_alias("react-dom/", external); import_map.insert_exact_alias("styled-jsx", external); import_map.insert_wildcard_alias("styled-jsx/", external); + import_map.insert_exact_alias("react-server-dom-webpack/", external); } ServerContextType::AppSSR { .. } | ServerContextType::AppRSC { .. } @@ -382,6 +387,10 @@ pub async fn insert_next_server_special_aliases( "react-dom/", request_to_import_mapping(app_dir, "next/dist/compiled/react-dom/*"), ); + import_map.insert_wildcard_alias( + "react-server-dom-webpack/", + request_to_import_mapping(app_dir, "next/dist/compiled/react-server-dom-webpack/*"), + ); } ServerContextType::Middleware => {} } diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index 0a7171604daf8..e40908651c7d9 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -1141,8 +1141,12 @@ export default async function build( forkOptions: { env: { ...process.env, - NEXT_PREBUNDLED_REACT_WORKER: type === 'app' ? '1' : '', - __NEXT_PRIVATE_PREBUNDLED_REACT: type === 'app' ? '1' : '', + __NEXT_PRIVATE_PREBUNDLED_REACT: + type === 'app' + ? config.experimental.experimentalReact + ? 'experimental' + : 'next' + : '', }, }, enableWorkerThreads: config.experimental.workerThreads, diff --git a/packages/next/src/build/utils.ts b/packages/next/src/build/utils.ts index c04e839414797..c6207c2d4a548 100644 --- a/packages/next/src/build/utils.ts +++ b/packages/next/src/build/utils.ts @@ -1955,7 +1955,7 @@ ${ // to ensure the correctness of the version for app. `\ if (nextConfig && nextConfig.experimental && nextConfig.experimental.appDir) { - process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = '1' + process.env.__NEXT_PRIVATE_PREBUNDLED_REACT = nextConfig.experimental.experimentalReact ? 'experimental' : 'next' } ` } diff --git a/packages/next/src/build/webpack-config.ts b/packages/next/src/build/webpack-config.ts index 3b1c1bf306738..e06feea116be2 100644 --- a/packages/next/src/build/webpack-config.ts +++ b/packages/next/src/build/webpack-config.ts @@ -86,7 +86,7 @@ const babelIncludeRegexes: RegExp[] = [ /[\\/](strip-ansi|ansi-regex|styled-jsx)[\\/]/, ] -const reactPackagesRegex = /^(react(?:$|\/)|react-dom(?:$|\/))/ +const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/ const staticGenerationAsyncStorageRegex = /next[\\/]dist[\\/]client[\\/]components[\\/]static-generation-async-storage/ @@ -704,6 +704,8 @@ export default async function getBaseWebpackConfig( const hasServerComponents = hasAppDir const disableOptimizedLoading = true const enableTypedRoutes = !!config.experimental.typedRoutes && hasAppDir + const experimentalReact = !!config.experimental.experimentalReact && hasAppDir + const bundledReactChannel = experimentalReact ? '-experimental' : '' if (isClient) { if ( @@ -1228,7 +1230,10 @@ export default async function getBaseWebpackConfig( request === 'react/jsx-runtime' ) { if (isAppLayer) { - return `commonjs next/dist/compiled/${request}` + return `commonjs next/dist/compiled/${request.replace( + 'react', + 'react' + bundledReactChannel + )}` } return } @@ -1237,10 +1242,7 @@ export default async function getBaseWebpackConfig( if (layer === WEBPACK_LAYERS.server) { // React needs to be bundled for Server Components so the special // `react-server` export condition can be used. - if ( - reactPackagesRegex.test(request) || - request === 'next/dist/compiled/react-server-dom-webpack/server.edge' - ) { + if (reactPackagesRegex.test(request)) { return } } @@ -1254,7 +1256,7 @@ export default async function getBaseWebpackConfig( return `commonjs ${request}` } - if (/^(react(?:$|\/)|react-dom(?:$|\/))/.test(request)) { + if (reactPackagesRegex.test(request)) { // override react-dom to server-rendering-stub for server if ( request === 'react-dom' && @@ -1262,9 +1264,18 @@ export default async function getBaseWebpackConfig( layer === WEBPACK_LAYERS.server || layer === WEBPACK_LAYERS.action) ) { - request = 'react-dom/server-rendering-stub' + request = `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub` + } else if (isAppLayer) { + request = + 'next/dist/compiled/' + + request.replace( + /^(react-server-dom-webpack|react-dom|react)/, + (name) => { + return name + bundledReactChannel + } + ) } - return `commonjs ${isAppLayer ? 'next/dist/compiled/' : ''}${request}` + return `commonjs ${request}` } const notExternalModules = @@ -1441,7 +1452,12 @@ export default async function getBaseWebpackConfig( // also map react to builtin ones with require-hook. if (layer === WEBPACK_LAYERS.client) { if (reactPackagesRegex.test(request)) { - return `commonjs next/dist/compiled/${request}` + return `commonjs next/dist/compiled/${request.replace( + /^(react-server-dom-webpack|react-dom|react)/, + (name) => { + return name + bundledReactChannel + } + )}` } return } @@ -1781,7 +1797,7 @@ export default async function getBaseWebpackConfig( ...(hasAppDir ? [ { - test: codeCondition.test, + // All app dir layers need to use this configured resolution logic issuerLayer: { or: [ WEBPACK_LAYERS.server, @@ -1801,10 +1817,13 @@ export default async function getBaseWebpackConfig( [require.resolve('next/dynamic')]: require.resolve( 'next/dist/shared/lib/app-dynamic' ), - 'react/jsx-runtime$': - 'next/dist/compiled/react/jsx-runtime', - 'react/jsx-dev-runtime$': - 'next/dist/compiled/react/jsx-dev-runtime', + 'react/jsx-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-runtime`, + 'react/jsx-dev-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`, + 'react-dom/server.edge$': `next/dist/compiled/react-dom${bundledReactChannel}/server.edge`, + 'react-server-dom-webpack/client$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`, + 'react-server-dom-webpack/client.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client.edge`, + 'react-server-dom-webpack/server.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.edge`, + 'react-server-dom-webpack/server.node$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.node`, }, }, }, @@ -1835,9 +1854,8 @@ export default async function getBaseWebpackConfig( // If missing the alias override here, the default alias will be used which aliases // react to the direct file path, not the package name. In that case the condition // will be ignored completely. - react: 'next/dist/compiled/react/react.shared-subset', - 'react-dom$': - 'next/dist/compiled/react-dom/server-rendering-stub', + react: `next/dist/compiled/react${bundledReactChannel}/react.shared-subset`, + 'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`, }, }, use: { @@ -1900,11 +1918,10 @@ export default async function getBaseWebpackConfig( // It needs `conditionNames` here to require the proper asset, // when react is acting as dependency of compiled/react-dom. alias: { - react: 'next/dist/compiled/react/react.shared-subset', + react: `next/dist/compiled/react${bundledReactChannel}/react.shared-subset`, // Use server rendering stub for RSC // x-ref: https://github.com/facebook/react/pull/25436 - 'react-dom$': - 'next/dist/compiled/react-dom/server-rendering-stub', + 'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`, }, }, }, @@ -1913,9 +1930,8 @@ export default async function getBaseWebpackConfig( test: codeCondition.test, resolve: { alias: { - react: 'next/dist/compiled/react', - 'react-dom$': - 'next/dist/compiled/react-dom/server-rendering-stub', + react: `next/dist/compiled/react${bundledReactChannel}`, + 'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`, }, }, }, @@ -1923,12 +1939,11 @@ export default async function getBaseWebpackConfig( test: codeCondition.test, resolve: { alias: { - react: 'next/dist/compiled/react', + react: `next/dist/compiled/react${bundledReactChannel}`, 'react-dom$': reactProductionProfiling - ? 'next/dist/compiled/react-dom/cjs/react-dom.profiling.min' - : 'next/dist/compiled/react-dom', - 'react-dom/client$': - 'next/dist/compiled/react-dom/client', + ? `next/dist/compiled/react-dom${bundledReactChannel}/cjs/react-dom.profiling.min` + : `next/dist/compiled/react-dom${bundledReactChannel}`, + 'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`, }, }, }, @@ -2292,7 +2307,7 @@ export default async function getBaseWebpackConfig( appDir, dev, isEdgeServer, - useExperimentalReact: false, + useExperimentalReact: experimentalReact, })), hasAppDir && !isClient && diff --git a/packages/next/src/build/webpack/loaders/next-app-loader.ts b/packages/next/src/build/webpack/loaders/next-app-loader.ts index a86c6a8cbf2ad..9074a12a7892d 100644 --- a/packages/next/src/build/webpack/loaders/next-app-loader.ts +++ b/packages/next/src/build/webpack/loaders/next-app-loader.ts @@ -592,7 +592,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { export * as serverHooks from 'next/dist/client/components/hooks-server-context' - export { renderToReadableStream, decodeReply } from 'next/dist/compiled/react-server-dom-webpack/server.edge' + export { renderToReadableStream, decodeReply } from 'react-server-dom-webpack/server.edge' export const __next_app_webpack_require__ = __webpack_require__ export { preloadStyle, preloadFont, preconnect } from 'next/dist/server/app-render/rsc/preloads' ` diff --git a/packages/next/src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts b/packages/next/src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts index 4c7ffc1457bc1..8d490e11c26ee 100644 --- a/packages/next/src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts +++ b/packages/next/src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts @@ -1,6 +1,8 @@ -// This file must be bundled in the app's client layer. +// This file must be bundled in the app's client layer, it shouldn't be directly +// imported by the server. -import { createServerReference } from 'next/dist/compiled/react-server-dom-webpack/client' +// eslint-disable-next-line import/no-extraneous-dependencies +import { createServerReference } from 'react-server-dom-webpack/client' import { callServer } from 'next/dist/client/app-call-server' // A noop wrapper to let the Flight client create the server reference. diff --git a/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts b/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts index 771e7ff856c54..af4726b6a0db9 100644 --- a/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts +++ b/packages/next/src/build/webpack/plugins/nextjs-require-cache-hot-reloader.ts @@ -12,6 +12,9 @@ const originModules = [ require.resolve('../../../server/load-components'), require.resolve('../../../server/next-server'), require.resolve('../../../compiled/react-server-dom-webpack/client.edge'), + require.resolve( + '../../../compiled/react-server-dom-webpack-experimental/client.edge' + ), ] const RUNTIME_NAMES = ['webpack-runtime', 'webpack-api-runtime'] @@ -23,7 +26,7 @@ export function deleteAppClientCache() { // ensure we reset the cache for sc_server components // loaded via react-server-dom-webpack const reactServerDomModId = require.resolve( - 'next/dist/compiled/react-server-dom-webpack/client.edge' + 'react-server-dom-webpack/client.edge' ) const reactServerDomMod = require.cache[reactServerDomModId] diff --git a/packages/next/src/client/app-call-server.ts b/packages/next/src/client/app-call-server.ts index 167759b0d9831..73a409f28820c 100644 --- a/packages/next/src/client/app-call-server.ts +++ b/packages/next/src/client/app-call-server.ts @@ -1,4 +1,6 @@ -import { encodeReply } from 'next/dist/compiled/react-server-dom-webpack/client' +// @ts-ignore +// eslint-disable-next-line import/no-extraneous-dependencies +import { encodeReply } from 'react-server-dom-webpack/client' export async function callServer(id: string, args: any[]) { const actionId = id diff --git a/packages/next/src/client/app-index.tsx b/packages/next/src/client/app-index.tsx index 77a2d17f0c520..856f21b0d844c 100644 --- a/packages/next/src/client/app-index.tsx +++ b/packages/next/src/client/app-index.tsx @@ -3,7 +3,9 @@ import '../build/polyfills/polyfill-module' // @ts-ignore react-dom/client exists when using React 18 import ReactDOMClient from 'react-dom/client' import React, { use } from 'react' -import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack/client' +// @ts-ignore +// eslint-disable-next-line import/no-extraneous-dependencies +import { createFromReadableStream } from 'react-server-dom-webpack/client' import { HeadManagerContext } from '../shared/lib/head-manager-context' import { GlobalLayoutRouterContext } from '../shared/lib/app-router-context' diff --git a/packages/next/src/client/components/router-reducer/fetch-server-response.ts b/packages/next/src/client/components/router-reducer/fetch-server-response.ts index b4cec07e24bfb..dca949d4e4a2b 100644 --- a/packages/next/src/client/components/router-reducer/fetch-server-response.ts +++ b/packages/next/src/client/components/router-reducer/fetch-server-response.ts @@ -1,6 +1,8 @@ 'use client' -import { createFromFetch } from 'next/dist/compiled/react-server-dom-webpack/client' +// @ts-ignore +// eslint-disable-next-line import/no-extraneous-dependencies +import { createFromFetch } from 'react-server-dom-webpack/client' import type { FlightRouterState, FlightData, diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/LICENSE b/packages/next/src/compiled/react-server-dom-webpack-experimental/LICENSE new file mode 100644 index 0000000000000..b93be90515ccd --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.development.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.development.js new file mode 100644 index 0000000000000..b7e9b84395a84 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.development.js @@ -0,0 +1,1735 @@ +/** + * @license React + * react-server-dom-webpack-client.browser.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var ReactDOM = require('react-dom'); +var React = require('react'); + +function createStringDecoder() { + return new TextDecoder(); +} +var decoderOptions = { + stream: true +}; +function readPartialStringChunk(decoder, buffer) { + return decoder.decode(buffer, decoderOptions); +} +function readFinalStringChunk(decoder, buffer) { + return decoder.decode(buffer); +} + +function parseModel(response, json) { + return JSON.parse(json, response._fromJSON); +} + +// eslint-disable-next-line no-unused-vars +function resolveClientReference(bundlerConfig, metadata) { + if (bundlerConfig) { + var moduleExports = bundlerConfig[metadata.id]; + var resolvedModuleData = moduleExports[metadata.name]; + var name; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // If we don't have this specific name, we might have the full module. + resolvedModuleData = moduleExports['*']; + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + metadata.id + '" in the React SSR Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + + name = metadata.name; + } + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: !!metadata.async + }; + } + + return metadata; +} +// If they're still pending they're a thenable. This map also exists +// in Webpack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); +var asyncModuleCache = new Map(); + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata.chunks; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkId = chunks[i]; + var entry = chunkCache.get(chunkId); + + if (entry === undefined) { + var thenable = globalThis.__next_chunk_load__(chunkId); + + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkId, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (metadata.async) { + var existingPromise = asyncModuleCache.get(metadata.id); + + if (existingPromise) { + if (existingPromise.status === 'fulfilled') { + return null; + } + + return existingPromise; + } else { + var modulePromise = Promise.all(promises).then(function () { + return globalThis.__next_require__(metadata.id); + }); + modulePromise.then(function (value) { + var fulfilledThenable = modulePromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = modulePromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + asyncModuleCache.set(metadata.id, modulePromise); + return modulePromise; + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports; + + if (metadata.async) { + // We assume that preloadModule has been called before, which + // should have added something to the module cache. + var promise = asyncModuleCache.get(metadata.id); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + } else { + moduleExports = globalThis.__next_require__(metadata.id); + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata.name]; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// This client file is in the shared folder because it applies to both SSR and browser contexts. +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function dispatchHint(code, model) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + var href, options; + + if (typeof model === 'string') { + href = model; + } else { + href = model[0]; + options = model[1]; + } + + switch (code) { + case 'D': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + dispatcher.prefetchDNS(href, options); + return; + } + + case 'C': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + dispatcher.preconnect(href, options); + return; + } + + case 'L': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + // $FlowFixMe[incompatible-call] options are not refined to their types by code + dispatcher.preload(href, options); + return; + } + + case 'I': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + // $FlowFixMe[incompatible-call] options are not refined to their types by code + dispatcher.preinit(href, options); + return; + } + } + } +} + +var knownServerReferences = new WeakMap(); +function createServerReference(id, callServer) { + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + return callServer(id, args); + }; + + knownServerReferences.set(proxy, { + id: id, + bound: null + }); + return proxy; +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value + REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); + } + + return ContextRegistry[globalName]; +} + +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var RESOLVED_MODULE = 'resolved_module'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function readChunk(chunk) { + // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + return chunk.value; + + case PENDING: + case BLOCKED: + // eslint-disable-next-line no-throw-literal + throw chunk; + + default: + throw chunk.reason; + } +} + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function createBlockedChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(BLOCKED, null, null, response); +} + +function createErrorChunk(response, error) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(ERRORED, null, error, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function createResolvedModuleChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODULE, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function resolveModuleChunk(chunk, value) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODULE; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + initializeModuleChunk(resolvedChunk); + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = parseModel(chunk._response, chunk.value); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + knownServerReferences.set(proxy, metaData); + return proxy; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + { + var metadata = _chunk2.value; + return createServerReferenceProxy(response, metadata); + } + // We always encode it first in the stream so it won't be pending. + + default: + throw _chunk2.reason; + } + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id3 = parseInt(value.slice(1), 16); + + var _chunk3 = getChunk(response, _id3); + + switch (_chunk3.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk3); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk3); + break; + } // The status might have changed after initialization. + + + switch (_chunk3.status) { + case INITIALIZED: + return _chunk3.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk3.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk3.reason; + } + } + } + } + + return value; +} +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + 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 createResponse$1(bundlerConfig, callServer) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _callServer: callServer !== undefined ? callServer : missingCall, + _chunks: chunks + }; + return response; +} +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); // TODO: Add an option to encode modules that are lazy loaded. + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function processFullRow(response, row) { + if (row === '') { + return; + } + + var colon = row.indexOf(':', 0); + var id = parseInt(row.slice(0, colon), 16); + var tag = row[colon + 1]; // When tags that are not text are added, check them here before + // parsing the row as text. + // switch (tag) { + // } + + switch (tag) { + case 'I': + { + resolveModule(response, id, row.slice(colon + 2)); + return; + } + + case 'H': + { + var code = row[colon + 2]; + resolveHint(response, code, row.slice(colon + 3)); + return; + } + + case 'E': + { + var errorInfo = JSON.parse(row.slice(colon + 2)); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + default: + { + // We assume anything else is JSON. + resolveModel(response, id, row.slice(colon + 1)); + return; + } + } +} + +function processStringChunk(response, chunk, offset) { + var linebreak = chunk.indexOf('\n', offset); + + while (linebreak > -1) { + var fullrow = response._partialRow + chunk.slice(offset, linebreak); + processFullRow(response, fullrow); + response._partialRow = ''; + offset = linebreak + 1; + linebreak = chunk.indexOf('\n', offset); + } + + response._partialRow += chunk.slice(offset); +} +function processBinaryChunk(response, chunk) { + + var stringDecoder = response._stringDecoder; + var linebreak = chunk.indexOf(10); // newline + + while (linebreak > -1) { + var fullrow = response._partialRow + readFinalStringChunk(stringDecoder, chunk.subarray(0, linebreak)); + processFullRow(response, fullrow); + response._partialRow = ''; + chunk = chunk.subarray(linebreak + 1); + linebreak = chunk.indexOf(10); // newline + } + + response._partialRow += readPartialStringChunk(stringDecoder, chunk); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function createResponse(bundlerConfig, callServer) { + // NOTE: CHECK THE COMPILER OUTPUT EACH TIME YOU CHANGE THIS. + // It should be inlined to one object literal but minor changes can break it. + var stringDecoder = createStringDecoder() ; + var response = createResponse$1(bundlerConfig, callServer); + response._partialRow = ''; + + { + response._stringDecoder = stringDecoder; + } // Don't inline this call because it causes closure to outline the call above. + + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +// Thenable +// function serializeByValueID(id: number): string { +// return '$' + id.toString(16); +// } + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeFormDataReference(id) { + // Why K? F is "Function". D is "Date". What else? + return '$K' + id.toString(16); +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +function processReply(root, formFieldPrefix, resolve, reject) { + var nextPartId = 1; + var pendingParts = 0; + var formData = null; + + function resolveToJSON(key, value) { + var parent = this; // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + error('Only plain objects can be passed to Server Functions from the Client. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Server Functions from the Client. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + // $FlowFixMe[method-unbinding] + if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } + + pendingParts++; + var promiseId = nextPartId++; + var thenable = value; + thenable.then(function (partValue) { + var partJSON = JSON.stringify(partValue, resolveToJSON); // $FlowFixMe[incompatible-type] We know it's not null because we assigned it above. + + var data = formData; // eslint-disable-next-line react-internal/safe-string-coercion + + data.append(formFieldPrefix + promiseId, partJSON); + pendingParts--; + + if (pendingParts === 0) { + resolve(data); + } + }, function (reason) { + // In the future we could consider serializing this as an error + // that throws on the server instead. + reject(reason); + }); + return serializePromiseID(promiseId); + } // TODO: Should we the Object.prototype.toString.call() to test for cross-realm objects? + + + if (value instanceof FormData) { + if (formData === null) { + // Upgrade to use FormData to allow us to use rich objects as its values. + formData = new FormData(); + } + + var data = formData; + var refId = nextPartId++; // Copy all the form fields with a prefix for this reference. + // These must come first in the form order because we assume that all the + // fields are available before this is referenced. + + var prefix = formFieldPrefix + refId + '_'; // $FlowFixMe[prop-missing]: FormData has forEach. + + value.forEach(function (originalValue, originalKey) { + data.append(prefix + originalKey, originalValue); + }); + return serializeFormDataReference(refId); + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (value.$$typeof === REACT_ELEMENT_TYPE) { + error('React Element cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_LAZY_TYPE) { + error('React Lazy cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + error('React Context Providers cannot be passed to Server Functions from the Client.%s', describeObjectForErrorMessage(parent, key)); + } else if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; // $FlowFixMe[method-unbinding] + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + var metaData = knownServerReferences.get(value); + + if (metaData !== undefined) { + var metaDataJSON = JSON.stringify(metaData, resolveToJSON); + + if (formData === null) { + // Upgrade to use FormData to allow us to stream this value. + formData = new FormData(); + } // The reference to this function came from the same client so we can pass it back. + + + var _refId = nextPartId++; // eslint-disable-next-line react-internal/safe-string-coercion + + + formData.set(formFieldPrefix + _refId, metaDataJSON); + return serializeServerReferenceID(_refId); + } + + throw new Error('Client Functions cannot be passed directly to Server Functions. ' + 'Only Functions passed from the Server can be passed back again.'); + } + + if (typeof value === 'symbol') { + // $FlowFixMe[incompatible-type] `description` might be undefined + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Server Functions. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.")); + } + + return serializeSymbolReference(name); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported as an argument to a Server Function."); + } // $FlowFixMe[incompatible-type] it's not going to be undefined because we'll encode it. + + + var json = JSON.stringify(root, resolveToJSON); + + if (formData === null) { + // If it's a simple data structure, we just use plain JSON. + resolve(json); + } else { + // Otherwise, we use FormData to let us stream in the result. + formData.set(formFieldPrefix + '0', json); + + if (pendingParts === 0) { + // $FlowFixMe[incompatible-call] this has already been refined. + resolve(formData); + } + } +} + +function createResponseFromOptions(options) { + return createResponse(null, options && options.callServer ? options.callServer : undefined); +} + +function startReadingFromStream(response, stream) { + var reader = stream.getReader(); + + function progress(_ref) { + var done = _ref.done, + value = _ref.value; + + if (done) { + close(response); + return; + } + + var buffer = value; + processBinaryChunk(response, buffer); + return reader.read().then(progress).catch(error); + } + + function error(e) { + reportGlobalError(response, e); + } + + reader.read().then(progress).catch(error); +} + +function createFromReadableStream(stream, options) { + var response = createResponseFromOptions(options); + startReadingFromStream(response, stream); + return getRoot(response); +} + +function createFromFetch(promiseForResponse, options) { + var response = createResponseFromOptions(options); + promiseForResponse.then(function (r) { + startReadingFromStream(response, r.body); + }, function (e) { + reportGlobalError(response, e); + }); + return getRoot(response); +} + +function createFromXHR(request, options) { + var response = createResponseFromOptions(options); + var processedLength = 0; + + function progress(e) { + var chunk = request.responseText; + processStringChunk(response, chunk, processedLength); + processedLength = chunk.length; + } + + function load(e) { + progress(); + close(response); + } + + function error(e) { + reportGlobalError(response, new TypeError('Network error')); + } + + request.addEventListener('progress', progress); + request.addEventListener('load', load); + request.addEventListener('error', error); + request.addEventListener('abort', error); + request.addEventListener('timeout', error); + return getRoot(response); +} + +function encodeReply(value) +/* We don't use URLSearchParams yet but maybe */ +{ + return new Promise(function (resolve, reject) { + processReply(value, '', resolve, reject); + }); +} + +exports.createFromFetch = createFromFetch; +exports.createFromReadableStream = createFromReadableStream; +exports.createFromXHR = createFromXHR; +exports.createServerReference = createServerReference; +exports.encodeReply = encodeReply; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.production.min.js new file mode 100644 index 0000000000000..8674f7157217f --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.production.min.js @@ -0,0 +1,34 @@ +/** + * @license React + * react-server-dom-webpack-client.browser.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var m=require("react-dom"),n=require("react"),p={stream:!0};function r(a,b){if(a){var c=a[b.id];if(a=c[b.name])c=a.name;else{a=c["*"];if(!a)throw Error('Could not find the module "'+b.id+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');c=b.name}return{id:a.id,chunks:a.chunks,name:c,async:!!b.async}}return b}var t=new Map,u=new Map;function v(){} +function w(a){for(var b=a.chunks,c=[],d=0;d 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports; + + if (metadata.async) { + // We assume that preloadModule has been called before, which + // should have added something to the module cache. + var promise = asyncModuleCache.get(metadata.id); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + } else { + moduleExports = globalThis.__next_require__(metadata.id); + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata.name]; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// This client file is in the shared folder because it applies to both SSR and browser contexts. +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function dispatchHint(code, model) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + var href, options; + + if (typeof model === 'string') { + href = model; + } else { + href = model[0]; + options = model[1]; + } + + switch (code) { + case 'D': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + dispatcher.prefetchDNS(href, options); + return; + } + + case 'C': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + dispatcher.preconnect(href, options); + return; + } + + case 'L': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + // $FlowFixMe[incompatible-call] options are not refined to their types by code + dispatcher.preload(href, options); + return; + } + + case 'I': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + // $FlowFixMe[incompatible-call] options are not refined to their types by code + dispatcher.preinit(href, options); + return; + } + } + } +} + +var knownServerReferences = new WeakMap(); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value + REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); + } + + return ContextRegistry[globalName]; +} + +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var RESOLVED_MODULE = 'resolved_module'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function readChunk(chunk) { + // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + return chunk.value; + + case PENDING: + case BLOCKED: + // eslint-disable-next-line no-throw-literal + throw chunk; + + default: + throw chunk.reason; + } +} + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function createBlockedChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(BLOCKED, null, null, response); +} + +function createErrorChunk(response, error) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(ERRORED, null, error, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function createResolvedModuleChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODULE, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function resolveModuleChunk(chunk, value) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODULE; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + initializeModuleChunk(resolvedChunk); + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = parseModel(chunk._response, chunk.value); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + knownServerReferences.set(proxy, metaData); + return proxy; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + { + var metadata = _chunk2.value; + return createServerReferenceProxy(response, metadata); + } + // We always encode it first in the stream so it won't be pending. + + default: + throw _chunk2.reason; + } + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id3 = parseInt(value.slice(1), 16); + + var _chunk3 = getChunk(response, _id3); + + switch (_chunk3.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk3); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk3); + break; + } // The status might have changed after initialization. + + + switch (_chunk3.status) { + case INITIALIZED: + return _chunk3.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk3.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk3.reason; + } + } + } + } + + return value; +} +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + 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 createResponse$1(bundlerConfig, callServer) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _callServer: callServer !== undefined ? callServer : missingCall, + _chunks: chunks + }; + return response; +} +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); // TODO: Add an option to encode modules that are lazy loaded. + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function processFullRow(response, row) { + if (row === '') { + return; + } + + var colon = row.indexOf(':', 0); + var id = parseInt(row.slice(0, colon), 16); + var tag = row[colon + 1]; // When tags that are not text are added, check them here before + // parsing the row as text. + // switch (tag) { + // } + + switch (tag) { + case 'I': + { + resolveModule(response, id, row.slice(colon + 2)); + return; + } + + case 'H': + { + var code = row[colon + 2]; + resolveHint(response, code, row.slice(colon + 3)); + return; + } + + case 'E': + { + var errorInfo = JSON.parse(row.slice(colon + 2)); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + default: + { + // We assume anything else is JSON. + resolveModel(response, id, row.slice(colon + 1)); + return; + } + } +} +function processBinaryChunk(response, chunk) { + + var stringDecoder = response._stringDecoder; + var linebreak = chunk.indexOf(10); // newline + + while (linebreak > -1) { + var fullrow = response._partialRow + readFinalStringChunk(stringDecoder, chunk.subarray(0, linebreak)); + processFullRow(response, fullrow); + response._partialRow = ''; + chunk = chunk.subarray(linebreak + 1); + linebreak = chunk.indexOf(10); // newline + } + + response._partialRow += readPartialStringChunk(stringDecoder, chunk); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function createResponse(bundlerConfig, callServer) { + // NOTE: CHECK THE COMPILER OUTPUT EACH TIME YOU CHANGE THIS. + // It should be inlined to one object literal but minor changes can break it. + var stringDecoder = createStringDecoder() ; + var response = createResponse$1(bundlerConfig, callServer); + response._partialRow = ''; + + { + response._stringDecoder = stringDecoder; + } // Don't inline this call because it causes closure to outline the call above. + + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function noServerCall() { + throw new Error('Server Functions cannot be called during initial render. ' + 'This would create a fetch waterfall. Try to use a Server Component ' + 'to pass data to Client Components instead.'); +} + +function createServerReference(id, callServer) { + return noServerCall; +} + +function createResponseFromOptions(options) { + return createResponse(options && options.moduleMap ? options.moduleMap : null, noServerCall); +} + +function startReadingFromStream(response, stream) { + var reader = stream.getReader(); + + function progress(_ref) { + var done = _ref.done, + value = _ref.value; + + if (done) { + close(response); + return; + } + + var buffer = value; + processBinaryChunk(response, buffer); + return reader.read().then(progress).catch(error); + } + + function error(e) { + reportGlobalError(response, e); + } + + reader.read().then(progress).catch(error); +} + +function createFromReadableStream(stream, options) { + var response = createResponseFromOptions(options); + startReadingFromStream(response, stream); + return getRoot(response); +} + +function createFromFetch(promiseForResponse, options) { + var response = createResponseFromOptions(options); + promiseForResponse.then(function (r) { + startReadingFromStream(response, r.body); + }, function (e) { + reportGlobalError(response, e); + }); + return getRoot(response); +} + +exports.createFromFetch = createFromFetch; +exports.createFromReadableStream = createFromReadableStream; +exports.createServerReference = createServerReference; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.edge.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.edge.production.min.js new file mode 100644 index 0000000000000..9dcbc40e69c82 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.edge.production.min.js @@ -0,0 +1,28 @@ +/** + * @license React + * react-server-dom-webpack-client.edge.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var p=require("react-dom"),r=require("react"),t={stream:!0};function u(a,b){if(a){var c=a[b.id];if(a=c[b.name])c=a.name;else{a=c["*"];if(!a)throw Error('Could not find the module "'+b.id+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');c=b.name}return{id:a.id,chunks:a.chunks,name:c,async:!!b.async}}return b}var v=new Map,w=new Map;function x(){} +function y(a){for(var b=a.chunks,c=[],d=0;d 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports; + + if (metadata.async) { + // We assume that preloadModule has been called before, which + // should have added something to the module cache. + var promise = asyncModuleCache.get(metadata.id); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + } else { + moduleExports = globalThis.__next_require__(metadata.id); + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata.name]; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// This client file is in the shared folder because it applies to both SSR and browser contexts. +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function dispatchHint(code, model) { + var dispatcher = ReactDOMCurrentDispatcher.current; + + if (dispatcher) { + var href, options; + + if (typeof model === 'string') { + href = model; + } else { + href = model[0]; + options = model[1]; + } + + switch (code) { + case 'D': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + dispatcher.prefetchDNS(href, options); + return; + } + + case 'C': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + dispatcher.preconnect(href, options); + return; + } + + case 'L': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + // $FlowFixMe[incompatible-call] options are not refined to their types by code + dispatcher.preload(href, options); + return; + } + + case 'I': + { + // $FlowFixMe[prop-missing] options are not refined to their types by code + // $FlowFixMe[incompatible-call] options are not refined to their types by code + dispatcher.preinit(href, options); + return; + } + } + } +} + +var knownServerReferences = new WeakMap(); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value + REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); + } + + return ContextRegistry[globalName]; +} + +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var RESOLVED_MODULE = 'resolved_module'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function readChunk(chunk) { + // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + return chunk.value; + + case PENDING: + case BLOCKED: + // eslint-disable-next-line no-throw-literal + throw chunk; + + default: + throw chunk.reason; + } +} + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function createBlockedChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(BLOCKED, null, null, response); +} + +function createErrorChunk(response, error) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(ERRORED, null, error, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function createResolvedModuleChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODULE, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function resolveModuleChunk(chunk, value) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODULE; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + initializeModuleChunk(resolvedChunk); + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = parseModel(chunk._response, chunk.value); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + knownServerReferences.set(proxy, metaData); + return proxy; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + { + var metadata = _chunk2.value; + return createServerReferenceProxy(response, metadata); + } + // We always encode it first in the stream so it won't be pending. + + default: + throw _chunk2.reason; + } + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id3 = parseInt(value.slice(1), 16); + + var _chunk3 = getChunk(response, _id3); + + switch (_chunk3.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk3); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk3); + break; + } // The status might have changed after initialization. + + + switch (_chunk3.status) { + case INITIALIZED: + return _chunk3.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk3.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk3.reason; + } + } + } + } + + return value; +} +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + 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 createResponse$1(bundlerConfig, callServer) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _callServer: callServer !== undefined ? callServer : missingCall, + _chunks: chunks + }; + return response; +} +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); // TODO: Add an option to encode modules that are lazy loaded. + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function processFullRow(response, row) { + if (row === '') { + return; + } + + var colon = row.indexOf(':', 0); + var id = parseInt(row.slice(0, colon), 16); + var tag = row[colon + 1]; // When tags that are not text are added, check them here before + // parsing the row as text. + // switch (tag) { + // } + + switch (tag) { + case 'I': + { + resolveModule(response, id, row.slice(colon + 2)); + return; + } + + case 'H': + { + var code = row[colon + 2]; + resolveHint(response, code, row.slice(colon + 3)); + return; + } + + case 'E': + { + var errorInfo = JSON.parse(row.slice(colon + 2)); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + default: + { + // We assume anything else is JSON. + resolveModel(response, id, row.slice(colon + 1)); + return; + } + } +} + +function processStringChunk(response, chunk, offset) { + var linebreak = chunk.indexOf('\n', offset); + + while (linebreak > -1) { + var fullrow = response._partialRow + chunk.slice(offset, linebreak); + processFullRow(response, fullrow); + response._partialRow = ''; + offset = linebreak + 1; + linebreak = chunk.indexOf('\n', offset); + } + + response._partialRow += chunk.slice(offset); +} +function processBinaryChunk(response, chunk) { + + var stringDecoder = response._stringDecoder; + var linebreak = chunk.indexOf(10); // newline + + while (linebreak > -1) { + var fullrow = response._partialRow + readFinalStringChunk(stringDecoder, chunk.subarray(0, linebreak)); + processFullRow(response, fullrow); + response._partialRow = ''; + chunk = chunk.subarray(linebreak + 1); + linebreak = chunk.indexOf(10); // newline + } + + response._partialRow += readPartialStringChunk(stringDecoder, chunk); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function createResponse(bundlerConfig, callServer) { + // NOTE: CHECK THE COMPILER OUTPUT EACH TIME YOU CHANGE THIS. + // It should be inlined to one object literal but minor changes can break it. + var stringDecoder = createStringDecoder() ; + var response = createResponse$1(bundlerConfig, callServer); + response._partialRow = ''; + + { + response._stringDecoder = stringDecoder; + } // Don't inline this call because it causes closure to outline the call above. + + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function noServerCall() { + throw new Error('Server Functions cannot be called during initial render. ' + 'This would create a fetch waterfall. Try to use a Server Component ' + 'to pass data to Client Components instead.'); +} + +function createServerReference(id, callServer) { + return noServerCall; +} + +function createFromNodeStream(stream, moduleMap) { + var response = createResponse(moduleMap, noServerCall); + stream.on('data', function (chunk) { + if (typeof chunk === 'string') { + processStringChunk(response, chunk, 0); + } else { + processBinaryChunk(response, chunk); + } + }); + stream.on('error', function (error) { + reportGlobalError(response, error); + }); + stream.on('end', function () { + return close(response); + }); + return getRoot(response); +} + +exports.createFromNodeStream = createFromNodeStream; +exports.createServerReference = createServerReference; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.production.min.js new file mode 100644 index 0000000000000..248e41c22e420 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.production.min.js @@ -0,0 +1,28 @@ +/** + * @license React + * react-server-dom-webpack-client.node.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var k=require("util"),l=require("react-dom"),m=require("react"),n={stream:!0};function p(a,b){if(a){var c=a[b.id];if(a=c[b.name])c=a.name;else{a=c["*"];if(!a)throw Error('Could not find the module "'+b.id+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');c=b.name}return{id:a.id,chunks:a.chunks,name:c,async:!!b.async}}return b}var q=new Map,r=new Map;function t(){} +function u(a){for(var b=a.chunks,c=[],d=0;d 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} + +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function createElement(type, key, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type: type, + key: key, + ref: null, + props: props, + // Record the component responsible for creating this element. + _owner: null + }; + + { + // We don't really need to add any of these but keeping them for good measure. + // Unfortunately, _store is enumerable in jest matchers so for equality to + // work, I need to keep it or make _store non-enumerable in the other file. + element._store = {}; + Object.defineProperty(element._store, 'validated', { + configurable: false, + enumerable: false, + writable: true, + value: true // This element has already been validated on the server. + + }); + Object.defineProperty(element, '_self', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + Object.defineProperty(element, '_source', { + configurable: false, + enumerable: false, + writable: false, + value: null + }); + } + + return element; +} + +function createLazyChunkWrapper(chunk) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + return lazyType; +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunk = createPendingChunk(response); + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function createServerReferenceProxy(response, metaData) { + var callServer = response._callServer; + + var proxy = function () { + // $FlowFixMe[method-unbinding] + var args = Array.prototype.slice.call(arguments); + var p = metaData.bound; + + if (!p) { + return callServer(metaData.id, args); + } + + if (p.status === INITIALIZED) { + var bound = p.value; + return callServer(metaData.id, bound.concat(args)); + } // Since this is a fake Promise whose .then doesn't chain, we have to wrap it. + // TODO: Remove the wrapper once that's fixed. + + + return Promise.resolve(p).then(function (bound) { + return callServer(metaData.id, bound.concat(args)); + }); + }; + + knownServerReferences.set(proxy, metaData); + return proxy; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + if (value === '$') { + // A very common symbol. + return REACT_ELEMENT_TYPE; + } + + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case 'L': + { + // Lazy node + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); // We create a React.lazy wrapper around any lazy values. + // When passed into React, we'll know how to suspend on this. + + return createLazyChunkWrapper(chunk); + } + + case '@': + { + // Promise + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + return _chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'P': + { + // Server Context Provider + return getOrCreateServerContext(value.slice(2)).Provider; + } + + case 'F': + { + // Server Reference + var _id2 = parseInt(value.slice(2), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + { + var metadata = _chunk2.value; + return createServerReferenceProxy(response, metadata); + } + // We always encode it first in the stream so it won't be pending. + + default: + throw _chunk2.reason; + } + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id3 = parseInt(value.slice(1), 16); + + var _chunk3 = getChunk(response, _id3); + + switch (_chunk3.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk3); + break; + + case RESOLVED_MODULE: + initializeModuleChunk(_chunk3); + break; + } // The status might have changed after initialization. + + + switch (_chunk3.status) { + case INITIALIZED: + return _chunk3.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk3.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk3.reason; + } + } + } + } + + return value; +} +function parseModelTuple(response, value) { + var tuple = value; + + if (tuple[0] === REACT_ELEMENT_TYPE) { + // TODO: Consider having React just directly accept these arrays as elements. + // Or even change the ReactElement type to be an array. + return createElement(tuple[1], tuple[2], tuple[3]); + } + + 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 createResponse$1(bundlerConfig, callServer) { + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _callServer: callServer !== undefined ? callServer : missingCall, + _chunks: chunks + }; + return response; +} +function resolveModel(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createResolvedModelChunk(response, model)); + } else { + resolveModelChunk(chunk, model); + } +} +function resolveModule(response, id, model) { + var chunks = response._chunks; + var chunk = chunks.get(id); + var clientReferenceMetadata = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, clientReferenceMetadata); // TODO: Add an option to encode modules that are lazy loaded. + // For now we preload all modules as early as possible since it's likely + // that we'll need them. + + var promise = preloadModule(clientReference); + + if (promise) { + var blockedChunk; + + if (!chunk) { + // Technically, we should just treat promise as the chunk in this + // case. Because it'll just behave as any other promise. + blockedChunk = createBlockedChunk(response); + chunks.set(id, blockedChunk); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + blockedChunk = chunk; + blockedChunk.status = BLOCKED; + } + + promise.then(function () { + return resolveModuleChunk(blockedChunk, clientReference); + }, function (error) { + return triggerErrorOnChunk(blockedChunk, error); + }); + } else { + if (!chunk) { + chunks.set(id, createResolvedModuleChunk(response, clientReference)); + } else { + // This can't actually happen because we don't have any forward + // references to modules. + resolveModuleChunk(chunk, clientReference); + } + } +} +function resolveErrorDev(response, id, digest, message, stack) { + + + var error = new Error(message || 'An error occurred in the Server Components render but no message was provided'); + error.stack = stack; + error.digest = digest; + var errorWithDigest = error; + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + chunks.set(id, createErrorChunk(response, errorWithDigest)); + } else { + triggerErrorOnChunk(chunk, errorWithDigest); + } +} +function resolveHint(response, code, model) { + var hintModel = parseModel(response, model); + dispatchHint(code, hintModel); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function processFullRow(response, row) { + if (row === '') { + return; + } + + var colon = row.indexOf(':', 0); + var id = parseInt(row.slice(0, colon), 16); + var tag = row[colon + 1]; // When tags that are not text are added, check them here before + // parsing the row as text. + // switch (tag) { + // } + + switch (tag) { + case 'I': + { + resolveModule(response, id, row.slice(colon + 2)); + return; + } + + case 'H': + { + var code = row[colon + 2]; + resolveHint(response, code, row.slice(colon + 3)); + return; + } + + case 'E': + { + var errorInfo = JSON.parse(row.slice(colon + 2)); + + { + resolveErrorDev(response, id, errorInfo.digest, errorInfo.message, errorInfo.stack); + } + + return; + } + + default: + { + // We assume anything else is JSON. + resolveModel(response, id, row.slice(colon + 1)); + return; + } + } +} + +function processStringChunk(response, chunk, offset) { + var linebreak = chunk.indexOf('\n', offset); + + while (linebreak > -1) { + var fullrow = response._partialRow + chunk.slice(offset, linebreak); + processFullRow(response, fullrow); + response._partialRow = ''; + offset = linebreak + 1; + linebreak = chunk.indexOf('\n', offset); + } + + response._partialRow += chunk.slice(offset); +} +function processBinaryChunk(response, chunk) { + + var stringDecoder = response._stringDecoder; + var linebreak = chunk.indexOf(10); // newline + + while (linebreak > -1) { + var fullrow = response._partialRow + readFinalStringChunk(stringDecoder, chunk.subarray(0, linebreak)); + processFullRow(response, fullrow); + response._partialRow = ''; + chunk = chunk.subarray(linebreak + 1); + linebreak = chunk.indexOf(10); // newline + } + + response._partialRow += readPartialStringChunk(stringDecoder, chunk); +} + +function createFromJSONCallback(response) { + // $FlowFixMe[missing-this-annot] + return function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + if (typeof value === 'object' && value !== null) { + return parseModelTuple(response, value); + } + + return value; + }; +} + +function createResponse(bundlerConfig, callServer) { + // NOTE: CHECK THE COMPILER OUTPUT EACH TIME YOU CHANGE THIS. + // It should be inlined to one object literal but minor changes can break it. + var stringDecoder = createStringDecoder() ; + var response = createResponse$1(bundlerConfig, callServer); + response._partialRow = ''; + + { + response._stringDecoder = stringDecoder; + } // Don't inline this call because it causes closure to outline the call above. + + + response._fromJSON = createFromJSONCallback(response); + return response; +} + +function noServerCall() { + throw new Error('Server Functions cannot be called during initial render. ' + 'This would create a fetch waterfall. Try to use a Server Component ' + 'to pass data to Client Components instead.'); +} + +function createServerReference(id, callServer) { + return noServerCall; +} + +function createFromNodeStream(stream, moduleMap) { + var response = createResponse(moduleMap, noServerCall); + stream.on('data', function (chunk) { + if (typeof chunk === 'string') { + processStringChunk(response, chunk, 0); + } else { + processBinaryChunk(response, chunk); + } + }); + stream.on('error', function (error) { + reportGlobalError(response, error); + }); + stream.on('end', function () { + return close(response); + }); + return getRoot(response); +} + +exports.createFromNodeStream = createFromNodeStream; +exports.createServerReference = createServerReference; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js new file mode 100644 index 0000000000000..6377268871197 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.node.unbundled.production.min.js @@ -0,0 +1,26 @@ +/** + * @license React + * react-server-dom-webpack-client.node.unbundled.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var g=require("util"),k=require("react-dom"),l=require("react"),m={stream:!0};function p(a,b){var c=a[b.id];if(a=c[b.name])b=a.name;else{a=c["*"];if(!a)throw Error('Could not find the module "'+b.id+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');b=b.name}return{specifier:a.specifier,name:b}}var q=new Map; +function r(a){var b=q.get(a.specifier);if(b)return"fulfilled"===b.status?null:b;var c=import(a.specifier);c.then(function(d){c.status="fulfilled";c.value=d},function(d){c.status="rejected";c.reason=d});q.set(a.specifier,c);return c}var t=k.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher,u=new WeakMap,v=Symbol.for("react.element"),w=Symbol.for("react.lazy"),x=Symbol.for("react.default_value"),y=l.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ContextRegistry; +function z(a,b,c,d){this.status=a;this.value=b;this.reason=c;this._response=d}z.prototype=Object.create(Promise.prototype);z.prototype.then=function(a,b){switch(this.status){case "resolved_model":A(this);break;case "resolved_module":B(this)}switch(this.status){case "fulfilled":a(this.value);break;case "pending":case "blocked":a&&(null===this.value&&(this.value=[]),this.value.push(a));b&&(null===this.reason&&(this.reason=[]),this.reason.push(b));break;default:b(this.reason)}}; +function C(a){switch(a.status){case "resolved_model":A(a);break;case "resolved_module":B(a)}switch(a.status){case "fulfilled":return a.value;case "pending":case "blocked":throw a;default:throw a.reason;}}function D(a,b){for(var c=0;c{e=e.contextModuleFactory;const l=b.resolverFactory.get("context", +{}),a=b.resolverFactory.get("normal");n.resolveAllClientFiles(b.context,l,a,b.inputFileSystem,e,function(c,d){c?g(c):(p=d,g())})});b.hooks.thisCompilation.tap("React Server Plugin",(e,g)=>{g=g.normalModuleFactory;e.dependencyFactories.set(G,g);e.dependencyTemplates.set(G,new C.Template);e=l=>{l.hooks.program.tap("React Server Plugin",()=>{const a=l.state.module;if(a.resource===H&&(t=!0,p))for(let d=0;d{e.hooks.processAssets.tap({name:"React Server Plugin",stage:E.Compilation.PROCESS_ASSETS_STAGE_REPORT},function(){if(!1===t)e.warnings.push(new E.WebpackError("Client runtime at react-server-dom-webpack/client was not found. React Server Components module map file "+ +n.clientManifestFilename+" was not created."));else{var g=new Set((p||[]).map(d=>d.request)),l={},a={};e.chunkGroups.forEach(function(d){function m(k,f){if(g.has(f.resource)&&(f=u.pathToFileURL(f.resource).href,void 0!==f)){const h={};l[f]={id:k,chunks:q,name:"*"};h["*"]={specifier:f,name:"*"};a[k]=h}}const q=d.chunks.map(function(k){return k.id});d.chunks.forEach(function(k){k=e.chunkGraph.getChunkModulesIterable(k);Array.from(k).forEach(function(f){const h=e.chunkGraph.getModuleId(f);m(h,f);f.modules&& +f.modules.forEach(v=>{m(h,v)})})})});var c=JSON.stringify(l,null,2);e.emitAsset(n.clientManifestFilename,new E.sources.RawSource(c,!1));c=JSON.stringify(a,null,2);e.emitAsset(n.ssrManifestFilename,new E.sources.RawSource(c,!1))}})})}resolveAllClientFiles(b,n,p,t,e,g){function l(a){if(-1===a.indexOf("use client"))return!1;let c;try{c=A.parse(a,{ecmaVersion:"2024",sourceType:"module"}).body}catch(d){return!1}for(a=0;a{"string"===typeof a?c(null,[new G(a)]):n.resolve({},b,a.directory,{},(d,m)=>{if(d)return c(d);e.resolveDependencies(t,{resource:m,resourceQuery:"",recursive:void 0===a.recursive?!0:a.recursive,regExp:a.include,include:void 0,exclude:a.exclude},(q,k)=>{if(q)return c(q);q=k.map(f=>{var h=r.join(m,f.userRequest);h=new G(h);h.userRequest=f.userRequest;return h});x.filter(q,(f,h)=>{p.resolve({},b,f.request,{},(v,y)=>{if(v|| +"string"!==typeof y)return h(null,!1);t.readFile(y,"utf-8",(w,z)=>{if(w||"string"!==typeof z)return h(null,!1);w=l(z);h(null,w)})})},c)})})},(a,c)=>{if(a)return g(a);a=[];for(let d=0;d 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + callback(); +} +var VIEW_SIZE = 512; +var currentView = null; +var writtenBytes = 0; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; +} +function writeChunk(destination, chunk) { + if (chunk.length === 0) { + return; + } + + if (chunk.length > VIEW_SIZE) { + { + if (precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + destination.enqueue(chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.length) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + destination.enqueue(currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view + + destination.enqueue(currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.length; +} +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more + + return true; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = null; + writtenBytes = 0; + } +} +function close$1(destination) { + destination.close(); +} +var textEncoder = new TextEncoder(); +function stringToChunk(content) { + return textEncoder.encode(content); +} +var precomputedChunkSet = new Set() ; +function closeWithError(destination, error) { + // $FlowFixMe[method-unbinding] + if (typeof destination.error === 'function') { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.error(error); + } else { + // Earlier implementations doesn't support this method. In that environment you're + // supposed to throw from a promise returned but we don't return a promise in our + // approach. We could fork this implementation but this is environment is an edge + // case to begin with. It's even less common to run this in an older environment. + // Even then, this is not where errors are supposed to happen and they get reported + // to a global callback in addition to this anyway. So it's fine just to close this. + destination.close(); + } +} + +// This file is an intermediate layer to translate between Flight +var stringify = JSON.stringify; + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function processErrorChunkProd(request, id, digest) { + { + // These errors should never make it into a build so we don't need to encode them in codes.json + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('processErrorChunkProd should never be called while in development mode. Use processErrorChunkDev instead. This is a bug in React.'); + } +} +function processErrorChunkDev(request, id, digest, message, stack) { + + var errorInfo = { + digest: digest, + message: message, + stack: stack + }; + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + return stringToChunk(row); +} +function processModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + return stringToChunk(row); +} +function processHintChunk(request, id, code, model) { + var json = stringify(model); + var row = serializeRowHeader('H' + code, id) + json + '\n'; + return stringToChunk(row); +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: !!clientReference.$$async + }; +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preinit: preinit +}; + +function prefetchDNS(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'D', [href, options]); + } else { + emitHint(request, 'D', href); + } + } + } + } +} + +function preconnect(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : ''; + var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'C', [href, options]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'L', [href, options]); + } + } + } +} + +function preinit(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'I' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'I', [href, options]); + } + } + } +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +function createHints() { + return new Set(); +} + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useMutableSource: unsupportedHook, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value + REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); + } + + return ContextRegistry[globalName]; +} + +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedJSONChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt.message, + stack = _getErrorMessageAndSt.stack; + + emitErrorChunkDev(request, newTask.id, digest, message, stack); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + + { + var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason), + _message = _getErrorMessageAndSt2.message, + _stack = _getErrorMessageAndSt2.stack; + + emitErrorChunkDev(request, newTask.id, digest, _message, _stack); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt3 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt3.message, + stack = _getErrorMessageAndSt3.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeByValueID(errorId); + } +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + request.pendingChunks++; + var metadataId = request.nextChunkId++; // We assume that this object doesn't suspend. + + var processedChunk = processModelChunk(request, metadataId, serverReferenceMetadata); + request.completedJSONChunks.push(processedChunk); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else { + // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt4 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt4.message, + stack = _getErrorMessageAndSt4.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeLazyID(errorId); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; // $FlowFixMe[method-unbinding] + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function getErrorMessageAndStackDev(error) { + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + return { + message: message, + stack: stack + }; + } +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitErrorChunkProd(request, id, digest) { + var processedChunk = processErrorChunkProd(); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunkDev(request, id, digest, message, stack) { + var processedChunk = processErrorChunkDev(request, id, digest, message, stack); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + var processedChunk = processImportChunk(request, id, clientReferenceMetadata); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var processedChunk = processHintChunk(request, request.nextChunkId++, code, model); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = processReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = processReferenceChunk(request, id, contextReference); + request.completedJSONChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + var processedChunk = processModelChunk(request, task.id, value); + request.completedJSONChunks.push(processedChunk); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt5 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt5.message, + stack = _getErrorMessageAndSt5.stack; + + emitErrorChunkDev(request, task.id, digest, message, stack); + } + } + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = processReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var jsonChunks = request.completedJSONChunks; + i = 0; + + for (; i < jsonChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = jsonChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + { + scheduleWork(function () { + return performWork(request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} // This is called to early terminate a request. It creates an error at all pending tasks. + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + + if (true) { + var _getErrorMessageAndSt6 = getErrorMessageAndStackDev(error), + message = _getErrorMessageAndSt6.message, + stack = _getErrorMessageAndSt6.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +// eslint-disable-next-line no-unused-vars +function resolveServerReference(bundlerConfig, id) { + var name = ''; + var resolvedModuleData = bundlerConfig[id]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = id.lastIndexOf('#'); + + if (idx !== -1) { + name = id.slice(idx + 1); + resolvedModuleData = bundlerConfig[id.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } // TODO: This needs to return async: true if it's an async module. + + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: false + }; +} // The chunk cache contains all the chunks we've preloaded so far. +// If they're still pending they're a thenable. This map also exists +// in Webpack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); +var asyncModuleCache = new Map(); + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata.chunks; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkId = chunks[i]; + var entry = chunkCache.get(chunkId); + + if (entry === undefined) { + var thenable = globalThis.__next_chunk_load__(chunkId); + + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkId, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (metadata.async) { + var existingPromise = asyncModuleCache.get(metadata.id); + + if (existingPromise) { + if (existingPromise.status === 'fulfilled') { + return null; + } + + return existingPromise; + } else { + var modulePromise = Promise.all(promises).then(function () { + return globalThis.__next_require__(metadata.id); + }); + modulePromise.then(function (value) { + var fulfilledThenable = modulePromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = modulePromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + asyncModuleCache.set(metadata.id, modulePromise); + return modulePromise; + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports; + + if (metadata.async) { + // We assume that preloadModule has been called before, which + // should have added something to the module cache. + var promise = asyncModuleCache.get(metadata.id); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + } else { + moduleExports = globalThis.__next_require__(metadata.id); + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata.name]; +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + if (_chunk.status === RESOLVED_MODEL) { + initializeModelChunk(_chunk); + } + + if (_chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw _chunk.reason; + } // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = _chunk.value; + return loadServerReference(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + var data = new FormData(); + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + data.append(entryKey.slice(formPrefix.length), entry); + } + }); + return data; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id2 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function renderToReadableStream(model, webpackMap, options) { + var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined); + + if (options && options.signal) { + var signal = options.signal; + + if (signal.aborted) { + abort(request, signal.reason); + } else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener('abort', listener); + }; + + signal.addEventListener('abort', listener); + } + } + + var stream = new ReadableStream({ + type: 'bytes', + start: function (controller) { + startWork(request); + }, + pull: function (controller) { + startFlowing(request, controller); + }, + cancel: function (reason) {} + }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. + { + highWaterMark: 0 + }); + return stream; +} + +function decodeReply(body, webpackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(webpackMap, '', body); + close(response); + return getRoot(response); +} + +exports.decodeReply = decodeReply; +exports.renderToReadableStream = renderToReadableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.browser.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.browser.production.min.js new file mode 100644 index 0000000000000..bb5006d5b2b39 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.browser.production.min.js @@ -0,0 +1,62 @@ +/** + * @license React + * react-server-dom-webpack-server.browser.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("react-dom"),ba=require("react"),l=null,m=0;function n(a,b){if(0!==b.length)if(512a.depth?za(b,a):Aa(b,a),E=a)}function Ba(a,b){var d=a._currentValue;a._currentValue=b;var c=E;return E=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var H=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Ca(){}function Da(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Ca,Ca),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}I=b;throw H;}}var I=null; +function Ea(){if(null===I)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=I;I=null;return a}var J=null,K=0,L=null;function Fa(){var a=L;L=null;return a}function Ga(a){return a._currentValue} +var Ka={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:M,useTransition:M,readContext:Ga,useContext:Ga,useReducer:M,useRef:M,useState:M,useInsertionEffect:M,useLayoutEffect:M,useImperativeHandle:M,useEffect:M,useId:Ha,useMutableSource:M,useSyncExternalStore:M,useCacheRefresh:function(){return Ia},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(O(a))return"[...]";a=Na(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function P(a){if("string"===typeof a)return a;switch(a){case ra:return"Suspense";case sa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case qa:return P(a.render);case ta:return P(a.type);case D:var b=a._payload;a=a._init;try{return P(a(b))}catch(d){}}return""} +function Q(a,b){var d=Na(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(O(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===C)e="<"+P(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gk.length&&40>e.length+k.length?e+k:e+"..."}e+="}"}return void 0===b?e:-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + setTimeout(callback, 0); +} +var VIEW_SIZE = 512; +var currentView = null; +var writtenBytes = 0; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; +} +function writeChunk(destination, chunk) { + if (chunk.length === 0) { + return; + } + + if (chunk.length > VIEW_SIZE) { + { + if (precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + destination.enqueue(chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.length) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + destination.enqueue(currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view + + destination.enqueue(currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.length; +} +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more + + return true; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)); + currentView = null; + writtenBytes = 0; + } +} +function close$1(destination) { + destination.close(); +} +var textEncoder = new TextEncoder(); +function stringToChunk(content) { + return textEncoder.encode(content); +} +var precomputedChunkSet = new Set() ; +function closeWithError(destination, error) { + // $FlowFixMe[method-unbinding] + if (typeof destination.error === 'function') { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.error(error); + } else { + // Earlier implementations doesn't support this method. In that environment you're + // supposed to throw from a promise returned but we don't return a promise in our + // approach. We could fork this implementation but this is environment is an edge + // case to begin with. It's even less common to run this in an older environment. + // Even then, this is not where errors are supposed to happen and they get reported + // to a global callback in addition to this anyway. So it's fine just to close this. + destination.close(); + } +} + +// This file is an intermediate layer to translate between Flight +var stringify = JSON.stringify; + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function processErrorChunkProd(request, id, digest) { + { + // These errors should never make it into a build so we don't need to encode them in codes.json + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('processErrorChunkProd should never be called while in development mode. Use processErrorChunkDev instead. This is a bug in React.'); + } +} +function processErrorChunkDev(request, id, digest, message, stack) { + + var errorInfo = { + digest: digest, + message: message, + stack: stack + }; + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + return stringToChunk(row); +} +function processModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + return stringToChunk(row); +} +function processHintChunk(request, id, code, model) { + var json = stringify(model); + var row = serializeRowHeader('H' + code, id) + json + '\n'; + return stringToChunk(row); +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: !!clientReference.$$async + }; +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preinit: preinit +}; + +function prefetchDNS(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'D', [href, options]); + } else { + emitHint(request, 'D', href); + } + } + } + } +} + +function preconnect(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : ''; + var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'C', [href, options]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'L', [href, options]); + } + } + } +} + +function preinit(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'I' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'I', [href, options]); + } + } + } +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +function createHints() { + return new Set(); +} + +var supportsRequestStorage = typeof AsyncLocalStorage === 'function'; +var requestStorage = supportsRequestStorage ? new AsyncLocalStorage() : null; + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useMutableSource: unsupportedHook, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value + REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); + } + + return ContextRegistry[globalName]; +} + +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedJSONChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + if (supportsRequestStorage) { + var store = requestStorage.getStore(); + if (store) return store; + } + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt.message, + stack = _getErrorMessageAndSt.stack; + + emitErrorChunkDev(request, newTask.id, digest, message, stack); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + + { + var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason), + _message = _getErrorMessageAndSt2.message, + _stack = _getErrorMessageAndSt2.stack; + + emitErrorChunkDev(request, newTask.id, digest, _message, _stack); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt3 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt3.message, + stack = _getErrorMessageAndSt3.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeByValueID(errorId); + } +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + request.pendingChunks++; + var metadataId = request.nextChunkId++; // We assume that this object doesn't suspend. + + var processedChunk = processModelChunk(request, metadataId, serverReferenceMetadata); + request.completedJSONChunks.push(processedChunk); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else { + // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt4 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt4.message, + stack = _getErrorMessageAndSt4.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeLazyID(errorId); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; // $FlowFixMe[method-unbinding] + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function getErrorMessageAndStackDev(error) { + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + return { + message: message, + stack: stack + }; + } +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitErrorChunkProd(request, id, digest) { + var processedChunk = processErrorChunkProd(); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunkDev(request, id, digest, message, stack) { + var processedChunk = processErrorChunkDev(request, id, digest, message, stack); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + var processedChunk = processImportChunk(request, id, clientReferenceMetadata); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var processedChunk = processHintChunk(request, request.nextChunkId++, code, model); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = processReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = processReferenceChunk(request, id, contextReference); + request.completedJSONChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + var processedChunk = processModelChunk(request, task.id, value); + request.completedJSONChunks.push(processedChunk); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt5 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt5.message, + stack = _getErrorMessageAndSt5.stack; + + emitErrorChunkDev(request, task.id, digest, message, stack); + } + } + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = processReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var jsonChunks = request.completedJSONChunks; + i = 0; + + for (; i < jsonChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = jsonChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + if (supportsRequestStorage) { + scheduleWork(function () { + return requestStorage.run(request, performWork, request); + }); + } else { + scheduleWork(function () { + return performWork(request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} // This is called to early terminate a request. It creates an error at all pending tasks. + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + + if (true) { + var _getErrorMessageAndSt6 = getErrorMessageAndStackDev(error), + message = _getErrorMessageAndSt6.message, + stack = _getErrorMessageAndSt6.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +// eslint-disable-next-line no-unused-vars +function resolveServerReference(bundlerConfig, id) { + var name = ''; + var resolvedModuleData = bundlerConfig[id]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = id.lastIndexOf('#'); + + if (idx !== -1) { + name = id.slice(idx + 1); + resolvedModuleData = bundlerConfig[id.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } // TODO: This needs to return async: true if it's an async module. + + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: false + }; +} // The chunk cache contains all the chunks we've preloaded so far. +// If they're still pending they're a thenable. This map also exists +// in Webpack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); +var asyncModuleCache = new Map(); + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata.chunks; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkId = chunks[i]; + var entry = chunkCache.get(chunkId); + + if (entry === undefined) { + var thenable = globalThis.__next_chunk_load__(chunkId); + + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkId, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (metadata.async) { + var existingPromise = asyncModuleCache.get(metadata.id); + + if (existingPromise) { + if (existingPromise.status === 'fulfilled') { + return null; + } + + return existingPromise; + } else { + var modulePromise = Promise.all(promises).then(function () { + return globalThis.__next_require__(metadata.id); + }); + modulePromise.then(function (value) { + var fulfilledThenable = modulePromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = modulePromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + asyncModuleCache.set(metadata.id, modulePromise); + return modulePromise; + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports; + + if (metadata.async) { + // We assume that preloadModule has been called before, which + // should have added something to the module cache. + var promise = asyncModuleCache.get(metadata.id); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + } else { + moduleExports = globalThis.__next_require__(metadata.id); + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata.name]; +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + if (_chunk.status === RESOLVED_MODEL) { + initializeModelChunk(_chunk); + } + + if (_chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw _chunk.reason; + } // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = _chunk.value; + return loadServerReference(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + var data = new FormData(); + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + data.append(entryKey.slice(formPrefix.length), entry); + } + }); + return data; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id2 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function renderToReadableStream(model, webpackMap, options) { + var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined); + + if (options && options.signal) { + var signal = options.signal; + + if (signal.aborted) { + abort(request, signal.reason); + } else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener('abort', listener); + }; + + signal.addEventListener('abort', listener); + } + } + + var stream = new ReadableStream({ + type: 'bytes', + start: function (controller) { + startWork(request); + }, + pull: function (controller) { + startFlowing(request, controller); + }, + cancel: function (reason) {} + }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. + { + highWaterMark: 0 + }); + return stream; +} + +function decodeReply(body, webpackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(webpackMap, '', body); + close(response); + return getRoot(response); +} + +exports.decodeReply = decodeReply; +exports.renderToReadableStream = renderToReadableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.edge.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.edge.production.min.js new file mode 100644 index 0000000000000..598376f18df19 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.edge.production.min.js @@ -0,0 +1,62 @@ +/** + * @license React + * react-server-dom-webpack-server.edge.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("react"),ba=require("react-dom"),l=null,m=0;function n(a,b){if(0!==b.length)if(512a.depth?Aa(b,a):Ba(b,a),F=a)}function Ca(a,b){var d=a._currentValue;a._currentValue=b;var c=F;return F=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var I=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Da(){}function Ea(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Da,Da),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}J=b;throw I;}}var J=null; +function Fa(){if(null===J)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=J;J=null;return a}var K=null,L=0,M=null;function Ga(){var a=M;M=null;return a}function Ha(a){return a._currentValue} +var La={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:N,useTransition:N,readContext:Ha,useContext:Ha,useReducer:N,useRef:N,useState:N,useInsertionEffect:N,useLayoutEffect:N,useImperativeHandle:N,useEffect:N,useId:Ia,useMutableSource:N,useSyncExternalStore:N,useCacheRefresh:function(){return Ja},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(Pa(a))return"[...]";a=Qa(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function O(a){if("string"===typeof a)return a;switch(a){case sa:return"Suspense";case ta:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case ra:return O(a.render);case ua:return O(a.type);case E:var b=a._payload;a=a._init;try{return O(a(b))}catch(d){}}return""} +function P(a,b){var d=Qa(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(Pa(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===D)e="<"+O(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gk.length&&40>e.length+k.length?e+k:e+"..."}e+="}"}return void 0===b?e:-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + setImmediate(callback); +} +function flushBuffered(destination) { + // If we don't have any more data to send right now. + // Flush whatever is in the buffer to the wire. + if (typeof destination.flush === 'function') { + // By convention the Zlib streams provide a flush function for this purpose. + // For Express, compression middleware adds this method. + destination.flush(); + } +} +var VIEW_SIZE = 2048; +var currentView = null; +var writtenBytes = 0; +var destinationHasCapacity = true; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + destinationHasCapacity = true; +} + +function writeStringChunk(destination, stringChunk) { + if (stringChunk.length === 0) { + return; + } // maximum possible view needed to encode entire string + + + if (stringChunk.length * 3 > VIEW_SIZE) { + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, textEncoder.encode(stringChunk)); + return; + } + + var target = currentView; + + if (writtenBytes > 0) { + target = currentView.subarray(writtenBytes); + } + + var _textEncoder$encodeIn = textEncoder.encodeInto(stringChunk, target), + read = _textEncoder$encodeIn.read, + written = _textEncoder$encodeIn.written; + + writtenBytes += written; + + if (read < stringChunk.length) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = textEncoder.encodeInto(stringChunk.slice(read), currentView).written; + } + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeViewChunk(destination, chunk) { + if (chunk.byteLength === 0) { + return; + } + + if (chunk.byteLength > VIEW_SIZE) { + { + if (precomputedChunkSet && precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.byteLength) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + writeToDestination(destination, currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); + writtenBytes += allowableBytes; + writeToDestination(destination, currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.byteLength; + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeChunk(destination, chunk) { + if (typeof chunk === 'string') { + writeStringChunk(destination, chunk); + } else { + writeViewChunk(destination, chunk); + } +} + +function writeToDestination(destination, view) { + var currentHasCapacity = destination.write(view); + destinationHasCapacity = destinationHasCapacity && currentHasCapacity; +} + +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); + return destinationHasCapacity; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.write(currentView.subarray(0, writtenBytes)); + } + + currentView = null; + writtenBytes = 0; + destinationHasCapacity = true; +} +function close$1(destination) { + destination.end(); +} +var textEncoder = new util.TextEncoder(); +function stringToChunk(content) { + return content; +} +var precomputedChunkSet = new Set() ; +function closeWithError(destination, error) { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.destroy(error); +} + +// This file is an intermediate layer to translate between Flight +var stringify = JSON.stringify; + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function processErrorChunkProd(request, id, digest) { + { + // These errors should never make it into a build so we don't need to encode them in codes.json + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('processErrorChunkProd should never be called while in development mode. Use processErrorChunkDev instead. This is a bug in React.'); + } +} +function processErrorChunkDev(request, id, digest, message, stack) { + + var errorInfo = { + digest: digest, + message: message, + stack: stack + }; + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + return stringToChunk(row); +} +function processModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + return stringToChunk(row); +} +function processHintChunk(request, id, code, model) { + var json = stringify(model); + var row = serializeRowHeader('H' + code, id) + json + '\n'; + return stringToChunk(row); +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: !!clientReference.$$async + }; +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preinit: preinit +}; + +function prefetchDNS(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'D', [href, options]); + } else { + emitHint(request, 'D', href); + } + } + } + } +} + +function preconnect(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : ''; + var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'C', [href, options]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'L', [href, options]); + } + } + } +} + +function preinit(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'I' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'I', [href, options]); + } + } + } +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +function createHints() { + return new Set(); +} + +var requestStorage = new async_hooks.AsyncLocalStorage(); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useMutableSource: unsupportedHook, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value + REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); + } + + return ContextRegistry[globalName]; +} + +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedJSONChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + { + var store = requestStorage.getStore(); + if (store) return store; + } + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt.message, + stack = _getErrorMessageAndSt.stack; + + emitErrorChunkDev(request, newTask.id, digest, message, stack); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + + { + var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason), + _message = _getErrorMessageAndSt2.message, + _stack = _getErrorMessageAndSt2.stack; + + emitErrorChunkDev(request, newTask.id, digest, _message, _stack); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt3 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt3.message, + stack = _getErrorMessageAndSt3.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeByValueID(errorId); + } +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + request.pendingChunks++; + var metadataId = request.nextChunkId++; // We assume that this object doesn't suspend. + + var processedChunk = processModelChunk(request, metadataId, serverReferenceMetadata); + request.completedJSONChunks.push(processedChunk); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else { + // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt4 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt4.message, + stack = _getErrorMessageAndSt4.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeLazyID(errorId); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; // $FlowFixMe[method-unbinding] + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function getErrorMessageAndStackDev(error) { + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + return { + message: message, + stack: stack + }; + } +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitErrorChunkProd(request, id, digest) { + var processedChunk = processErrorChunkProd(); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunkDev(request, id, digest, message, stack) { + var processedChunk = processErrorChunkDev(request, id, digest, message, stack); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + var processedChunk = processImportChunk(request, id, clientReferenceMetadata); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var processedChunk = processHintChunk(request, request.nextChunkId++, code, model); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = processReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = processReferenceChunk(request, id, contextReference); + request.completedJSONChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + var processedChunk = processModelChunk(request, task.id, value); + request.completedJSONChunks.push(processedChunk); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt5 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt5.message, + stack = _getErrorMessageAndSt5.stack; + + emitErrorChunkDev(request, task.id, digest, message, stack); + } + } + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = processReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var jsonChunks = request.completedJSONChunks; + i = 0; + + for (; i < jsonChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = jsonChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + flushBuffered(destination); + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + { + scheduleWork(function () { + return requestStorage.run(request, performWork, request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} // This is called to early terminate a request. It creates an error at all pending tasks. + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + + if (true) { + var _getErrorMessageAndSt6 = getErrorMessageAndStackDev(error), + message = _getErrorMessageAndSt6.message, + stack = _getErrorMessageAndSt6.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +// eslint-disable-next-line no-unused-vars +function resolveServerReference(bundlerConfig, id) { + var name = ''; + var resolvedModuleData = bundlerConfig[id]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = id.lastIndexOf('#'); + + if (idx !== -1) { + name = id.slice(idx + 1); + resolvedModuleData = bundlerConfig[id.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } // TODO: This needs to return async: true if it's an async module. + + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: false + }; +} // The chunk cache contains all the chunks we've preloaded so far. +// If they're still pending they're a thenable. This map also exists +// in Webpack but unfortunately it's not exposed so we have to +// replicate it in user space. null means that it has already loaded. + +var chunkCache = new Map(); +var asyncModuleCache = new Map(); + +function ignoreReject() {// We rely on rejected promises to be handled by another listener. +} // Start preloading the modules since we might need them soon. +// This function doesn't suspend. + + +function preloadModule(metadata) { + var chunks = metadata.chunks; + var promises = []; + + for (var i = 0; i < chunks.length; i++) { + var chunkId = chunks[i]; + var entry = chunkCache.get(chunkId); + + if (entry === undefined) { + var thenable = globalThis.__next_chunk_load__(chunkId); + + promises.push(thenable); // $FlowFixMe[method-unbinding] + + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + thenable.then(resolve, ignoreReject); + chunkCache.set(chunkId, thenable); + } else if (entry !== null) { + promises.push(entry); + } + } + + if (metadata.async) { + var existingPromise = asyncModuleCache.get(metadata.id); + + if (existingPromise) { + if (existingPromise.status === 'fulfilled') { + return null; + } + + return existingPromise; + } else { + var modulePromise = Promise.all(promises).then(function () { + return globalThis.__next_require__(metadata.id); + }); + modulePromise.then(function (value) { + var fulfilledThenable = modulePromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = modulePromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + asyncModuleCache.set(metadata.id, modulePromise); + return modulePromise; + } + } else if (promises.length > 0) { + return Promise.all(promises); + } else { + return null; + } +} // Actually require the module or suspend if it's not yet ready. +// Increase priority if necessary. + +function requireModule(metadata) { + var moduleExports; + + if (metadata.async) { + // We assume that preloadModule has been called before, which + // should have added something to the module cache. + var promise = asyncModuleCache.get(metadata.id); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + } else { + moduleExports = globalThis.__next_require__(metadata.id); + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.__esModule ? moduleExports.default : moduleExports; + } + + return moduleExports[metadata.name]; +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + if (_chunk.status === RESOLVED_MODEL) { + initializeModelChunk(_chunk); + } + + if (_chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw _chunk.reason; + } // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = _chunk.value; + return loadServerReference(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + var data = new FormData(); + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + data.append(entryKey.slice(formPrefix.length), entry); + } + }); + return data; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id2 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function resolveField(response, key, value) { + // Add this field to the backing store. + response._formData.append(key, value); + + var prefix = response._prefix; + + if (key.startsWith(prefix)) { + var chunks = response._chunks; + var id = +key.slice(prefix.length); + var chunk = chunks.get(id); + + if (chunk) { + // We were waiting on this key so now we can resolve it. + resolveModelChunk(chunk, value); + } + } +} +function resolveFileInfo(response, key, filename, mime) { + return { + chunks: [], + filename: filename, + mime: mime + }; +} +function resolveFileChunk(response, handle, chunk) { + handle.chunks.push(chunk); +} +function resolveFileComplete(response, key, handle) { + // Add this file to the backing store. + // Node.js doesn't expose a global File constructor so we need to use + // the append() form that takes the file name as the third argument, + // to create a File object. + var blob = new Blob(handle.chunks, { + type: handle.mime + }); + + response._formData.append(key, blob, handle.filename); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function createDrainHandler(destination, request) { + return function () { + return startFlowing(request, destination); + }; +} + +function renderToPipeableStream(model, webpackMap, options) { + var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined); + var hasStartedFlowing = false; + startWork(request); + return { + pipe: function (destination) { + if (hasStartedFlowing) { + throw new Error('React currently only supports piping to one writable stream.'); + } + + hasStartedFlowing = true; + startFlowing(request, destination); + destination.on('drain', createDrainHandler(destination, request)); + return destination; + }, + abort: function (reason) { + abort(request, reason); + } + }; +} + +function decodeReplyFromBusboy(busboyStream, webpackMap) { + var response = createResponse(webpackMap, ''); + var pendingFiles = 0; + var queuedFields = []; + busboyStream.on('field', function (name, value) { + if (pendingFiles > 0) { + // Because the 'end' event fires two microtasks after the next 'field' + // we would resolve files and fields out of order. To handle this properly + // we queue any fields we receive until the previous file is done. + queuedFields.push(name, value); + } else { + resolveField(response, name, value); + } + }); + busboyStream.on('file', function (name, value, _ref) { + var filename = _ref.filename, + encoding = _ref.encoding, + mimeType = _ref.mimeType; + + if (encoding.toLowerCase() === 'base64') { + throw new Error("React doesn't accept base64 encoded file uploads because we don't expect " + "form data passed from a browser to ever encode data that way. If that's " + 'the wrong assumption, we can easily fix it.'); + } + + pendingFiles++; + var file = resolveFileInfo(response, name, filename, mimeType); + value.on('data', function (chunk) { + resolveFileChunk(response, file, chunk); + }); + value.on('end', function () { + resolveFileComplete(response, name, file); + pendingFiles--; + + if (pendingFiles === 0) { + // Release any queued fields + for (var i = 0; i < queuedFields.length; i += 2) { + resolveField(response, queuedFields[i], queuedFields[i + 1]); + } + + queuedFields.length = 0; + } + }); + }); + busboyStream.on('finish', function () { + close(response); + }); + busboyStream.on('error', function (err) { + reportGlobalError(response, err); + }); + return getRoot(response); +} + +function decodeReply(body, webpackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(webpackMap, '', body); + close(response); + return getRoot(response); +} + +exports.decodeReply = decodeReply; +exports.decodeReplyFromBusboy = decodeReplyFromBusboy; +exports.renderToPipeableStream = renderToPipeableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.production.min.js new file mode 100644 index 0000000000000..925ba2288e3cc --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.production.min.js @@ -0,0 +1,67 @@ +/** + * @license React + * react-server-dom-webpack-server.node.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("async_hooks"),ba=require("util"),ca=require("react"),da=require("react-dom"),l=null,m=0,p=!0;function r(a,b){a=a.write(b);p=p&&a} +function t(a,b){if("string"===typeof b){if(0!==b.length)if(2048<3*b.length)0a.depth?Ca(b,a):Da(b,a),F=a)}function Fa(a,b){var d=a._currentValue;a._currentValue=b;var c=F;return F=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var Ga=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Ha(){}function Ia(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Ha,Ha),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}H=b;throw Ga;}}var H=null; +function Ja(){if(null===H)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=H;H=null;return a}var I=null,J=0,K=null;function Ka(){var a=K;K=null;return a}function La(a){return a._currentValue} +var Pa={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:L,useTransition:L,readContext:La,useContext:La,useReducer:L,useRef:L,useState:L,useInsertionEffect:L,useLayoutEffect:L,useImperativeHandle:L,useEffect:L,useId:Ma,useMutableSource:L,useSyncExternalStore:L,useCacheRefresh:function(){return Na},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(Ta(a))return"[...]";a=Ua(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function M(a){if("string"===typeof a)return a;switch(a){case ua:return"Suspense";case va:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case ta:return M(a.render);case wa:return M(a.type);case E:var b=a._payload;a=a._init;try{return M(a(b))}catch(d){}}return""} +function N(a,b){var d=Ua(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(Ta(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===D)e="<"+M(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gk.length&&40>e.length+k.length?e+k:e+"..."}e+="}"}return void 0===b?e:-1 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + setImmediate(callback); +} +function flushBuffered(destination) { + // If we don't have any more data to send right now. + // Flush whatever is in the buffer to the wire. + if (typeof destination.flush === 'function') { + // By convention the Zlib streams provide a flush function for this purpose. + // For Express, compression middleware adds this method. + destination.flush(); + } +} +var VIEW_SIZE = 2048; +var currentView = null; +var writtenBytes = 0; +var destinationHasCapacity = true; +function beginWriting(destination) { + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + destinationHasCapacity = true; +} + +function writeStringChunk(destination, stringChunk) { + if (stringChunk.length === 0) { + return; + } // maximum possible view needed to encode entire string + + + if (stringChunk.length * 3 > VIEW_SIZE) { + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, textEncoder.encode(stringChunk)); + return; + } + + var target = currentView; + + if (writtenBytes > 0) { + target = currentView.subarray(writtenBytes); + } + + var _textEncoder$encodeIn = textEncoder.encodeInto(stringChunk, target), + read = _textEncoder$encodeIn.read, + written = _textEncoder$encodeIn.written; + + writtenBytes += written; + + if (read < stringChunk.length) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = textEncoder.encodeInto(stringChunk.slice(read), currentView).written; + } + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeViewChunk(destination, chunk) { + if (chunk.byteLength === 0) { + return; + } + + if (chunk.byteLength > VIEW_SIZE) { + { + if (precomputedChunkSet && precomputedChunkSet.has(chunk)) { + error('A large precomputed chunk was passed to writeChunk without being copied.' + ' Large chunks get enqueued directly and are not copied. This is incompatible with precomputed chunks because you cannot enqueue the same precomputed chunk twice.' + ' Use "cloneChunk" to make a copy of this large precomputed chunk before writing it. This is a bug in React.'); + } + } // this chunk may overflow a single view which implies it was not + // one that is cached by the streaming renderer. We will enqueu + // it directly and expect it is not re-used + + + if (writtenBytes > 0) { + writeToDestination(destination, currentView.subarray(0, writtenBytes)); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + writeToDestination(destination, chunk); + return; + } + + var bytesToWrite = chunk; + var allowableBytes = currentView.length - writtenBytes; + + if (allowableBytes < bytesToWrite.byteLength) { + // this chunk would overflow the current view. We enqueue a full view + // and start a new view with the remaining chunk + if (allowableBytes === 0) { + // the current view is already full, send it + writeToDestination(destination, currentView); + } else { + // fill up the current view and apply the remaining chunk bytes + // to a new view. + currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); + writtenBytes += allowableBytes; + writeToDestination(destination, currentView); + bytesToWrite = bytesToWrite.subarray(allowableBytes); + } + + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } + + currentView.set(bytesToWrite, writtenBytes); + writtenBytes += bytesToWrite.byteLength; + + if (writtenBytes === VIEW_SIZE) { + writeToDestination(destination, currentView); + currentView = new Uint8Array(VIEW_SIZE); + writtenBytes = 0; + } +} + +function writeChunk(destination, chunk) { + if (typeof chunk === 'string') { + writeStringChunk(destination, chunk); + } else { + writeViewChunk(destination, chunk); + } +} + +function writeToDestination(destination, view) { + var currentHasCapacity = destination.write(view); + destinationHasCapacity = destinationHasCapacity && currentHasCapacity; +} + +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); + return destinationHasCapacity; +} +function completeWriting(destination) { + if (currentView && writtenBytes > 0) { + destination.write(currentView.subarray(0, writtenBytes)); + } + + currentView = null; + writtenBytes = 0; + destinationHasCapacity = true; +} +function close$1(destination) { + destination.end(); +} +var textEncoder = new util.TextEncoder(); +function stringToChunk(content) { + return content; +} +var precomputedChunkSet = new Set() ; +function closeWithError(destination, error) { + // $FlowFixMe[incompatible-call]: This is an Error object or the destination accepts other types. + destination.destroy(error); +} + +// This file is an intermediate layer to translate between Flight +var stringify = JSON.stringify; + +function serializeRowHeader(tag, id) { + return id.toString(16) + ':' + tag; +} + +function processErrorChunkProd(request, id, digest) { + { + // These errors should never make it into a build so we don't need to encode them in codes.json + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('processErrorChunkProd should never be called while in development mode. Use processErrorChunkDev instead. This is a bug in React.'); + } +} +function processErrorChunkDev(request, id, digest, message, stack) { + + var errorInfo = { + digest: digest, + message: message, + stack: stack + }; + var row = serializeRowHeader('E', id) + stringify(errorInfo) + '\n'; + return stringToChunk(row); +} +function processModelChunk(request, id, model) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(model, request.toJSON); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processReferenceChunk(request, id, reference) { + var json = stringify(reference); + var row = id.toString(16) + ':' + json + '\n'; + return stringToChunk(row); +} +function processImportChunk(request, id, clientReferenceMetadata) { + // $FlowFixMe[incompatible-type] stringify can return null + var json = stringify(clientReferenceMetadata); + var row = serializeRowHeader('I', id) + json + '\n'; + return stringToChunk(row); +} +function processHintChunk(request, id, code, model) { + var json = stringify(model); + var row = serializeRowHeader('H' + code, id) + json + '\n'; + return stringToChunk(row); +} + +// eslint-disable-next-line no-unused-vars +var CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference'); +var SERVER_REFERENCE_TAG = Symbol.for('react.server.reference'); +function getClientReferenceKey(reference) { + return reference.$$async ? reference.$$id + '#async' : reference.$$id; +} +function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG; +} +function isServerReference(reference) { + return reference.$$typeof === SERVER_REFERENCE_TAG; +} +function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id; + var name = ''; + var resolvedModuleData = config[modulePath]; + + if (resolvedModuleData) { + // The potentially aliased name. + name = resolvedModuleData.name; + } else { + // We didn't find this specific export name but we might have the * export + // which contains this name as well. + // TODO: It's unfortunate that we now have to parse this string. We should + // probably go back to encoding path and name separately on the client reference. + var idx = modulePath.lastIndexOf('#'); + + if (idx !== -1) { + name = modulePath.slice(idx + 1); + resolvedModuleData = config[modulePath.slice(0, idx)]; + } + + if (!resolvedModuleData) { + throw new Error('Could not find the module "' + modulePath + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.'); + } + } + + return { + id: resolvedModuleData.id, + chunks: resolvedModuleData.chunks, + name: name, + async: !!clientReference.$$async + }; +} +function getServerReferenceId(config, serverReference) { + return serverReference.$$id; +} +function getServerReferenceBoundArguments(config, serverReference) { + return serverReference.$$bound; +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMFlightServerDispatcher = { + prefetchDNS: prefetchDNS, + preconnect: preconnect, + preload: preload, + preinit: preinit +}; + +function prefetchDNS(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'D' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'D', [href, options]); + } else { + emitHint(request, 'D', href); + } + } + } + } +} + +function preconnect(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var crossOrigin = options == null || typeof options.crossOrigin !== 'string' ? null : options.crossOrigin === 'use-credentials' ? 'use-credentials' : ''; + var key = "C" + (crossOrigin === null ? 'null' : crossOrigin) + "|" + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + + if (options) { + emitHint(request, 'C', [href, options]); + } else { + emitHint(request, 'C', href); + } + } + } + } +} + +function preload(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'L' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'L', [href, options]); + } + } + } +} + +function preinit(href, options) { + { + if (typeof href === 'string') { + var request = resolveRequest(); + + if (request) { + var hints = getHints(request); + var key = 'I' + href; + + if (hints.has(key)) { + // duplicate hint + return; + } + + hints.add(key); + emitHint(request, 'I', [href, options]); + } + } + } +} + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareHostDispatcher() { + ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. +function createHints() { + return new Set(); +} + +var requestStorage = new async_hooks.AsyncLocalStorage(); + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_SERVER_CONTEXT_TYPE = Symbol.for('react.server_context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var REACT_MEMO_CACHE_SENTINEL = Symbol.for('react.memo_cache_sentinel'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. +// The structure of a context snapshot is an implementation of this file. +// Currently, it's implemented as tracking the current active node. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); // On the way back, we push the new ones that weren't common. + + pushNode(next); + } + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe[incompatible-call]: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue; + context._currentValue = nextValue; + + { + if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider() { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + var value = prevSnapshot.parentValue; + + if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue = value; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext$1(context) { + var value = context._currentValue ; + return value; +} + +// Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally, +// changes to one module should be reflected in the others. +// TODO: Rename this module and the corresponding Fiber one to "Thenable" +// instead of "Wakeable". Or some other more appropriate name. +// An error that is thrown (e.g. by `use`) to trigger Suspense. If we +// detect this is caught by userspace, we'll log a warning in development. +var SuspenseException = new Error("Suspense Exception: This is not a real error! It's an implementation " + 'detail of `use` to interrupt the current render. You must either ' + 'rethrow it immediately, or move the `use` call outside of the ' + '`try/catch` block. Capturing without rethrowing will lead to ' + 'unexpected behavior.\n\n' + 'To handle async errors, wrap your component in an error boundary, or ' + "call the promise's `.catch` method and pass the result to `use`"); +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} + +function noop() {} + +function trackUsedThenable(thenableState, thenable, index) { + var previous = thenableState[index]; + + if (previous === undefined) { + thenableState.push(thenable); + } else { + if (previous !== thenable) { + // Reuse the previous thenable, and drop the new one. We can assume + // they represent the same value, because components are idempotent. + // Avoid an unhandled rejection errors for the Promises that we'll + // intentionally ignore. + thenable.then(noop, noop); + thenable = previous; + } + } // We use an expando to track the status and result of a thenable so that we + // can synchronously unwrap the value. Think of this as an extension of the + // Promise API, or a custom interface that is a superset of Thenable. + // + // If the thenable doesn't have a status, set it to "pending" and attach + // a listener that will update its status and result when it resolves. + + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + if (typeof thenable.status === 'string') ; else { + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); // Check one more time in case the thenable resolved synchronously + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledThenable = thenable; + return fulfilledThenable.value; + } + + case 'rejected': + { + var rejectedThenable = thenable; + throw rejectedThenable.reason; + } + } + } // Suspend. + // + // Throwing here is an implementation detail that allows us to unwind the + // call stack. But we shouldn't allow it to leak into userspace. Throw an + // opaque placeholder value instead of the actual thenable. If it doesn't + // get captured by the work loop, log a warning, because that means + // something in userspace must have caught it. + + + suspendedThenable = thenable; + throw SuspenseException; + } + } +} // This is used to track the actual thenable that suspended so it can be +// passed to the rest of the Suspense implementation — which, for historical +// reasons, expects to receive a thenable. + +var suspendedThenable = null; +function getSuspendedThenable() { + // This is called right after `use` suspends by throwing an exception. `use` + // throws an opaque value instead of the thenable itself so that it can't be + // caught in userspace. Then the work loop accesses the actual thenable using + // this function. + if (suspendedThenable === null) { + throw new Error('Expected a suspended thenable. This is a bug in React. Please file ' + 'an issue.'); + } + + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} + +var currentRequest$1 = null; +var thenableIndexCounter = 0; +var thenableState = null; +function prepareToUseHooksForRequest(request) { + currentRequest$1 = request; +} +function resetHooksForRequest() { + currentRequest$1 = null; +} +function prepareToUseHooksForComponent(prevThenableState) { + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} + +function readContext(context) { + { + if (context.$$typeof !== REACT_SERVER_CONTEXT_TYPE) { + if (isClientReference(context)) { + error('Cannot read a Client Context from a Server Component.'); + } else { + error('Only createServerContext is supported in Server Components.'); + } + } + + if (currentRequest$1 === null) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext$1(context); +} + +var HooksDispatcher = { + useMemo: function (nextCreate) { + return nextCreate(); + }, + useCallback: function (callback) { + return callback; + }, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + readContext: readContext, + useContext: readContext, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useInsertionEffect: unsupportedHook, + useLayoutEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useEffect: unsupportedHook, + useId: useId, + useMutableSource: unsupportedHook, + useSyncExternalStore: unsupportedHook, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useMemoCache: function (size) { + var data = new Array(size); + + for (var i = 0; i < size; i++) { + data[i] = REACT_MEMO_CACHE_SENTINEL; + } + + return data; + }, + use: use +}; + +function unsupportedHook() { + throw new Error('This Hook is not supported in Server Components.'); +} + +function unsupportedRefresh() { + throw new Error('Refreshing the cache is not supported in Server Components.'); +} + +function useId() { + if (currentRequest$1 === null) { + throw new Error('useId can only be used while React is rendering'); + } + + var id = currentRequest$1.identifierCount++; // use 'S' for Flight components to distinguish from 'R' and 'r' in Fizz/Client + + return ':' + currentRequest$1.identifierPrefix + 'S' + id.toString(32) + ':'; +} + +function use(usable) { + if (usable !== null && typeof usable === 'object' || typeof usable === 'function') { + // $FlowFixMe[method-unbinding] + if (typeof usable.then === 'function') { + // This is a thenable. + var thenable = usable; // Track the position of the thenable within this fiber. + + var index = thenableIndexCounter; + thenableIndexCounter += 1; + + if (thenableState === null) { + thenableState = createThenableState(); + } + + return trackUsedThenable(thenableState, thenable, index); + } else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext(context); + } + } + + { + if (isClientReference(usable)) { + error('Cannot use() an already resolved Client Reference.'); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function createSignal() { + return new AbortController().signal; +} + +function resolveCache() { + var request = resolveRequest(); + + if (request) { + return getCache(request); + } + + return new Map(); +} + +var DefaultCacheDispatcher = { + getCacheSignal: function () { + var cache = resolveCache(); + var entry = cache.get(createSignal); + + if (entry === undefined) { + entry = createSignal(); + cache.set(createSignal, entry); + } + + return entry; + }, + getCacheForType: function (resourceType) { + var cache = resolveCache(); + var entry = cache.get(resourceType); + + if (entry === undefined) { + entry = resourceType(); // TODO: Warn if undefined? + + cache.set(resourceType, entry); + } + + return entry; + } +}; + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +// in case they error. + +var jsxPropsParents = new WeakMap(); +var jsxChildrenParents = new WeakMap(); + +function isObjectPrototype(object) { + if (!object) { + return false; + } + + var ObjectPrototype = Object.prototype; + + if (object === ObjectPrototype) { + return true; + } // It might be an object from a different Realm which is + // still just a plain simple object. + + + if (Object.getPrototypeOf(object)) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + if (!(names[i] in ObjectPrototype)) { + return false; + } + } + + return true; +} + +function isSimpleObject(object) { + if (!isObjectPrototype(Object.getPrototypeOf(object))) { + return false; + } + + var names = Object.getOwnPropertyNames(object); + + for (var i = 0; i < names.length; i++) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + + if (!descriptor) { + return false; + } + + if (!descriptor.enumerable) { + if ((names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function') { + // React adds key and ref getters to props objects to issue warnings. + // Those getters will not be transferred to the client, but that's ok, + // so we'll special case them. + continue; + } + + return false; + } + } + + return true; +} +function objectName(object) { + // $FlowFixMe[method-unbinding] + var name = Object.prototype.toString.call(object); + return name.replace(/^\[object (.*)\]$/, function (m, p0) { + return p0; + }); +} + +function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; +} + +function describeValueForErrorMessage(value) { + switch (typeof value) { + case 'string': + { + return JSON.stringify(value.length <= 10 ? value : value.slice(0, 10) + '...'); + } + + case 'object': + { + if (isArray(value)) { + return '[...]'; + } + + var name = objectName(value); + + if (name === 'Object') { + return '{...}'; + } + + return name; + } + + case 'function': + return 'function'; + + default: + // eslint-disable-next-line react-internal/safe-string-coercion + return String(value); + } +} + +function describeElementType(type) { + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + + case REACT_MEMO_TYPE: + return describeElementType(type.type); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeElementType(init(payload)); + } catch (x) {} + } + } + } + + return ''; +} + +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + + if (objKind !== 'Object' && objKind !== 'Array') { + return objKind; + } + + var str = ''; + var start = -1; + var length = 0; + + if (isArray(objectOrArray)) { + if (jsxChildrenParents.has(objectOrArray)) { + // Print JSX Children + var type = jsxChildrenParents.get(objectOrArray); + str = '<' + describeElementType(type) + '>'; + var array = objectOrArray; + + for (var i = 0; i < array.length; i++) { + var value = array[i]; + var substr = void 0; + + if (typeof value === 'string') { + substr = value; + } else if (typeof value === 'object' && value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + substr = '{' + describeObjectForErrorMessage(value) + '}'; + } else { + substr = '{' + describeValueForErrorMessage(value) + '}'; + } + + if ('' + i === expandedName) { + start = str.length; + length = substr.length; + str += substr; + } else if (substr.length < 15 && str.length + substr.length < 40) { + str += substr; + } else { + str += '{...}'; + } + } + + str += ''; + } else { + // Print Array + str = '['; + var _array = objectOrArray; + + for (var _i = 0; _i < _array.length; _i++) { + if (_i > 0) { + str += ', '; + } + + var _value = _array[_i]; + + var _substr = void 0; + + if (typeof _value === 'object' && _value !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr = describeObjectForErrorMessage(_value); + } else { + _substr = describeValueForErrorMessage(_value); + } + + if ('' + _i === expandedName) { + start = str.length; + length = _substr.length; + str += _substr; + } else if (_substr.length < 10 && str.length + _substr.length < 40) { + str += _substr; + } else { + str += '...'; + } + } + + str += ']'; + } + } else { + if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) { + str = '<' + describeElementType(objectOrArray.type) + '/>'; + } else if (jsxPropsParents.has(objectOrArray)) { + // Print JSX + var _type = jsxPropsParents.get(objectOrArray); + + str = '<' + (describeElementType(_type) || '...'); + var object = objectOrArray; + var names = Object.keys(object); + + for (var _i2 = 0; _i2 < names.length; _i2++) { + str += ' '; + var name = names[_i2]; + str += describeKeyForErrorMessage(name) + '='; + var _value2 = object[name]; + + var _substr2 = void 0; + + if (name === expandedName && typeof _value2 === 'object' && _value2 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr2 = describeObjectForErrorMessage(_value2); + } else { + _substr2 = describeValueForErrorMessage(_value2); + } + + if (typeof _value2 !== 'string') { + _substr2 = '{' + _substr2 + '}'; + } + + if (name === expandedName) { + start = str.length; + length = _substr2.length; + str += _substr2; + } else if (_substr2.length < 10 && str.length + _substr2.length < 40) { + str += _substr2; + } else { + str += '...'; + } + } + + str += '>'; + } else { + // Print Object + str = '{'; + var _object = objectOrArray; + + var _names = Object.keys(_object); + + for (var _i3 = 0; _i3 < _names.length; _i3++) { + if (_i3 > 0) { + str += ', '; + } + + var _name = _names[_i3]; + str += describeKeyForErrorMessage(_name) + ': '; + var _value3 = _object[_name]; + + var _substr3 = void 0; + + if (typeof _value3 === 'object' && _value3 !== null) { + // $FlowFixMe[incompatible-call] found when upgrading Flow + _substr3 = describeObjectForErrorMessage(_value3); + } else { + _substr3 = describeValueForErrorMessage(_value3); + } + + if (_name === expandedName) { + start = str.length; + length = _substr3.length; + str += _substr3; + } else if (_substr3.length < 10 && str.length + _substr3.length < 40) { + str += _substr3; + } else { + str += '...'; + } + } + + str += '}'; + } + } + + if (expandedName === undefined) { + return str; + } + + if (start > -1 && length > 0) { + var highlight = ' '.repeat(start) + '^'.repeat(length); + return '\n ' + str + '\n ' + highlight; + } + + return '\n ' + str; +} + +var ContextRegistry = ReactSharedInternals.ContextRegistry; +function getOrCreateServerContext(globalName) { + if (!ContextRegistry[globalName]) { + ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe[incompatible-call] function signature doesn't reflect the symbol value + REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); + } + + return ContextRegistry[globalName]; +} + +// Thenable + +var PENDING$1 = 0; +var COMPLETED = 1; +var ABORTED = 3; +var ERRORED$1 = 4; +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper +} + +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +function createRequest(model, bundlerConfig, onError, context, identifierPrefix) { + if (ReactCurrentCache.current !== null && ReactCurrentCache.current !== DefaultCacheDispatcher) { + throw new Error('Currently React only supports one RSC renderer at a time.'); + } + + prepareHostDispatcher(); + ReactCurrentCache.current = DefaultCacheDispatcher; + var abortSet = new Set(); + var pingedTasks = []; + var hints = createHints(); + var request = { + status: OPEN, + flushScheduled: false, + fatalError: null, + destination: null, + bundlerConfig: bundlerConfig, + cache: new Map(), + nextChunkId: 0, + pendingChunks: 0, + hints: hints, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + completedImportChunks: [], + completedHintChunks: [], + completedJSONChunks: [], + completedErrorChunks: [], + writtenSymbols: new Map(), + writtenClientReferences: new Map(), + writtenServerReferences: new Map(), + writtenProviders: new Map(), + identifierPrefix: identifierPrefix || '', + identifierCount: 1, + onError: onError === undefined ? defaultErrorHandler : onError, + // $FlowFixMe[missing-this-annot] + toJSON: function (key, value) { + return resolveModelToJSON(request, this, key, value); + } + }; + request.pendingChunks++; + var rootContext = createRootContext(context); + var rootTask = createTask(request, model, rootContext, abortSet); + pingedTasks.push(rootTask); + return request; +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + + { + var store = requestStorage.getStore(); + if (store) return store; + } + + return null; +} + +function createRootContext(reqContext) { + return importServerContexts(reqContext); +} + +var POP = {}; + +function serializeThenable(request, thenable) { + request.pendingChunks++; + var newTask = createTask(request, null, getActiveContext(), request.abortableTasks); + + switch (thenable.status) { + case 'fulfilled': + { + // We have the resolved value, we can go ahead and schedule it for serialization. + newTask.model = thenable.value; + pingTask(request, newTask); + return newTask.id; + } + + case 'rejected': + { + var x = thenable.reason; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt.message, + stack = _getErrorMessageAndSt.stack; + + emitErrorChunkDev(request, newTask.id, digest, message, stack); + } + + return newTask.id; + } + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + thenable.then(function (value) { + newTask.model = value; + pingTask(request, newTask); + }, function (reason) { + newTask.status = ERRORED$1; // TODO: We should ideally do this inside performWork so it's scheduled + + var digest = logRecoverableError(request, reason); + + { + var _getErrorMessageAndSt2 = getErrorMessageAndStackDev(reason), + _message = _getErrorMessageAndSt2.message, + _stack = _getErrorMessageAndSt2.stack; + + emitErrorChunkDev(request, newTask.id, digest, _message, _stack); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + }); + return newTask.id; +} + +function emitHint(request, code, model) { + emitHintChunk(request, code, model); + enqueueFlush(request); +} +function getHints(request) { + return request.hints; +} +function getCache(request) { + return request.cache; +} + +function readThenable(thenable) { + if (thenable.status === 'fulfilled') { + return thenable.value; + } else if (thenable.status === 'rejected') { + throw thenable.reason; + } + + throw thenable; +} + +function createLazyWrapperAroundWakeable(wakeable) { + // This is a temporary fork of the `use` implementation until we accept + // promises everywhere. + var thenable = wakeable; + + switch (thenable.status) { + case 'fulfilled': + case 'rejected': + break; + + default: + { + if (typeof thenable.status === 'string') { + // Only instrument the thenable if the status if not defined. If + // it's defined, but an unknown value, assume it's been instrumented by + // some custom userspace implementation. We treat it as "pending". + break; + } + + var pendingThenable = thenable; + pendingThenable.status = 'pending'; + pendingThenable.then(function (fulfilledValue) { + if (thenable.status === 'pending') { + var fulfilledThenable = thenable; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = fulfilledValue; + } + }, function (error) { + if (thenable.status === 'pending') { + var rejectedThenable = thenable; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = error; + } + }); + break; + } + } + + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: thenable, + _init: readThenable + }; + return lazyType; +} + +function attemptResolveElement(request, type, key, ref, props, prevThenableState) { + if (ref !== null && ref !== undefined) { + // When the ref moves to the regular props object this will implicitly + // throw for functions. We could probably relax it to a DEV warning for other + // cases. + throw new Error('Refs cannot be used in Server Components, nor passed to Client Components.'); + } + + { + jsxPropsParents.set(props, type); + + if (typeof props.children === 'object' && props.children !== null) { + jsxChildrenParents.set(props.children, type); + } + } + + if (typeof type === 'function') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } // This is a server-side component. + + + prepareToUseHooksForComponent(prevThenableState); + var result = type(props); + + if (typeof result === 'object' && result !== null && typeof result.then === 'function') { + // When the return value is in children position we can resolve it immediately, + // to its value without a wrapper if it's synchronously available. + var thenable = result; + + if (thenable.status === 'fulfilled') { + return thenable.value; + } // TODO: Once we accept Promises as children on the client, we can just return + // the thenable here. + + + return createLazyWrapperAroundWakeable(result); + } + + return result; + } else if (typeof type === 'string') { + // This is a host element. E.g. HTML. + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (typeof type === 'symbol') { + if (type === REACT_FRAGMENT_TYPE) { + // For key-less fragments, we add a small optimization to avoid serializing + // it as a wrapper. + // TODO: If a key is specified, we should propagate its key to any children. + // Same as if a Server Component has a key. + return props.children; + } // This might be a built-in React component. We'll let the client decide. + // Any built-in works as long as its props are serializable. + + + return [REACT_ELEMENT_TYPE, type, key, props]; + } else if (type != null && typeof type === 'object') { + if (isClientReference(type)) { + // This is a reference to a Client Component. + return [REACT_ELEMENT_TYPE, type, key, props]; + } + + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + { + var payload = type._payload; + var init = type._init; + var wrappedType = init(payload); + return attemptResolveElement(request, wrappedType, key, ref, props, prevThenableState); + } + + case REACT_FORWARD_REF_TYPE: + { + var render = type.render; + prepareToUseHooksForComponent(prevThenableState); + return render(props, undefined); + } + + case REACT_MEMO_TYPE: + { + return attemptResolveElement(request, type.type, key, ref, props, prevThenableState); + } + + case REACT_PROVIDER_TYPE: + { + pushProvider(type._context, props.value); + + { + var extraKeys = Object.keys(props).filter(function (value) { + if (value === 'children' || value === 'value') { + return false; + } + + return true; + }); + + if (extraKeys.length !== 0) { + error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); + } + } + + return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. + { + value: props.value, + children: props.children, + __pop: POP + }]; + } + } + } + + throw new Error("Unsupported Server Component type: " + describeValueForErrorMessage(type)); +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + request.flushScheduled = request.destination !== null; + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createTask(request, model, context, abortSet) { + var id = request.nextChunkId++; + var task = { + id: id, + status: PENDING$1, + model: model, + context: context, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} + +function serializeByValueID(id) { + return '$' + id.toString(16); +} + +function serializeLazyID(id) { + return '$L' + id.toString(16); +} + +function serializePromiseID(id) { + return '$@' + id.toString(16); +} + +function serializeServerReferenceID(id) { + return '$F' + id.toString(16); +} + +function serializeSymbolReference(name) { + return '$S' + name; +} + +function serializeProviderReference(name) { + return '$P' + name; +} + +function serializeNumber(number) { + if (Number.isFinite(number)) { + if (number === 0 && 1 / number === -Infinity) { + return '$-0'; + } else { + return number; + } + } else { + if (number === Infinity) { + return '$Infinity'; + } else if (number === -Infinity) { + return '$-Infinity'; + } else { + return '$NaN'; + } + } +} + +function serializeUndefined() { + return '$undefined'; +} + +function serializeDateFromDateJSON(dateJSON) { + // JSON.stringify automatically calls Date.prototype.toJSON which calls toISOString. + // We need only tack on a $D prefix. + return '$D' + dateJSON; +} + +function serializeBigInt(n) { + return '$n' + n.toString(10); +} + +function serializeClientReference(request, parent, key, clientReference) { + var clientReferenceKey = getClientReferenceKey(clientReference); + var writtenClientReferences = request.writtenClientReferences; + var existingId = writtenClientReferences.get(clientReferenceKey); + + if (existingId !== undefined) { + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(existingId); + } + + return serializeByValueID(existingId); + } + + try { + var clientReferenceMetadata = resolveClientReferenceMetadata(request.bundlerConfig, clientReference); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata); + writtenClientReferences.set(clientReferenceKey, importId); + + if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { + // If we're encoding the "type" of an element, we can refer + // to that by a lazy reference instead of directly since React + // knows how to deal with lazy values. This lets us suspend + // on this component rather than its parent until the code has + // loaded. + return serializeLazyID(importId); + } + + return serializeByValueID(importId); + } catch (x) { + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt3 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt3.message, + stack = _getErrorMessageAndSt3.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeByValueID(errorId); + } +} + +function serializeServerReference(request, parent, key, serverReference) { + var writtenServerReferences = request.writtenServerReferences; + var existingId = writtenServerReferences.get(serverReference); + + if (existingId !== undefined) { + return serializeServerReferenceID(existingId); + } + + var bound = getServerReferenceBoundArguments(request.bundlerConfig, serverReference); + var serverReferenceMetadata = { + id: getServerReferenceId(request.bundlerConfig, serverReference), + bound: bound ? Promise.resolve(bound) : null + }; + request.pendingChunks++; + var metadataId = request.nextChunkId++; // We assume that this object doesn't suspend. + + var processedChunk = processModelChunk(request, metadataId, serverReferenceMetadata); + request.completedJSONChunks.push(processedChunk); + writtenServerReferences.set(serverReference, metadataId); + return serializeServerReferenceID(metadataId); +} + +function escapeStringValue(value) { + if (value[0] === '$') { + // We need to escape $ prefixed strings since we use those to encode + // references to IDs and as special symbol values. + return '$' + value; + } else { + return value; + } +} + +var insideContextProps = null; +var isInsideContextValue = false; +function resolveModelToJSON(request, parent, key, value) { + // Make sure that `parent[key]` wasn't JSONified before `value` was passed to us + { + // $FlowFixMe[incompatible-use] + var originalValue = parent[key]; + + if (typeof originalValue === 'object' && originalValue !== value && !(originalValue instanceof Date)) { + if (objectName(originalValue) !== 'Object') { + var jsxParentType = jsxChildrenParents.get(parent); + + if (typeof jsxParentType === 'string') { + error('%s objects cannot be rendered as text children. Try formatting it using toString().%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(originalValue), describeObjectForErrorMessage(parent, key)); + } + } else { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props.%s', describeObjectForErrorMessage(parent, key)); + } + } + } // Special Symbols + + + switch (value) { + case REACT_ELEMENT_TYPE: + return '$'; + } + + { + if (parent[0] === REACT_ELEMENT_TYPE && parent[1] && parent[1].$$typeof === REACT_PROVIDER_TYPE && key === '3') { + insideContextProps = value; + } else if (insideContextProps === parent && key === 'value') { + isInsideContextValue = true; + } else if (insideContextProps === parent && key === 'children') { + isInsideContextValue = false; + } + } // Resolve Server Components. + + + while (typeof value === 'object' && value !== null && (value.$$typeof === REACT_ELEMENT_TYPE || value.$$typeof === REACT_LAZY_TYPE)) { + { + if (isInsideContextValue) { + error('React elements are not allowed in ServerContext'); + } + } + + try { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + { + // TODO: Concatenate keys of parents onto children. + var element = value; // Attempt to render the Server Component. + + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, null); + break; + } + + case REACT_LAZY_TYPE: + { + var payload = value._payload; + var init = value._init; + value = init(payload); + break; + } + } + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended, we'll need to create a new task and resolve it later. + request.pendingChunks++; + var newTask = createTask(request, value, getActiveContext(), request.abortableTasks); + var ping = newTask.ping; + x.then(ping, ping); + newTask.thenableState = getThenableStateAfterSuspending(); + return serializeLazyID(newTask.id); + } else { + // Something errored. We'll still send everything we have up until this point. + // We'll replace this element with a lazy reference that throws on the client + // once it gets rendered. + request.pendingChunks++; + var errorId = request.nextChunkId++; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt4 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt4.message, + stack = _getErrorMessageAndSt4.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + return serializeLazyID(errorId); + } + } + } + + if (value === null) { + return null; + } + + if (typeof value === 'object') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); // $FlowFixMe[method-unbinding] + } else if (typeof value.then === 'function') { + // We assume that any object with a .then property is a "Thenable" type, + // or a Promise type. Either of which can be represented by a Promise. + var promiseId = serializeThenable(request, value); + return serializePromiseID(promiseId); + } else if (value.$$typeof === REACT_PROVIDER_TYPE) { + var providerKey = value._context._globalName; + var writtenProviders = request.writtenProviders; + var providerId = writtenProviders.get(key); + + if (providerId === undefined) { + request.pendingChunks++; + providerId = request.nextChunkId++; + writtenProviders.set(providerKey, providerId); + emitProviderChunk(request, providerId, providerKey); + } + + return serializeByValueID(providerId); + } else if (value === POP) { + popProvider(); + + { + insideContextProps = null; + isInsideContextValue = false; + } + + return undefined; + } + + if (!isArray(value)) { + var iteratorFn = getIteratorFn(value); + + if (iteratorFn) { + return Array.from(value); + } + } + + { + if (value !== null && !isArray(value)) { + // Verify that this is a simple plain object. + if (objectName(value) !== 'Object') { + error('Only plain objects can be passed to Client Components from Server Components. ' + '%s objects are not supported.%s', objectName(value), describeObjectForErrorMessage(parent, key)); + } else if (!isSimpleObject(value)) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Classes or other objects with methods are not supported.%s', describeObjectForErrorMessage(parent, key)); + } else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + + if (symbols.length > 0) { + error('Only plain objects can be passed to Client Components from Server Components. ' + 'Objects with symbol properties like %s are not supported.%s', symbols[0].description, describeObjectForErrorMessage(parent, key)); + } + } + } + } // $FlowFixMe[incompatible-return] + + + return value; + } + + if (typeof value === 'string') { + // TODO: Maybe too clever. If we support URL there's no similar trick. + if (value[value.length - 1] === 'Z') { + // Possibly a Date, whose toJSON automatically calls toISOString + // $FlowFixMe[incompatible-use] + var _originalValue = parent[key]; // $FlowFixMe[method-unbinding] + + if (_originalValue instanceof Date) { + return serializeDateFromDateJSON(value); + } + } + + return escapeStringValue(value); + } + + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return serializeNumber(value); + } + + if (typeof value === 'undefined') { + return serializeUndefined(); + } + + if (typeof value === 'function') { + if (isClientReference(value)) { + return serializeClientReference(request, parent, key, value); + } + + if (isServerReference(value)) { + return serializeServerReference(request, parent, key, value); + } + + if (/^on[A-Z]/.test(key)) { + throw new Error('Event handlers cannot be passed to Client Component props.' + describeObjectForErrorMessage(parent, key) + '\nIf you need interactivity, consider converting part of this to a Client Component.'); + } else { + throw new Error('Functions cannot be passed directly to Client Components ' + 'unless you explicitly expose it by marking it with "use server".' + describeObjectForErrorMessage(parent, key)); + } + } + + if (typeof value === 'symbol') { + var writtenSymbols = request.writtenSymbols; + var existingId = writtenSymbols.get(value); + + if (existingId !== undefined) { + return serializeByValueID(existingId); + } // $FlowFixMe[incompatible-type] `description` might be undefined + + + var name = value.description; + + if (Symbol.for(name) !== value) { + throw new Error('Only global symbols received from Symbol.for(...) can be passed to Client Components. ' + ("The symbol Symbol.for(" + // $FlowFixMe[incompatible-type] `description` might be undefined + value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, key)); + } + + request.pendingChunks++; + var symbolId = request.nextChunkId++; + emitSymbolChunk(request, symbolId, name); + writtenSymbols.set(value, symbolId); + return serializeByValueID(symbolId); + } + + if (typeof value === 'bigint') { + return serializeBigInt(value); + } + + throw new Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, key)); +} + +function logRecoverableError(request, error) { + var onError = request.onError; + var errorDigest = onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest || ''; +} + +function getErrorMessageAndStackDev(error) { + { + var message; + var stack = ''; + + try { + if (error instanceof Error) { + // eslint-disable-next-line react-internal/safe-string-coercion + message = String(error.message); // eslint-disable-next-line react-internal/safe-string-coercion + + stack = String(error.stack); + } else { + message = 'Error: ' + error; + } + } catch (x) { + message = 'An error occurred but serializing the error message failed.'; + } + + return { + message: message, + stack: stack + }; + } +} + +function fatalError(request, error) { + // This is called outside error handling code such as if an error happens in React internals. + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function emitErrorChunkProd(request, id, digest) { + var processedChunk = processErrorChunkProd(); + request.completedErrorChunks.push(processedChunk); +} + +function emitErrorChunkDev(request, id, digest, message, stack) { + var processedChunk = processErrorChunkDev(request, id, digest, message, stack); + request.completedErrorChunks.push(processedChunk); +} + +function emitImportChunk(request, id, clientReferenceMetadata) { + var processedChunk = processImportChunk(request, id, clientReferenceMetadata); + request.completedImportChunks.push(processedChunk); +} + +function emitHintChunk(request, code, model) { + var processedChunk = processHintChunk(request, request.nextChunkId++, code, model); + request.completedHintChunks.push(processedChunk); +} + +function emitSymbolChunk(request, id, name) { + var symbolReference = serializeSymbolReference(name); + var processedChunk = processReferenceChunk(request, id, symbolReference); + request.completedImportChunks.push(processedChunk); +} + +function emitProviderChunk(request, id, contextName) { + var contextReference = serializeProviderReference(contextName); + var processedChunk = processReferenceChunk(request, id, contextReference); + request.completedJSONChunks.push(processedChunk); +} + +function retryTask(request, task) { + if (task.status !== PENDING$1) { + // We completed this by other means before we had a chance to retry it. + return; + } + + switchContext(task.context); + + try { + var value = task.model; + + if (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var element = value; // When retrying a component, reuse the thenableState from the + // previous attempt. + + var prevThenableState = task.thenableState; // Attempt to render the Server Component. + // Doing this here lets us reuse this same task if the next component + // also suspends. + + task.model = value; + value = attemptResolveElement(request, element.type, element.key, element.ref, element.props, prevThenableState); // Successfully finished this component. We're going to keep rendering + // using the same task, but we reset its thenable state before continuing. + + task.thenableState = null; // Keep rendering and reuse the same task. This inner loop is separate + // from the render above because we don't need to reset the thenable state + // until the next time something suspends and retries. + + while (typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE) { + // TODO: Concatenate keys of parents onto children. + var nextElement = value; + task.model = value; + value = attemptResolveElement(request, nextElement.type, nextElement.key, nextElement.ref, nextElement.props, null); + } + } + + var processedChunk = processModelChunk(request, task.id, value); + request.completedJSONChunks.push(processedChunk); + request.abortableTasks.delete(task); + task.status = COMPLETED; + } catch (thrownValue) { + var x = thrownValue === SuspenseException ? // This is a special type of exception used for Suspense. For historical + // reasons, the rest of the Suspense implementation expects the thrown + // value to be a thenable, because before `use` existed that was the + // (unstable) API for suspending. This implementation detail can change + // later, once we deprecate the old API in favor of `use`. + getSuspendedThenable() : thrownValue; // $FlowFixMe[method-unbinding] + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + task.thenableState = getThenableStateAfterSuspending(); + return; + } else { + request.abortableTasks.delete(task); + task.status = ERRORED$1; + var digest = logRecoverableError(request, x); + + { + var _getErrorMessageAndSt5 = getErrorMessageAndStackDev(x), + message = _getErrorMessageAndSt5.message, + stack = _getErrorMessageAndSt5.stack; + + emitErrorChunkDev(request, task.id, digest, message, stack); + } + } + } +} + +function performWork(request) { + var prevDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest = request; + prepareToUseHooksForRequest(request); + + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + + for (var i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + ReactCurrentDispatcher.current = prevDispatcher; + resetHooksForRequest(); + currentRequest = prevRequest; + } +} + +function abortTask(task, request, errorId) { + task.status = ABORTED; // Instead of emitting an error per task.id, we emit a model that only + // has a single value referencing the error. + + var ref = serializeByValueID(errorId); + var processedChunk = processReferenceChunk(request, task.id, ref); + request.completedErrorChunks.push(processedChunk); +} + +function flushCompletedChunks(request, destination) { + beginWriting(); + + try { + // We emit module chunks first in the stream so that + // they can be preloaded as early as possible. + var importsChunks = request.completedImportChunks; + var i = 0; + + for (; i < importsChunks.length; i++) { + request.pendingChunks--; + var chunk = importsChunks[i]; + var keepWriting = writeChunkAndReturn(destination, chunk); + + if (!keepWriting) { + request.destination = null; + i++; + break; + } + } + + importsChunks.splice(0, i); // Next comes hints. + + var hintChunks = request.completedHintChunks; + i = 0; + + for (; i < hintChunks.length; i++) { + var _chunk = hintChunks[i]; + + var _keepWriting = writeChunkAndReturn(destination, _chunk); + + if (!_keepWriting) { + request.destination = null; + i++; + break; + } + } + + hintChunks.splice(0, i); // Next comes model data. + + var jsonChunks = request.completedJSONChunks; + i = 0; + + for (; i < jsonChunks.length; i++) { + request.pendingChunks--; + var _chunk2 = jsonChunks[i]; + + var _keepWriting2 = writeChunkAndReturn(destination, _chunk2); + + if (!_keepWriting2) { + request.destination = null; + i++; + break; + } + } + + jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay + // any error messages and prioritize display of other parts of + // the page. + + var errorChunks = request.completedErrorChunks; + i = 0; + + for (; i < errorChunks.length; i++) { + request.pendingChunks--; + var _chunk3 = errorChunks[i]; + + var _keepWriting3 = writeChunkAndReturn(destination, _chunk3); + + if (!_keepWriting3) { + request.destination = null; + i++; + break; + } + } + + errorChunks.splice(0, i); + } finally { + request.flushScheduled = false; + completeWriting(destination); + } + + flushBuffered(destination); + + if (request.pendingChunks === 0) { + // We're done. + close$1(destination); + } +} + +function startWork(request) { + request.flushScheduled = request.destination !== null; + + { + scheduleWork(function () { + return requestStorage.run(request, performWork, request); + }); + } +} + +function enqueueFlush(request) { + if (request.flushScheduled === false && // If there are pinged tasks we are going to flush anyway after work completes + request.pingedTasks.length === 0 && // If there is no destination there is nothing we can flush to. A flush will + // happen when we start flowing again + request.destination !== null) { + var destination = request.destination; + request.flushScheduled = true; + scheduleWork(function () { + return flushCompletedChunks(request, destination); + }); + } +} + +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedChunks(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} // This is called to early terminate a request. It creates an error at all pending tasks. + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + // We have tasks to abort. We'll emit one error row and then emit a reference + // to that row from every row that's still remaining. + var error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + var digest = logRecoverableError(request, error); + request.pendingChunks++; + var errorId = request.nextChunkId++; + + if (true) { + var _getErrorMessageAndSt6 = getErrorMessageAndStackDev(error), + message = _getErrorMessageAndSt6.message, + stack = _getErrorMessageAndSt6.stack; + + emitErrorChunkDev(request, errorId, digest, message, stack); + } + + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedChunks(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function importServerContexts(contexts) { + if (contexts) { + var prevContext = getActiveContext(); + switchContext(rootContextSnapshot); + + for (var i = 0; i < contexts.length; i++) { + var _contexts$i = contexts[i], + name = _contexts$i[0], + value = _contexts$i[1]; + var context = getOrCreateServerContext(name); + pushProvider(context, value); + } + + var importedContext = getActiveContext(); + switchContext(prevContext); + return importedContext; + } + + return rootContextSnapshot; +} + +// eslint-disable-next-line no-unused-vars +function resolveServerReference(bundlerConfig, id) { + var idx = id.lastIndexOf('#'); + var specifier = id.slice(0, idx); + var name = id.slice(idx + 1); + return { + specifier: specifier, + name: name + }; +} +var asyncModuleCache = new Map(); +function preloadModule(metadata) { + var existingPromise = asyncModuleCache.get(metadata.specifier); + + if (existingPromise) { + if (existingPromise.status === 'fulfilled') { + return null; + } + + return existingPromise; + } else { + // $FlowFixMe[unsupported-syntax] + var modulePromise = import(metadata.specifier); + modulePromise.then(function (value) { + var fulfilledThenable = modulePromise; + fulfilledThenable.status = 'fulfilled'; + fulfilledThenable.value = value; + }, function (reason) { + var rejectedThenable = modulePromise; + rejectedThenable.status = 'rejected'; + rejectedThenable.reason = reason; + }); + asyncModuleCache.set(metadata.specifier, modulePromise); + return modulePromise; + } +} +function requireModule(metadata) { + var moduleExports; // We assume that preloadModule has been called before, which + // should have added something to the module cache. + + var promise = asyncModuleCache.get(metadata.specifier); + + if (promise.status === 'fulfilled') { + moduleExports = promise.value; + } else { + throw promise.reason; + } + + if (metadata.name === '*') { + // This is a placeholder value that represents that the caller imported this + // as a CommonJS module as is. + return moduleExports; + } + + if (metadata.name === '') { + // This is a placeholder value that represents that the caller accessed the + // default property of this if it was an ESM interop module. + return moduleExports.default; + } + + return moduleExports[metadata.name]; +} + +// The server acts as a Client of itself when resolving Server References. +var PENDING = 'pending'; +var BLOCKED = 'blocked'; +var RESOLVED_MODEL = 'resolved_model'; +var INITIALIZED = 'fulfilled'; +var ERRORED = 'rejected'; // $FlowFixMe[missing-this-annot] + +function Chunk(status, value, reason, response) { + this.status = status; + this.value = value; + this.reason = reason; + this._response = response; +} // We subclass Promise.prototype so that we get other methods like .catch + + +Chunk.prototype = Object.create(Promise.prototype); // TODO: This doesn't return a new Promise chain unlike the real .then + +Chunk.prototype.then = function (resolve, reject) { + var chunk = this; // If we have resolved content, we try to initialize it first which + // might put us back into one of the other states. + + switch (chunk.status) { + case RESOLVED_MODEL: + initializeModelChunk(chunk); + break; + } // The status might have changed after initialization. + + + switch (chunk.status) { + case INITIALIZED: + resolve(chunk.value); + break; + + case PENDING: + case BLOCKED: + if (resolve) { + if (chunk.value === null) { + chunk.value = []; + } + + chunk.value.push(resolve); + } + + if (reject) { + if (chunk.reason === null) { + chunk.reason = []; + } + + chunk.reason.push(reject); + } + + break; + + default: + reject(chunk.reason); + break; + } +}; + +function getRoot(response) { + var chunk = getChunk(response, 0); + return chunk; +} + +function createPendingChunk(response) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(PENDING, null, null, response); +} + +function wakeChunk(listeners, value) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener(value); + } +} + +function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { + switch (chunk.status) { + case INITIALIZED: + wakeChunk(resolveListeners, chunk.value); + break; + + case PENDING: + case BLOCKED: + chunk.value = resolveListeners; + chunk.reason = rejectListeners; + break; + + case ERRORED: + if (rejectListeners) { + wakeChunk(rejectListeners, chunk.reason); + } + + break; + } +} + +function triggerErrorOnChunk(chunk, error) { + if (chunk.status !== PENDING && chunk.status !== BLOCKED) { + // We already resolved. We didn't expect to see this. + return; + } + + var listeners = chunk.reason; + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + + if (listeners !== null) { + wakeChunk(listeners, error); + } +} + +function createResolvedModelChunk(response, value) { + // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors + return new Chunk(RESOLVED_MODEL, value, null, response); +} + +function resolveModelChunk(chunk, value) { + if (chunk.status !== PENDING) { + // We already resolved. We didn't expect to see this. + return; + } + + var resolveListeners = chunk.value; + var rejectListeners = chunk.reason; + var resolvedChunk = chunk; + resolvedChunk.status = RESOLVED_MODEL; + resolvedChunk.value = value; + + if (resolveListeners !== null) { + // This is unfortunate that we're reading this eagerly if + // we already have listeners attached since they might no + // longer be rendered or might not be the highest pri. + initializeModelChunk(resolvedChunk); // The status might have changed after initialization. + + wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); + } +} + +function bindArgs(fn, args) { + return fn.bind.apply(fn, [null].concat(args)); +} + +function loadServerReference(response, id, bound, parentChunk, parentObject, key) { + var serverReference = resolveServerReference(response._bundlerConfig, id); // We expect most servers to not really need this because you'd just have all + // the relevant modules already loaded but it allows for lazy loading of code + // if needed. + + var preloadPromise = preloadModule(serverReference); + var promise; + + if (bound) { + promise = Promise.all([bound, preloadPromise]).then(function (_ref) { + var args = _ref[0]; + return bindArgs(requireModule(serverReference), args); + }); + } else { + if (preloadPromise) { + promise = Promise.resolve(preloadPromise).then(function () { + return requireModule(serverReference); + }); + } else { + // Synchronously available + return requireModule(serverReference); + } + } + + promise.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); // We need a placeholder value that will be replaced later. + + return null; +} + +var initializingChunk = null; +var initializingChunkBlockedModel = null; + +function initializeModelChunk(chunk) { + var prevChunk = initializingChunk; + var prevBlocked = initializingChunkBlockedModel; + initializingChunk = chunk; + initializingChunkBlockedModel = null; + + try { + var value = JSON.parse(chunk.value, chunk._response._fromJSON); + + if (initializingChunkBlockedModel !== null && initializingChunkBlockedModel.deps > 0) { + initializingChunkBlockedModel.value = value; // We discovered new dependencies on modules that are not yet resolved. + // We have to go the BLOCKED state until they're resolved. + + var blockedChunk = chunk; + blockedChunk.status = BLOCKED; + blockedChunk.value = null; + blockedChunk.reason = null; + } else { + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = value; + } + } catch (error) { + var erroredChunk = chunk; + erroredChunk.status = ERRORED; + erroredChunk.reason = error; + } finally { + initializingChunk = prevChunk; + initializingChunkBlockedModel = prevBlocked; + } +} // Report that any missing chunks in the model is now going to throw this +// error upon read. Also notify any pending promises. + + +function reportGlobalError(response, error) { + response._chunks.forEach(function (chunk) { + // If this chunk was already resolved or errored, it won't + // trigger an error but if it wasn't then we need to + // because we won't be getting any new data to resolve it. + if (chunk.status === PENDING) { + triggerErrorOnChunk(chunk, error); + } + }); +} + +function getChunk(response, id) { + var chunks = response._chunks; + var chunk = chunks.get(id); + + if (!chunk) { + var prefix = response._prefix; + var key = prefix + id; // Check if we have this field in the backing store already. + + var backingEntry = response._formData.get(key); + + if (backingEntry != null) { + // We assume that this is a string entry for now. + chunk = createResolvedModelChunk(response, backingEntry); + } else { + // We're still waiting on this entry to stream in. + chunk = createPendingChunk(response); + } + + chunks.set(id, chunk); + } + + return chunk; +} + +function createModelResolver(chunk, parentObject, key) { + var blocked; + + if (initializingChunkBlockedModel) { + blocked = initializingChunkBlockedModel; + blocked.deps++; + } else { + blocked = initializingChunkBlockedModel = { + deps: 1, + value: null + }; + } + + return function (value) { + parentObject[key] = value; + blocked.deps--; + + if (blocked.deps === 0) { + if (chunk.status !== BLOCKED) { + return; + } + + var resolveListeners = chunk.value; + var initializedChunk = chunk; + initializedChunk.status = INITIALIZED; + initializedChunk.value = blocked.value; + + if (resolveListeners !== null) { + wakeChunk(resolveListeners, blocked.value); + } + } + }; +} + +function createModelReject(chunk) { + return function (error) { + return triggerErrorOnChunk(chunk, error); + }; +} + +function parseModelString(response, parentObject, key, value) { + if (value[0] === '$') { + switch (value[1]) { + case '$': + { + // This was an escaped string value. + return value.slice(1); + } + + case '@': + { + // Promise + var id = parseInt(value.slice(2), 16); + var chunk = getChunk(response, id); + return chunk; + } + + case 'S': + { + // Symbol + return Symbol.for(value.slice(2)); + } + + case 'F': + { + // Server Reference + var _id = parseInt(value.slice(2), 16); + + var _chunk = getChunk(response, _id); + + if (_chunk.status === RESOLVED_MODEL) { + initializeModelChunk(_chunk); + } + + if (_chunk.status !== INITIALIZED) { + // We know that this is emitted earlier so otherwise it's an error. + throw _chunk.reason; + } // TODO: Just encode this in the reference inline instead of as a model. + + + var metaData = _chunk.value; + return loadServerReference(response, metaData.id, metaData.bound, initializingChunk, parentObject, key); + } + + case 'K': + { + // FormData + var stringId = value.slice(2); + var formPrefix = response._prefix + stringId + '_'; + var data = new FormData(); + var backingFormData = response._formData; // We assume that the reference to FormData always comes after each + // entry that it references so we can assume they all exist in the + // backing store already. + // $FlowFixMe[prop-missing] FormData has forEach on it. + + backingFormData.forEach(function (entry, entryKey) { + if (entryKey.startsWith(formPrefix)) { + data.append(entryKey.slice(formPrefix.length), entry); + } + }); + return data; + } + + case 'I': + { + // $Infinity + return Infinity; + } + + case '-': + { + // $-0 or $-Infinity + if (value === '$-0') { + return -0; + } else { + return -Infinity; + } + } + + case 'N': + { + // $NaN + return NaN; + } + + case 'u': + { + // matches "$undefined" + // Special encoding for `undefined` which can't be serialized as JSON otherwise. + return undefined; + } + + case 'D': + { + // Date + return new Date(Date.parse(value.slice(2))); + } + + case 'n': + { + // BigInt + return BigInt(value.slice(2)); + } + + default: + { + // We assume that anything else is a reference ID. + var _id2 = parseInt(value.slice(1), 16); + + var _chunk2 = getChunk(response, _id2); + + switch (_chunk2.status) { + case RESOLVED_MODEL: + initializeModelChunk(_chunk2); + break; + } // The status might have changed after initialization. + + + switch (_chunk2.status) { + case INITIALIZED: + return _chunk2.value; + + case PENDING: + case BLOCKED: + var parentChunk = initializingChunk; + + _chunk2.then(createModelResolver(parentChunk, parentObject, key), createModelReject(parentChunk)); + + return null; + + default: + throw _chunk2.reason; + } + } + } + } + + return value; +} + +function createResponse(bundlerConfig, formFieldPrefix) { + var backingFormData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new FormData(); + var chunks = new Map(); + var response = { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: backingFormData, + _chunks: chunks, + _fromJSON: function (key, value) { + if (typeof value === 'string') { + // We can't use .bind here because we need the "this" value. + return parseModelString(response, this, key, value); + } + + return value; + } + }; + return response; +} +function resolveField(response, key, value) { + // Add this field to the backing store. + response._formData.append(key, value); + + var prefix = response._prefix; + + if (key.startsWith(prefix)) { + var chunks = response._chunks; + var id = +key.slice(prefix.length); + var chunk = chunks.get(id); + + if (chunk) { + // We were waiting on this key so now we can resolve it. + resolveModelChunk(chunk, value); + } + } +} +function resolveFileInfo(response, key, filename, mime) { + return { + chunks: [], + filename: filename, + mime: mime + }; +} +function resolveFileChunk(response, handle, chunk) { + handle.chunks.push(chunk); +} +function resolveFileComplete(response, key, handle) { + // Add this file to the backing store. + // Node.js doesn't expose a global File constructor so we need to use + // the append() form that takes the file name as the third argument, + // to create a File object. + var blob = new Blob(handle.chunks, { + type: handle.mime + }); + + response._formData.append(key, blob, handle.filename); +} +function close(response) { + // In case there are any remaining unresolved chunks, they won't + // be resolved now. So we need to issue an error to those. + // Ideally we should be able to early bail out if we kept a + // ref count of pending chunks. + reportGlobalError(response, new Error('Connection closed.')); +} + +function createDrainHandler(destination, request) { + return function () { + return startFlowing(request, destination); + }; +} + +function renderToPipeableStream(model, webpackMap, options) { + var request = createRequest(model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined); + var hasStartedFlowing = false; + startWork(request); + return { + pipe: function (destination) { + if (hasStartedFlowing) { + throw new Error('React currently only supports piping to one writable stream.'); + } + + hasStartedFlowing = true; + startFlowing(request, destination); + destination.on('drain', createDrainHandler(destination, request)); + return destination; + }, + abort: function (reason) { + abort(request, reason); + } + }; +} + +function decodeReplyFromBusboy(busboyStream, webpackMap) { + var response = createResponse(webpackMap, ''); + var pendingFiles = 0; + var queuedFields = []; + busboyStream.on('field', function (name, value) { + if (pendingFiles > 0) { + // Because the 'end' event fires two microtasks after the next 'field' + // we would resolve files and fields out of order. To handle this properly + // we queue any fields we receive until the previous file is done. + queuedFields.push(name, value); + } else { + resolveField(response, name, value); + } + }); + busboyStream.on('file', function (name, value, _ref) { + var filename = _ref.filename, + encoding = _ref.encoding, + mimeType = _ref.mimeType; + + if (encoding.toLowerCase() === 'base64') { + throw new Error("React doesn't accept base64 encoded file uploads because we don't expect " + "form data passed from a browser to ever encode data that way. If that's " + 'the wrong assumption, we can easily fix it.'); + } + + pendingFiles++; + var file = resolveFileInfo(response, name, filename, mimeType); + value.on('data', function (chunk) { + resolveFileChunk(response, file, chunk); + }); + value.on('end', function () { + resolveFileComplete(response, name, file); + pendingFiles--; + + if (pendingFiles === 0) { + // Release any queued fields + for (var i = 0; i < queuedFields.length; i += 2) { + resolveField(response, queuedFields[i], queuedFields[i + 1]); + } + + queuedFields.length = 0; + } + }); + }); + busboyStream.on('finish', function () { + close(response); + }); + busboyStream.on('error', function (err) { + reportGlobalError(response, err); + }); + return getRoot(response); +} + +function decodeReply(body, webpackMap) { + if (typeof body === 'string') { + var form = new FormData(); + form.append('0', body); + body = form; + } + + var response = createResponse(webpackMap, '', body); + close(response); + return getRoot(response); +} + +exports.decodeReply = decodeReply; +exports.decodeReplyFromBusboy = decodeReplyFromBusboy; +exports.renderToPipeableStream = renderToPipeableStream; + })(); +} diff --git a/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js new file mode 100644 index 0000000000000..3b1b1d5a04b44 --- /dev/null +++ b/packages/next/src/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.unbundled.production.min.js @@ -0,0 +1,65 @@ +/** + * @license React + * react-server-dom-webpack-server.node.unbundled.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("async_hooks"),ba=require("util"),ca=require("react"),da=require("react-dom"),l=null,m=0,p=!0;function r(a,b){a=a.write(b);p=p&&a} +function t(a,b){if("string"===typeof b){if(0!==b.length)if(2048<3*b.length)0a.depth?Ba(b,a):Ca(b,a),G=a)}function Ea(a,b){var d=a._currentValue;a._currentValue=b;var c=G;return G=a={parent:c,depth:null===c?0:c.depth+1,context:a,parentValue:d,value:b}}var Fa=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); +function Ga(){}function Ha(a,b,d){d=a[d];void 0===d?a.push(b):d!==b&&(b.then(Ga,Ga),b=d);switch(b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;default:if("string"!==typeof b.status)switch(a=b,a.status="pending",a.then(function(c){if("pending"===b.status){var e=b;e.status="fulfilled";e.value=c}},function(c){if("pending"===b.status){var e=b;e.status="rejected";e.reason=c}}),b.status){case "fulfilled":return b.value;case "rejected":throw b.reason;}I=b;throw Fa;}}var I=null; +function Ia(){if(null===I)throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue.");var a=I;I=null;return a}var J=null,K=0,L=null;function Ja(){var a=L;L=null;return a}function Ka(a){return a._currentValue} +var Oa={useMemo:function(a){return a()},useCallback:function(a){return a},useDebugValue:function(){},useDeferredValue:M,useTransition:M,readContext:Ka,useContext:Ka,useReducer:M,useRef:M,useState:M,useInsertionEffect:M,useLayoutEffect:M,useImperativeHandle:M,useEffect:M,useId:La,useMutableSource:M,useSyncExternalStore:M,useCacheRefresh:function(){return Ma},useMemoCache:function(a){for(var b=Array(a),d=0;d=a.length?a:a.slice(0,10)+"...");case "object":if(Sa(a))return"[...]";a=Ta(a);return"Object"===a?"{...}":a;case "function":return"function";default:return String(a)}} +function N(a){if("string"===typeof a)return a;switch(a){case ta:return"Suspense";case ua:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case sa:return N(a.render);case va:return N(a.type);case F:var b=a._payload;a=a._init;try{return N(a(b))}catch(d){}}return""} +function O(a,b){var d=Ta(a);if("Object"!==d&&"Array"!==d)return d;d=-1;var c=0;if(Sa(a)){var e="[";for(var f=0;fg.length&&40>e.length+g.length?e+g:e+"..."}e+="]"}else if(a.$$typeof===E)e="<"+N(a.type)+"/>";else{e="{";f=Object.keys(a);for(g=0;gh.length&&40>e.length+h.length?e+h:e+"..."}e+="}"}return void 0===b?e:-1=0.10.0" - }, - "peerDependencies": { - "react": "18.3.0-next-6eadbe0c4-20230425", - "react-dom": "18.3.0-next-6eadbe0c4-20230425", - "webpack": "^5.59.0" - }, "dependencies": { "acorn-loose": "^8.3.0", "neo-async": "^2.6.1", "loose-envify": "^1.1.0" }, - "browserify": { - "transform": [ - "loose-envify" - ] + "peerDependencies": { + "react": "18.3.0-next-6eadbe0c4-20230425", + "react-dom": "18.3.0-next-6eadbe0c4-20230425", + "webpack": "^5.59.0" } } \ No newline at end of file diff --git a/packages/next/src/lib/metadata/metadata.tsx b/packages/next/src/lib/metadata/metadata.tsx index 4ab5c1c61fc5c..ff0ea311e3ea9 100644 --- a/packages/next/src/lib/metadata/metadata.tsx +++ b/packages/next/src/lib/metadata/metadata.tsx @@ -1,3 +1,6 @@ +import type { GetDynamicParamFromSegment } from '../../server/app-render/app-render' +import type { LoaderTree } from '../../server/lib/app-dir-module' + import React from 'react' import { AppleWebAppMeta, @@ -14,8 +17,6 @@ import { } from './generate/opengraph' import { IconsMetadata } from './generate/icons' import { accumulateMetadata, resolveMetadata } from './resolve-metadata' -import { LoaderTree } from '../../server/lib/app-dir-module' -import type { GetDynamicParamFromSegment } from '../../server/app-render/app-render' // Generate the actual React elements from the resolved metadata. export async function MetadataTree({ diff --git a/packages/next/src/server/app-render/action-handler.ts b/packages/next/src/server/app-render/action-handler.ts index c057207c33f65..8dd2e053d3bb0 100644 --- a/packages/next/src/server/app-render/action-handler.ts +++ b/packages/next/src/server/app-render/action-handler.ts @@ -108,7 +108,7 @@ export async function handleAction({ const { decodeReply, decodeReplyFromBusboy, - } = require('next/dist/compiled/react-server-dom-webpack/server.node') + } = require(`react-server-dom-webpack/server.node`) if (isMultipartAction) { const busboy = require('busboy') diff --git a/packages/next/src/server/app-render/app-render.tsx b/packages/next/src/server/app-render/app-render.tsx index d1449bb1b6cf9..ea2a609a7d18f 100644 --- a/packages/next/src/server/app-render/app-render.tsx +++ b/packages/next/src/server/app-render/app-render.tsx @@ -13,10 +13,11 @@ import type { import type { StaticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage' import type { StaticGenerationBailout } from '../../client/components/static-generation-bailout' import type { RequestAsyncStorage } from '../../client/components/request-async-storage' -// Import builtin react directly to avoid require cache conflicts -import React from 'next/dist/compiled/react' -import ReactDOMServer from 'next/dist/compiled/react-dom/server.edge' + +import React from 'react' +import ReactDOMServer from 'react-dom/server.edge' import { NotFound as DefaultNotFound } from '../../client/components/error' +import { createServerComponentRenderer } from './create-server-components-renderer' import { ParsedUrlQuery } from 'querystring' import { NextParsedUrlQuery } from '../request-meta' @@ -26,14 +27,13 @@ import { createBufferedTransformStream, continueFromInitialStream, streamToBufferedResult, -} from '../node-web-streams-helper' +} from '../stream-utils/node-web-streams-helper' import { canSegmentBeOverridden, matchSegment, } from '../../client/components/match-segments' import { ServerInsertedHTMLContext } from '../../shared/lib/server-inserted-html' import { stripInternalQueries } from '../internal-utils' -import { HeadManagerContext } from '../../shared/lib/head-manager-context' import { NEXT_ROUTER_PREFETCH, NEXT_ROUTER_STATE_TREE, @@ -56,7 +56,6 @@ import { interopDefault } from './interop-default' import { preloadComponent } from './preload-component' import { FlightRenderResult } from './flight-render-result' import { createErrorHandler } from './create-error-handler' -import { createServerComponentRenderer } from './create-server-components-renderer' import { getShortDynamicParamType } from './get-short-dynamic-param-type' import { getSegmentParam } from './get-segment-param' import { getCssInlinedLinkTags } from './get-css-inlined-link-tags' @@ -1332,10 +1331,11 @@ export async function renderToHTMLOrFlight( nonce ) + const { HeadManagerContext } = + require('../../shared/lib/head-manager-context') as typeof import('../../shared/lib/head-manager-context') const serverInsertedHTMLCallbacks: Set<() => React.ReactNode> = new Set() function InsertedHTML({ children }: { children: JSX.Element }) { // Reset addInsertedHtmlCallback on each render - serverInsertedHTMLCallbacks.clear() const addInsertedHtml = React.useCallback( (handler: () => React.ReactNode) => { serverInsertedHTMLCallbacks.add(handler) @@ -1422,27 +1422,30 @@ export async function renderToHTMLOrFlight( } } - const flushed = renderToString( - <> - {Array.from(serverInsertedHTMLCallbacks).map((callback) => - callback() - )} - {polyfillsFlushed - ? null - : polyfills?.map((polyfill) => { - return ( -