diff --git a/docs/api-reference/next/legacy/image.md b/docs/api-reference/next/legacy/image.md index c8493622ec8a..4f9919160d2b 100644 --- a/docs/api-reference/next/legacy/image.md +++ b/docs/api-reference/next/legacy/image.md @@ -89,18 +89,18 @@ The layout behavior of the image as the viewport changes size. | `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | yes | | `fill` | Grow in both X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | yes | -- [Demo the `intrinsic` layout (default)](https://image-component.nextjs.gallery/layout-intrinsic) +- [Demo the `intrinsic` layout (default)](https://image-legacy-component.nextjs.gallery/layout-intrinsic) - When `intrinsic`, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports. -- [Demo the `fixed` layout](https://image-component.nextjs.gallery/layout-fixed) +- [Demo the `fixed` layout](https://image-legacy-component.nextjs.gallery/layout-fixed) - When `fixed`, the image dimensions will not change as the viewport changes (no responsiveness) similar to the native `img` element. -- [Demo the `responsive` layout](https://image-component.nextjs.gallery/layout-responsive) +- [Demo the `responsive` layout](https://image-legacy-component.nextjs.gallery/layout-responsive) - When `responsive`, the image will scale the dimensions down for smaller viewports and scale up for larger viewports. - Ensure the parent element uses `display: block` in their stylesheet. -- [Demo the `fill` layout](https://image-component.nextjs.gallery/layout-fill) +- [Demo the `fill` layout](https://image-legacy-component.nextjs.gallery/layout-fill) - When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative. - This is usually paired with the [`objectFit`](#objectFit) property. - Ensure the parent element has `position: relative` in their stylesheet. -- [Demo background image](https://image-component.nextjs.gallery/background) +- [Demo background image](https://image-legacy-component.nextjs.gallery/background) ### loader @@ -193,9 +193,9 @@ When `empty`, there will be no placeholder while the image is loading, only empt Try it out: -- [Demo the `blur` placeholder](https://image-component.nextjs.gallery/placeholder) -- [Demo the shimmer effect with `blurDataURL` prop](https://image-component.nextjs.gallery/shimmer) -- [Demo the color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color) +- [Demo the `blur` placeholder](https://image-legacy-component.nextjs.gallery/placeholder) +- [Demo the shimmer effect with `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/shimmer) +- [Demo the color effect with `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/color) ## Advanced Props @@ -258,9 +258,9 @@ less) is recommended. Including larger images as placeholders may harm your appl Try it out: -- [Demo the default `blurDataURL` prop](https://image-component.nextjs.gallery/placeholder) -- [Demo the shimmer effect with `blurDataURL` prop](https://image-component.nextjs.gallery/shimmer) -- [Demo the color effect with `blurDataURL` prop](https://image-component.nextjs.gallery/color) +- [Demo the default `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/placeholder) +- [Demo the shimmer effect with `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/shimmer) +- [Demo the color effect with `blurDataURL` prop](https://image-legacy-component.nextjs.gallery/color) You can also [generate a solid color Data URL](https://png-pixel.com) to match the image. diff --git a/docs/basic-features/image-optimization.md b/docs/basic-features/image-optimization.md index 6264cb647226..d68189b83007 100644 --- a/docs/basic-features/image-optimization.md +++ b/docs/basic-features/image-optimization.md @@ -193,7 +193,7 @@ This is the default for `
` elements but should be specified otherwise. ### Styling Examples -For examples of the Image component used with the various styles, see the [Image component example app](https://image-component.nextjs.gallery). +For examples of the Image component used with the various styles, see the [Image Component Demo](https://image-component.nextjs.gallery). ## Configuration diff --git a/docs/basic-features/supported-browsers-features.md b/docs/basic-features/supported-browsers-features.md index 6a0b94881833..8631fd8ec747 100644 --- a/docs/basic-features/supported-browsers-features.md +++ b/docs/basic-features/supported-browsers-features.md @@ -4,7 +4,17 @@ description: Browser support and which JavaScript features are supported by Next # Supported Browsers and Features -Next.js supports **IE11 and all modern browsers** (Edge, Firefox, Chrome, Safari, Opera, et al) with no required configuration. +Next.js supports **modern browsers** with zero configuration. + +- Chrome 64+ +- Edge 79+ +- Firefox 67+ +- Opera 51+ +- Safari 12+ + +## Browserslist + +If you would like to target specific browsers or features, Next.js supports [Browserslist](https://browsersl.ist) configuration. ## Polyfills diff --git a/docs/upgrading.md b/docs/upgrading.md index e397ed623bfa..f26370f29ed4 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -6,6 +6,8 @@ description: Learn how to upgrade Next.js. ## Upgrading from 12 to 13 +The [Supported Browsers](/docs/basic-features/supported-browsers-features.md) have been changed to drop Internet Explorer and target modern browsers. + The minimum Node.js version has been bumped from 12.22.0 to 14.0.0, since 12.x has reached end-of-life. The `swcMinify` configuration property was changed from `false` to `true`. See [Next.js Compiler](/docs/advanced-features/compiler.md) for more info. @@ -15,7 +17,7 @@ A [codemod is available](/docs/advanced-features/codemods.md#next-image-to-legac The `next/link` child can no longer be ``. Add the `legacyBehavior` prop to use the legacy behavior or remove the `` to upgrade. A [codemod is available](/docs/advanced-features/codemods.md#new-link) to automatically upgrade your code. -The `target` configuration option has been removed and superseded by [Output File Tracing](https://nextjs.org/docs/advanced-features/output-file-tracing). +The `target` configuration property has been removed and superseded by [Output File Tracing](https://nextjs.org/docs/advanced-features/output-file-tracing). ## Upgrading to 12.2 diff --git a/examples/image-component/README.md b/examples/image-component/README.md index d56babeeaaa8..f56fc5671d6b 100644 --- a/examples/image-component/README.md +++ b/examples/image-component/README.md @@ -6,7 +6,7 @@ The index page ([`pages/index.js`](pages/index.js)) has a couple images, one int ## Live demo -[https://image-component.nextjs.gallery/](https://image-component.nextjs.gallery/) +[https://image-component.nextjs.gallery](https://image-component.nextjs.gallery) ## Deploy your own diff --git a/examples/image-legacy-component/README.md b/examples/image-legacy-component/README.md index 4aea7c6be0f9..84d5c3561cb0 100644 --- a/examples/image-legacy-component/README.md +++ b/examples/image-legacy-component/README.md @@ -1,29 +1,29 @@ -# Image Component Example +# Legacy Image Component Example -This example shows how to use the [Image Component in Next.js](https://nextjs.org/docs/api-reference/next/image) serve optimized, responsive images. +This example shows how to use the [Legacy Image Component in Next.js](https://nextjs.org/docs/api-reference/next/legacy/image) serve optimized, responsive images. The index page ([`pages/index.js`](pages/index.js)) has a couple images, one internal image and one external image. In [`next.config.js`](next.config.js), the `domains` property is used to enable external images. The other pages demonstrate the different layouts. Run or deploy the app to see how it works! ## Live demo -[https://image-component.nextjs.gallery/](https://image-component.nextjs.gallery/) +[https://image-legacy-component.nextjs.gallery](https://image-legacy-component.nextjs.gallery) ## Deploy your own Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/image-legacy-component) -[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/image-component&project-name=image-component&repository-name=image-legacy-component) +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/image-legacy-component&project-name=image-legacy-component&repository-name=image-legacy-component) ## How to use Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example: ```bash -npx create-next-app --example image-component image-app +npx create-next-app --example image-legacy-component image-app # or -yarn create next-app --example image-component image-app +yarn create next-app --example image-legacy-component image-app # or -pnpm create next-app --example image-component image-app +pnpm create next-app --example image-legacy-component image-app ``` Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)). diff --git a/examples/with-stripe-typescript/components/Cart.tsx b/examples/with-stripe-typescript/components/Cart.tsx index 2aa5893d127b..ca4d01a08d2c 100644 --- a/examples/with-stripe-typescript/components/Cart.tsx +++ b/examples/with-stripe-typescript/components/Cart.tsx @@ -1,5 +1,5 @@ import React, { ReactNode } from 'react' -import { CartProvider } from 'use-shopping-cart/react' +import { CartProvider } from 'use-shopping-cart' import * as config from '../config' const Cart = ({ children }: { children: ReactNode }) => ( diff --git a/examples/with-stripe-typescript/components/CartSummary.tsx b/examples/with-stripe-typescript/components/CartSummary.tsx index e7055e8c0c4b..a1262ae77b3f 100644 --- a/examples/with-stripe-typescript/components/CartSummary.tsx +++ b/examples/with-stripe-typescript/components/CartSummary.tsx @@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react' import StripeTestCards from '../components/StripeTestCards' -import { useShoppingCart } from 'use-shopping-cart/react' +import { useShoppingCart } from 'use-shopping-cart' import { fetchPostJSON } from '../utils/api-helpers' const CartSummary = () => { diff --git a/examples/with-stripe-typescript/components/ClearCart.tsx b/examples/with-stripe-typescript/components/ClearCart.tsx index 49aaf8b7ae39..daf923cf3523 100644 --- a/examples/with-stripe-typescript/components/ClearCart.tsx +++ b/examples/with-stripe-typescript/components/ClearCart.tsx @@ -1,5 +1,5 @@ import { useEffect } from 'react' -import { useShoppingCart } from 'use-shopping-cart/react' +import { useShoppingCart } from 'use-shopping-cart' export default function ClearCart() { const { clearCart } = useShoppingCart() diff --git a/examples/with-stripe-typescript/components/Products.tsx b/examples/with-stripe-typescript/components/Products.tsx index db8560ecda48..20763e6863ef 100644 --- a/examples/with-stripe-typescript/components/Products.tsx +++ b/examples/with-stripe-typescript/components/Products.tsx @@ -1,6 +1,6 @@ import products from '../data/products' import { formatCurrencyString } from 'use-shopping-cart' -import { useShoppingCart } from 'use-shopping-cart/react' +import { useShoppingCart } from 'use-shopping-cart' const Products = () => { const { addItem, removeItem } = useShoppingCart() diff --git a/examples/with-stripe-typescript/package.json b/examples/with-stripe-typescript/package.json index 38da16d8ff6f..f1c9d7fd57fc 100644 --- a/examples/with-stripe-typescript/package.json +++ b/examples/with-stripe-typescript/package.json @@ -6,22 +6,23 @@ "start": "next start" }, "dependencies": { - "@stripe/react-stripe-js": "1.7.0", - "@stripe/stripe-js": "1.22.0", - "micro": "^9.3.4", + "@stripe/react-stripe-js": "1.13.0", + "@stripe/stripe-js": "1.42.0", + "micro": "^9.4.1", "micro-cors": "^0.1.1", "next": "latest", - "react": "^17.0.2", - "react-dom": "^17.0.2", - "stripe": "8.200.0", - "swr": "^0.1.16", - "use-shopping-cart": "3.0.5" + "react": "^18.2.0", + "react-dom": "^18.2.0", + "stripe": "10.14.0", + "swr": "^1.3.0", + "use-shopping-cart": "3.1.2", + "redux": "4.2.0" }, "devDependencies": { - "@types/micro": "^7.3.3", - "@types/micro-cors": "^0.1.0", - "@types/node": "^13.1.2", - "@types/react": "^16.9.17", - "typescript": "4.5.5" + "@types/micro": "^7.3.7", + "@types/micro-cors": "^0.1.2", + "@types/node": "^18.11.2", + "@types/react": "^18.0.21", + "typescript": "4.8.4" } } diff --git a/lerna.json b/lerna.json index e66ad7a7e63e..8311b6f749e4 100644 --- a/lerna.json +++ b/lerna.json @@ -16,5 +16,5 @@ "registry": "https://registry.npmjs.org/" } }, - "version": "12.3.2-canary.30" + "version": "12.3.2-canary.32" } diff --git a/package.json b/package.json index 6af2281f0e9b..ee7fcf8a5507 100644 --- a/package.json +++ b/package.json @@ -40,11 +40,9 @@ "next-with-deps": "./scripts/next-with-deps.sh", "next": "node --trace-deprecation --enable-source-maps packages/next/dist/bin/next", "next-react-17": "__NEXT_REACT_CHANNEL=17 node --trace-deprecation --enable-source-maps -r ./test/lib/react-channel-require-hook.js packages/next/dist/bin/next", - "next-react-exp": "__NEXT_REACT_CHANNEL=exp node --trace-deprecation --enable-source-maps -r ./test/lib/react-channel-require-hook.js packages/next/dist/bin/next", "next-no-sourcemaps": "node --trace-deprecation packages/next/dist/bin/next", "clean-trace-jaeger": "rm -rf test/integration/basic/.next && TRACE_TARGET=JAEGER node --trace-deprecation --enable-source-maps packages/next/dist/bin/next build test/integration/basic", "debug": "node --inspect packages/next/dist/bin/next", - "debug-react-exp": "__NEXT_REACT_CHANNEL=exp node --inspect --trace-deprecation --enable-source-maps -r ./test/lib/react-channel-require-hook.js packages/next/dist/bin/next", "postinstall": "git config feature.manyFiles true && node scripts/install-native.mjs", "version": "pnpm install && git add pnpm-lock.yaml", "prepare": "husky install" @@ -183,8 +181,6 @@ "react-17": "npm:react@17.0.2", "react-dom": "18.2.0", "react-dom-17": "npm:react-dom@17.0.2", - "react-dom-exp": "npm:react-dom@0.0.0-experimental-a8c16a004-20221012", - "react-exp": "npm:react@0.0.0-experimental-a8c16a004-20221012", "react-ssr-prepass": "1.0.8", "react-virtualized": "9.22.3", "relay-compiler": "13.0.2", diff --git a/packages/create-next-app/package.json b/packages/create-next-app/package.json index d9bac0fb8595..7b405c0c7617 100644 --- a/packages/create-next-app/package.json +++ b/packages/create-next-app/package.json @@ -1,6 +1,6 @@ { "name": "create-next-app", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "keywords": [ "react", "next", diff --git a/packages/eslint-config-next/package.json b/packages/eslint-config-next/package.json index 272cf7cf0d2c..5ecbff7e3719 100644 --- a/packages/eslint-config-next/package.json +++ b/packages/eslint-config-next/package.json @@ -1,6 +1,6 @@ { "name": "eslint-config-next", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "description": "ESLint configuration used by NextJS.", "main": "index.js", "license": "MIT", @@ -9,7 +9,7 @@ "directory": "packages/eslint-config-next" }, "dependencies": { - "@next/eslint-plugin-next": "12.3.2-canary.30", + "@next/eslint-plugin-next": "12.3.2-canary.32", "@rushstack/eslint-patch": "^1.1.3", "@typescript-eslint/parser": "^5.21.0", "eslint-import-resolver-node": "^0.3.6", diff --git a/packages/eslint-plugin-next/package.json b/packages/eslint-plugin-next/package.json index 60b35fd0b2ae..95b827b7391d 100644 --- a/packages/eslint-plugin-next/package.json +++ b/packages/eslint-plugin-next/package.json @@ -1,6 +1,6 @@ { "name": "@next/eslint-plugin-next", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "description": "ESLint plugin for NextJS.", "main": "dist/index.js", "license": "MIT", diff --git a/packages/font/package.json b/packages/font/package.json index 1493bc201544..89248b77f622 100644 --- a/packages/font/package.json +++ b/packages/font/package.json @@ -1,6 +1,6 @@ { "name": "@next/font", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "repository": { "url": "vercel/next.js", "directory": "packages/font" diff --git a/packages/next-bundle-analyzer/package.json b/packages/next-bundle-analyzer/package.json index c3be13759210..35778bd72514 100644 --- a/packages/next-bundle-analyzer/package.json +++ b/packages/next-bundle-analyzer/package.json @@ -1,6 +1,6 @@ { "name": "@next/bundle-analyzer", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "main": "index.js", "types": "index.d.ts", "license": "MIT", diff --git a/packages/next-codemod/package.json b/packages/next-codemod/package.json index 114d694b46d0..9441b3825c5c 100644 --- a/packages/next-codemod/package.json +++ b/packages/next-codemod/package.json @@ -1,6 +1,6 @@ { "name": "@next/codemod", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "license": "MIT", "dependencies": { "chalk": "4.1.0", diff --git a/packages/next-env/package.json b/packages/next-env/package.json index 2602ad2ba4b1..3843a7c2698c 100644 --- a/packages/next-env/package.json +++ b/packages/next-env/package.json @@ -1,6 +1,6 @@ { "name": "@next/env", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "keywords": [ "react", "next", diff --git a/packages/next-mdx/package.json b/packages/next-mdx/package.json index a1b74f67dbb1..495644adac79 100644 --- a/packages/next-mdx/package.json +++ b/packages/next-mdx/package.json @@ -1,6 +1,6 @@ { "name": "@next/mdx", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "main": "index.js", "license": "MIT", "repository": { diff --git a/packages/next-plugin-storybook/package.json b/packages/next-plugin-storybook/package.json index 7fd43f1e3790..571b3ce8b817 100644 --- a/packages/next-plugin-storybook/package.json +++ b/packages/next-plugin-storybook/package.json @@ -1,6 +1,6 @@ { "name": "@next/plugin-storybook", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "repository": { "url": "vercel/next.js", "directory": "packages/next-plugin-storybook" diff --git a/packages/next-polyfill-module/package.json b/packages/next-polyfill-module/package.json index 39cabddb8cb4..821b22539cb7 100644 --- a/packages/next-polyfill-module/package.json +++ b/packages/next-polyfill-module/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-module", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)", "main": "dist/polyfill-module.js", "license": "MIT", diff --git a/packages/next-polyfill-nomodule/package.json b/packages/next-polyfill-nomodule/package.json index 5cc379705ebd..d2005e55619f 100644 --- a/packages/next-polyfill-nomodule/package.json +++ b/packages/next-polyfill-nomodule/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-nomodule", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "description": "A polyfill for non-dead, nomodule browsers.", "main": "dist/polyfill-nomodule.js", "license": "MIT", diff --git a/packages/next-swc/Cargo.lock b/packages/next-swc/Cargo.lock index 519ee8f2ffc3..e3c2431017e2 100644 --- a/packages/next-swc/Cargo.lock +++ b/packages/next-swc/Cargo.lock @@ -165,9 +165,9 @@ dependencies = [ [[package]] name = "binding_macros" -version = "0.20.33" +version = "0.20.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dd93110b899b44eaf4a68f6c1f0e2f9bdb7f6ce8b3c5a33f90b6e0240617629" +checksum = "7f0239cba0f7a458f594af9d3dd3b1797fae99ff2082a62932981811491f62b2" dependencies = [ "anyhow", "console_error_panic_hook", @@ -2956,9 +2956,9 @@ dependencies = [ [[package]] name = "swc" -version = "0.232.33" +version = "0.232.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb404480ed114e7fe5450ecbed1afe3de228979be6f1b091f089f67062f7066" +checksum = "d35a875a7bcaaaefccd067fdd924c588fbeac786921248d035153436539c52a4" dependencies = [ "ahash", "anyhow", @@ -3007,9 +3007,9 @@ dependencies = [ [[package]] name = "swc_atoms" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5ffecde9d1a937a61b4799478d598121b539eb7da6127c16af86a044017e1e5" +checksum = "a6692dd18b783106f3cafc2721341c1e59a41d153e06d8d7814c78ad92a6ac11" dependencies = [ "once_cell", "rkyv", @@ -3022,9 +3022,9 @@ dependencies = [ [[package]] name = "swc_bundler" -version = "0.192.30" +version = "0.192.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6afce6cc026a9c5f89c9506c43ec77c0675b648e5b466d8bd126a292ff8c3b7" +checksum = "bc9093c6983a1701937bd4f936d6c2fa2155f481caf435e4312fc3dcfaa8dd23" dependencies = [ "ahash", "anyhow", @@ -3070,9 +3070,9 @@ dependencies = [ [[package]] name = "swc_common" -version = "0.29.8" +version = "0.29.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "251762fb5b797ece63903a9a6625af90f3c49b41d8c6ed40d0362a06de749d4f" +checksum = "6d1cc2ff3b5ebf6d91a43b713a8f30dac2e638ea1189658d9cba91e8ba70633a" dependencies = [ "ahash", "anyhow", @@ -3128,9 +3128,9 @@ dependencies = [ [[package]] name = "swc_core" -version = "0.38.20" +version = "0.39.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c21dbd294a2d9a73e841081648a0204ca66dcbbdb35156c23e13467ca232b4c" +checksum = "a8bb50afd30d553b9364d4509b2d85cb42bd78640cf269c388953b8b8a81960c" dependencies = [ "binding_macros", "swc", @@ -3167,9 +3167,9 @@ dependencies = [ [[package]] name = "swc_css_ast" -version = "0.122.1" +version = "0.123.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8694c9a93799f46338c3e973a2247088e8150a9fe1ae0bf329d520ea3f85f56f" +checksum = "6fac7af2bd6f6123ffea646a416efa49e557508de79afd4f574b3818d5956f2a" dependencies = [ "is-macro", "serde", @@ -3180,9 +3180,9 @@ dependencies = [ [[package]] name = "swc_css_codegen" -version = "0.132.2" +version = "0.133.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b33eedb2bfc2713aba7a15822dc94b2b958e3a5dbacabb665e07becaa8d2162b" +checksum = "75f46885b4c24fae057a4fd322e1c782b823f0e764c014c2bc6be5caae56c15f" dependencies = [ "auto_impl", "bitflags", @@ -3210,9 +3210,9 @@ dependencies = [ [[package]] name = "swc_css_parser" -version = "0.131.2" +version = "0.132.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d417cc14ddf6c4839c7942555cc52b3d2fbc2cb8343bf88a46d89603687bb8" +checksum = "e525a746ae3232aac75de1394aaedd4f7cdee06f15fa4915959b7b2acc66f7a5" dependencies = [ "bitflags", "lexical", @@ -3224,9 +3224,9 @@ dependencies = [ [[package]] name = "swc_css_prefixer" -version = "0.133.2" +version = "0.134.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58a7db3fe0fc6c8214db8ab2775641f3eec56b48f7e0570ff073fdffedbbcdf7" +checksum = "f8bfe2a20799064eae4d8eee414b6960b5500222598164036f074671d6cb9904" dependencies = [ "once_cell", "preset_env_base", @@ -3241,9 +3241,9 @@ dependencies = [ [[package]] name = "swc_css_utils" -version = "0.119.1" +version = "0.120.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c81838d3ec3b3722d4cea64458b8b2f473b0b6eb63fbdf429d57d70cf262a7cb" +checksum = "31926afb46e05e8cf2dc3700b97ab192868e2051d8cfc7e7ff7d790a24278f06" dependencies = [ "once_cell", "serde", @@ -3256,9 +3256,9 @@ dependencies = [ [[package]] name = "swc_css_visit" -version = "0.121.1" +version = "0.122.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9613b15568230993d9a1e2bdac61c37f22abe4fd882abc50b2e7883e90e8fc5" +checksum = "fa6d37102e3e3763587b789b7eda1664cb163948e32f08741338eb7ae65eeeb0" dependencies = [ "serde", "swc_atoms", @@ -3269,9 +3269,9 @@ dependencies = [ [[package]] name = "swc_ecma_ast" -version = "0.94.11" +version = "0.94.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2509a573182f91de55320e6427e1ecf77a50dda3f63a0cc9e5a96bcaca53fe14" +checksum = "beaafac8e8c6ab204d65ec9761bf7b1513fc7cb3f307fbd12c901219c0a5c20b" dependencies = [ "bitflags", "is-macro", @@ -3287,9 +3287,9 @@ dependencies = [ [[package]] name = "swc_ecma_codegen" -version = "0.127.17" +version = "0.127.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad298191affa4288fb38f54d0de248bf574ac6ff96267fe719ddc5286d3e9c93" +checksum = "2aa40ba4f04658482496607b21d64a8f029d163c0f55c8c6fc4a7ac83b08dd6f" dependencies = [ "memchr", "num-bigint", @@ -3319,9 +3319,9 @@ dependencies = [ [[package]] name = "swc_ecma_ext_transforms" -version = "0.91.18" +version = "0.91.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2ba086508721a3fb581c0b28442b5c67b72fa96c4f58519479f58ef5d8643a7" +checksum = "798a2d8b484b0c12e72f9dee4bdcb1718216ceb8d2e6b16c064eab63c03ae8c1" dependencies = [ "phf", "swc_atoms", @@ -3333,9 +3333,9 @@ dependencies = [ [[package]] name = "swc_ecma_lints" -version = "0.66.25" +version = "0.66.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bf73cedb07db24ce5bcafd5a540ada45057b918954926c365bc16bd811b8680" +checksum = "abdd91a1c544ed15597151bfa510db41b0490e0b4dd2fb3b9546d1365b055476" dependencies = [ "ahash", "auto_impl", @@ -3354,9 +3354,9 @@ dependencies = [ [[package]] name = "swc_ecma_loader" -version = "0.41.9" +version = "0.41.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db84a155dae4e16871718558a47ad12501edcf29437499d0852357bd706e584e" +checksum = "6d698974ec9e0676537385f067ee3ebdfbf6d98c08130ce1b28d722db87c5d60" dependencies = [ "ahash", "anyhow", @@ -3376,9 +3376,9 @@ dependencies = [ [[package]] name = "swc_ecma_minifier" -version = "0.159.30" +version = "0.159.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ee4fc7420e3e894833a548fe9f9a45b0203b4ef0ea83a6da7c2b575f67f9f6f" +checksum = "aec9d4f8fed9093c778e14b3825b2926a2efa8498cddf9decb49158b40de7fba" dependencies = [ "ahash", "arrayvec", @@ -3410,9 +3410,9 @@ dependencies = [ [[package]] name = "swc_ecma_parser" -version = "0.122.13" +version = "0.122.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524aef6fd6a65f877108880329e668f2e60f7b408d83882858c55cf286bd1fec" +checksum = "6ca8d5fbd704c18ddc699717c7746a68e658cf6de6058d9a380c7df58fed5338" dependencies = [ "either", "enum_kind", @@ -3429,9 +3429,9 @@ dependencies = [ [[package]] name = "swc_ecma_preset_env" -version = "0.174.16" +version = "0.174.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9de6f74af5c5bde172dbb16461ee937983c2af01b70fe1c213f1c09cc644e5" +checksum = "028e78b81b0ea62841830fe9acc300432654609bdea0d94dca552eda0eaa1791" dependencies = [ "ahash", "anyhow", @@ -3470,9 +3470,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms" -version = "0.198.16" +version = "0.198.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aec98279e526604dc6ee7da40b45a68062192f8d1ebf670893c8cbfaa6eed301" +checksum = "99839d79b006b52c1df0e86158f1d7eff93cf4efe7ef53c004a1440e423133ff" dependencies = [ "swc_atoms", "swc_common", @@ -3490,9 +3490,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_base" -version = "0.111.26" +version = "0.111.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f14e060d4f9271238cd7088f57526a3694a4716be2c7f3005cf5484b1d455bd9" +checksum = "993cd3a0be3b5e35e51af8f06700a3fca13861482ba586f9cad12d081ceb0c8e" dependencies = [ "better_scoped_tls", "bitflags", @@ -3513,9 +3513,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_classes" -version = "0.100.25" +version = "0.100.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebfe4166eb4c3f58f913a55561f60ee79ce56af901613db65a1d64d61f78d9c1" +checksum = "3c46fdcd9a96380a9b7ad70f8ecdb059c068b76cbdd79ff822ca9e204abb0214" dependencies = [ "swc_atoms", "swc_common", @@ -3527,9 +3527,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_compat" -version = "0.136.12" +version = "0.136.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51a2965b7abb255bcae1ad9db159805d72b6e6701db405bde39d4f2eb4f454b7" +checksum = "fb99f24925b75eae214aa6ff6a4d08badfde1ae006b1be8b17e73a1dc49a422c" dependencies = [ "ahash", "arrayvec", @@ -3567,9 +3567,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_module" -version = "0.153.13" +version = "0.153.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89f82416cc7e21457a7b06432899e66e5933015128354f8e45e1b28ce41a0d77" +checksum = "45fcd2bf4e6bda9ffe3e1dd54b895f1747550b0fd04f8b463c7982e7694e0680" dependencies = [ "Inflector", "ahash", @@ -3595,9 +3595,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_optimization" -version = "0.167.16" +version = "0.167.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6c3e0882ba0a691ee9e63c27d6e806967d775e9e9e9692cd98ad34182d02ea" +checksum = "22e3341d0b52a425bcc0ce4d8b056c3cbea506e78ba7e00962157ca8b65d25c9" dependencies = [ "ahash", "dashmap", @@ -3621,9 +3621,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_proposal" -version = "0.144.12" +version = "0.144.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67d68f68ab789c203f809295073956294873b5a41e0c248a8ff14979fbf92b20" +checksum = "32c02eae68857dce8b7b7f063864500b82c4f3130dd7d64c78d637512af0964f" dependencies = [ "either", "serde", @@ -3640,9 +3640,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_react" -version = "0.155.13" +version = "0.155.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "757970530a568dbd3dd6b1e919e43ad28a726dc42f1b25665e0e5b2e26e25b2b" +checksum = "6eed61e65e92c3c5db3d5fdbd8433d51909fb1473576fe15b12ea9c63118df22" dependencies = [ "ahash", "base64", @@ -3667,9 +3667,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_testing" -version = "0.114.12" +version = "0.114.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d951d3059f3392c1b2e75d93d7d37fe806c4ee5e9298d24c06885ffc560e32" +checksum = "19c76d4a8b5a8a1f227f9a316a4137ced7b7dc4b140d58d23d10ba0a861ec519" dependencies = [ "ansi_term", "anyhow", @@ -3693,9 +3693,9 @@ dependencies = [ [[package]] name = "swc_ecma_transforms_typescript" -version = "0.159.14" +version = "0.159.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de76d2a596d487613f12fd04b8361f3883e0e6da8fb353c896a8fbf94b539b9" +checksum = "b1e59476f30cf62fad5f7183f7f778dbf08dc9821c892bf906b4c3445f4d35b3" dependencies = [ "serde", "swc_atoms", @@ -3709,9 +3709,9 @@ dependencies = [ [[package]] name = "swc_ecma_utils" -version = "0.105.18" +version = "0.105.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83425258fc1dd55ae5541fcbf766c65c944c20098eb14345c07decb4e5c0c300" +checksum = "1f2e4deb0f5cbb491ac3b6d28eb856cc00fd22d0149d10d96f43c658a3239f01" dependencies = [ "indexmap", "num_cpus", @@ -3727,9 +3727,9 @@ dependencies = [ [[package]] name = "swc_ecma_visit" -version = "0.80.11" +version = "0.80.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02ba4bec476ac4d25e48a6f777b19e8eb857a3ad453c830ef74176c8574177a1" +checksum = "02d510d7e892a2d23e96813d262fbfbdb984bcd9593c57676f682b1e02fc3eb9" dependencies = [ "num-bigint", "swc_atoms", @@ -3771,9 +3771,9 @@ dependencies = [ [[package]] name = "swc_error_reporters" -version = "0.13.8" +version = "0.13.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e175dfc7554a1f1b7cc5e1918a11cb537f7574ba258f233c96a5479a683af9b" +checksum = "df807362a74ecf07439f03c6ec09d72c469a0471eb2b08fc0dc93fb3482507b8" dependencies = [ "anyhow", "miette", @@ -3784,9 +3784,9 @@ dependencies = [ [[package]] name = "swc_fast_graph" -version = "0.17.9" +version = "0.17.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8b7421429d484e75ac5c70a4ae3c89b9e7bf0a1950731b6847cb22e001ad667" +checksum = "bdea120688bfd2d7183a8daa8b281daa0717e7e216f79b79548d736294697387" dependencies = [ "ahash", "indexmap", @@ -3796,9 +3796,9 @@ dependencies = [ [[package]] name = "swc_graph_analyzer" -version = "0.18.9" +version = "0.18.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288378f59c3d87e5a57ca7350c165113823b9302b94f9f9ada3314c9f22a4e6" +checksum = "908b1807b6744c4d261bba48e9f91346f5a7c5d21c1383aa85df3361af3f8351" dependencies = [ "ahash", "auto_impl", @@ -3831,9 +3831,9 @@ dependencies = [ [[package]] name = "swc_node_comments" -version = "0.16.8" +version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f66f8373372a49fd08a8b07f44ebb8dded10d47524e9914fb3e9397ac1bb4df4" +checksum = "8c07978351d9c326e969b5fff58ec844a765fe2367a4b0eaceb1ad18c07984bb" dependencies = [ "ahash", "dashmap", @@ -3858,9 +3858,9 @@ dependencies = [ [[package]] name = "swc_plugin_proxy" -version = "0.22.11" +version = "0.22.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e63919ebb1746b87198a6b036b79f9b465be8327eb25ddddd23a867f1d18f2b5" +checksum = "e77ac4bfe3caa221ec0dfd101852da000116d2c458280f9a94d2ec6114f0c660" dependencies = [ "better_scoped_tls", "rkyv", @@ -3872,9 +3872,9 @@ dependencies = [ [[package]] name = "swc_plugin_runner" -version = "0.77.16" +version = "0.77.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78aec934659ccb768198adde2cec91c6a2d5e242630af683b53b6d500c7fb157" +checksum = "1317d7c8e50b2fba5e33041216bae79ba20f1e0ac9cf19983bb50974367f8115" dependencies = [ "anyhow", "enumset", @@ -3895,9 +3895,9 @@ dependencies = [ [[package]] name = "swc_timer" -version = "0.17.8" +version = "0.17.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59be817f36174b972aa345a7ba1431191f414e4fd2ecd07052dac7968eca982c" +checksum = "243bba75c03251238d09f06cc04427e499d0136560a89ab8bf39dd4db89e264f" dependencies = [ "tracing", ] @@ -3989,9 +3989,9 @@ dependencies = [ [[package]] name = "testing" -version = "0.31.8" +version = "0.31.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f1d8f85e7121e1d4f895d394b381f6c9cfb3ec15df0c2b6771bbfa96cf356f1" +checksum = "7783ba6ebad3a5c0e50f23c2a24be50995c7d3d9a3bce050fc1a8c640995b261" dependencies = [ "ansi_term", "difference", diff --git a/packages/next-swc/crates/core/Cargo.toml b/packages/next-swc/crates/core/Cargo.toml index b36eccd262db..40e6cc4c8d0d 100644 --- a/packages/next-swc/crates/core/Cargo.toml +++ b/packages/next-swc/crates/core/Cargo.toml @@ -42,9 +42,9 @@ swc_core = { features = [ "ecma_parser_typescript", "cached", "base" -], version = "0.38.22" } +], version = "0.39.7" } [dev-dependencies] -swc_core = { features = ["testing_transform"], version = "0.38.22" } -testing = "0.31.8" +swc_core = { features = ["testing_transform"], version = "0.39.7" } +testing = "0.31.9" walkdir = "2.3.2" diff --git a/packages/next-swc/crates/emotion/Cargo.toml b/packages/next-swc/crates/emotion/Cargo.toml index d09ecaeaead3..d33fab749fc8 100644 --- a/packages/next-swc/crates/emotion/Cargo.toml +++ b/packages/next-swc/crates/emotion/Cargo.toml @@ -19,9 +19,9 @@ regex = "1.5" serde = "1" sourcemap = "6.0.1" tracing = { version = "0.1.32", features = ["release_max_level_info"] } -swc_core = { features = ["common", "ecma_ast","ecma_codegen", "ecma_utils", "ecma_visit", "trace_macro"], version = "0.38.22" } +swc_core = { features = ["common", "ecma_ast","ecma_codegen", "ecma_utils", "ecma_visit", "trace_macro"], version = "0.39.7" } [dev-dependencies] -swc_core = { features = ["testing_transform", "ecma_transforms_react"], version = "0.38.22" } -testing = "0.31.8" +swc_core = { features = ["testing_transform", "ecma_transforms_react"], version = "0.39.7" } +testing = "0.31.9" serde_json = "1" diff --git a/packages/next-swc/crates/modularize_imports/Cargo.toml b/packages/next-swc/crates/modularize_imports/Cargo.toml index 8d8243da3729..ab220afdc499 100644 --- a/packages/next-swc/crates/modularize_imports/Cargo.toml +++ b/packages/next-swc/crates/modularize_imports/Cargo.toml @@ -15,8 +15,8 @@ handlebars = "4.2.1" once_cell = "1.13.0" regex = "1.5" serde = "1" -swc_core = { features = ["cached", "ecma_ast", "ecma_visit"], version = "0.38.22" } +swc_core = { features = ["cached", "ecma_ast", "ecma_visit"], version = "0.39.7" } [dev-dependencies] -swc_core = { features = ["testing_transform"], version = "0.38.22" } -testing = "0.31.8" +swc_core = { features = ["testing_transform"], version = "0.39.7" } +testing = "0.31.9" diff --git a/packages/next-swc/crates/napi/Cargo.toml b/packages/next-swc/crates/napi/Cargo.toml index b45f0c133331..b92541b5b479 100644 --- a/packages/next-swc/crates/napi/Cargo.toml +++ b/packages/next-swc/crates/napi/Cargo.toml @@ -50,7 +50,7 @@ swc_core = { features = [ "ecma_transforms_typescript", "ecma_utils", "ecma_visit", -], version = "0.38.22" } +], version = "0.39.7" } tracing = { version = "0.1.32", features = ["release_max_level_info"] } tracing-futures = "0.2.5" tracing-subscriber = "0.3.9" diff --git a/packages/next-swc/crates/styled_components/Cargo.toml b/packages/next-swc/crates/styled_components/Cargo.toml index d8058a0d0aaa..f889ae6c631e 100644 --- a/packages/next-swc/crates/styled_components/Cargo.toml +++ b/packages/next-swc/crates/styled_components/Cargo.toml @@ -21,13 +21,13 @@ swc_core = { features = [ "ecma_ast", "ecma_utils", "ecma_visit" -], version = "0.38.22" } +], version = "0.39.7" } [dev-dependencies] serde_json = "1" -testing = "0.31.8" +testing = "0.31.9" swc_core = { features = [ "ecma_parser", "ecma_transforms", "testing_transform" -], version = "0.38.22" } +], version = "0.39.7" } diff --git a/packages/next-swc/crates/styled_jsx/Cargo.toml b/packages/next-swc/crates/styled_jsx/Cargo.toml index d522ca3397a5..cd83659d98db 100644 --- a/packages/next-swc/crates/styled_jsx/Cargo.toml +++ b/packages/next-swc/crates/styled_jsx/Cargo.toml @@ -24,10 +24,10 @@ swc_core = { features = [ "ecma_minifier", "ecma_utils", "ecma_visit" -], version = "0.38.22" } +], version = "0.39.7" } [dev-dependencies] -testing = "0.31.8" +testing = "0.31.9" swc_core = { features = [ "testing_transform" -], version = "0.38.22" } +], version = "0.39.7" } diff --git a/packages/next-swc/crates/wasm/Cargo.toml b/packages/next-swc/crates/wasm/Cargo.toml index abb9815079a0..6a46d53d8231 100644 --- a/packages/next-swc/crates/wasm/Cargo.toml +++ b/packages/next-swc/crates/wasm/Cargo.toml @@ -45,7 +45,7 @@ swc_core = { features = [ "ecma_parser_typescript", "ecma_utils", "ecma_visit" -], version = "0.38.22" } +], version = "0.39.7" } # Workaround a bug diff --git a/packages/next-swc/package.json b/packages/next-swc/package.json index 25ae7556c6c1..a2eb7579095e 100644 --- a/packages/next-swc/package.json +++ b/packages/next-swc/package.json @@ -1,6 +1,6 @@ { "name": "@next/swc", - "version": "12.3.2-canary.30", + "version": "12.3.2-canary.32", "private": true, "scripts": { "build-native": "napi build --platform -p next-swc-napi --cargo-name next_swc_napi --features plugin --js false native", diff --git a/packages/next/build/index.ts b/packages/next/build/index.ts index b4f4e122cc9e..9aff27259e62 100644 --- a/packages/next/build/index.ts +++ b/packages/next/build/index.ts @@ -300,6 +300,9 @@ export default async function build( const publicDir = path.join(dir, 'public') const isAppDirEnabled = !!config.experimental.appDir + if (isAppDirEnabled) { + process.env.HAS_APP_DIR = '1' + } const { pagesDir, appDir } = findPagesDir(dir, isAppDirEnabled) const hasPublicDir = await fileExists(publicDir) diff --git a/packages/next/build/utils.ts b/packages/next/build/utils.ts index 0b50d10708f0..23f64a0b5622 100644 --- a/packages/next/build/utils.ts +++ b/packages/next/build/utils.ts @@ -1,7 +1,6 @@ import type { NextConfigComplete } from '../server/config-shared' import '../server/node-polyfill-fetch' -import loadRequireHook from '../build/webpack/require-hook' import chalk from 'next/dist/compiled/chalk' import getGzipSize from 'next/dist/compiled/gzip-size' import textTable from 'next/dist/compiled/text-table' @@ -49,6 +48,15 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin' import { getRuntimeContext } from '../server/web/sandbox' +import { + loadRequireHook, + overrideBuiltInReactPackages, +} from './webpack/require-hook' + +loadRequireHook() +if (process.env.HAS_APP_DIR) { + overrideBuiltInReactPackages() +} export type ROUTER_TYPE = 'pages' | 'app' @@ -69,8 +77,6 @@ const fsStat = (file: string) => { return (fileStats[file] = fileSize(file)) } -loadRequireHook() - export function unique(main: ReadonlyArray, sub: ReadonlyArray): T[] { return [...new Set([...main, ...sub])] } @@ -1755,8 +1761,9 @@ export function getSupportedBrowsers( return browsers } - // When user does not have browserslist use the default target - // When `experimental.legacyBrowsers: false` the modern default is used + // When the user sets `legacyBrowsers: true`, we pass undefined + // to SWC which is basically ES5 and matches the default behavior + // prior to Next.js 13 return config.experimental.legacyBrowsers ? undefined : MODERN_BROWSERSLIST_TARGET diff --git a/packages/next/build/webpack-config.ts b/packages/next/build/webpack-config.ts index 412634c03775..a5a25db39123 100644 --- a/packages/next/build/webpack-config.ts +++ b/packages/next/build/webpack-config.ts @@ -2,7 +2,7 @@ import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-ut import chalk from 'next/dist/compiled/chalk' import crypto from 'crypto' import { webpack } from 'next/dist/compiled/webpack/webpack' -import path, { dirname, join as pathJoin, relative as relativePath } from 'path' +import path, { join as pathJoin, relative as relativePath } from 'path' import { escapeStringRegexp } from '../shared/lib/escape-regexp' import { DOT_NEXT_ALIAS, @@ -89,9 +89,6 @@ const nodePathList = (process.env.NODE_PATH || '') .split(process.platform === 'win32' ? ';' : ':') .filter((p) => !!p) -const reactDir = dirname(require.resolve('react/package.json')) -const reactDomDir = dirname(require.resolve('react-dom/package.json')) - const watchOptions = Object.freeze({ aggregateTimeout: 5, ignored: ['**/.git/**', '**/.next/**'], @@ -125,6 +122,12 @@ function isResourceInPackages(resource: string, packageNames?: string[]) { ) } +const builtInReactImports = [ + 'react', + 'react/jsx-runtime', + 'next/dist/compiled/react-server-dom-webpack/writer.browser.server', +] + export function getDefineEnv({ dev, config, @@ -573,11 +576,6 @@ export default async function getBaseWebpackConfig( '`experimental.runtime` requires React 18 to be installed.' ) } - if (hasAppDir) { - throw new Error( - '`experimental.appDir` requires React 18 to be installed.' - ) - } } } @@ -698,9 +696,7 @@ export default async function getBaseWebpackConfig( fileReading: config.experimental.swcFileReading, nextConfig: config, jsConfig, - supportedBrowsers: config.experimental.browsersListForSwc - ? supportedBrowsers - : undefined, + supportedBrowsers, swcCacheDir: path.join(dir, config?.distDir ?? '.next', 'cache', 'swc'), ...extraOptions, }, @@ -869,11 +865,19 @@ export default async function getBaseWebpackConfig( next: NEXT_PROJECT_ROOT, - react: reactDir, - 'react-dom$': reactDomDir, - 'react-dom/server$': `${reactDomDir}/server`, - 'react-dom/server.browser$': `${reactDomDir}/server.browser`, - 'react-dom/client$': `${reactDomDir}/client`, + ...(hasServerComponents + ? { + // For react and react-dom, alias them dynamically for server layer + // and others in the loaders configuration + 'react-dom/client$': 'next/dist/compiled/react-dom/client', + 'react-dom/server$': 'next/dist/compiled/react-dom/server', + 'react-dom/server.browser$': + 'next/dist/compiled/react-dom/server.browser', + 'react/jsx-dev-runtime$': + 'next/dist/compiled/react/jsx-dev-runtime', + 'react/jsx-runtime$': 'next/dist/compiled/react/jsx-runtime', + } + : undefined), 'styled-jsx/style$': require.resolve(`styled-jsx/style`), 'styled-jsx$': require.resolve(`styled-jsx`), @@ -1035,12 +1039,7 @@ export default async function getBaseWebpackConfig( // Special internal modules that must be bundled for Server Components. if (layer === WEBPACK_LAYERS.server) { - if ( - request === 'react' || - request === 'react/jsx-runtime' || - request === - 'next/dist/compiled/react-server-dom-webpack/writer.browser.server' - ) { + if (builtInReactImports.includes(request)) { return } } @@ -1514,47 +1513,6 @@ export default async function getBaseWebpackConfig( }, module: { rules: [ - ...(hasAppDir && !isClient && !isEdgeServer - ? [ - { - issuerLayer: WEBPACK_LAYERS.server, - test: (req: string) => { - // If it's not a source code file, or has been opted out of - // bundling, don't resolve it. - if ( - !codeCondition.test.test(req) || - isResourceInPackages( - req, - config.experimental.serverComponentsExternalPackages - ) - ) { - return false - } - - return true - }, - resolve: process.env.__NEXT_REACT_CHANNEL - ? { - conditionNames: ['react-server', 'node', 'require'], - alias: { - react: `react-${process.env.__NEXT_REACT_CHANNEL}`, - 'react-dom': `react-dom-${process.env.__NEXT_REACT_CHANNEL}`, - }, - } - : { - conditionNames: ['react-server', 'node', 'require'], - alias: { - // 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: 'react', - 'react-dom': 'react-dom', - }, - }, - }, - ] - : []), - // TODO: FIXME: do NOT webpack 5 support with this // x-ref: https://github.com/webpack/webpack/issues/11467 ...(!config.experimental.fullySpecified @@ -1578,22 +1536,39 @@ export default async function getBaseWebpackConfig( }, ] : []), - // Alias `next/dynamic` to React.lazy implementation for RSC - ...(hasServerComponents + ...(hasAppDir && !isClient ? [ { - test: codeCondition.test, - include: [appDir], + issuerLayer: WEBPACK_LAYERS.server, + test: (req: string) => { + // If it's not a source code file, or has been opted out of + // bundling, don't resolve it. + if ( + !codeCondition.test.test(req) || + isResourceInPackages( + req, + config.experimental.serverComponentsExternalPackages + ) + ) { + return false + } + + return true + }, resolve: { + conditionNames: ['react-server', 'node', 'require'], alias: { - [require.resolve('next/dynamic')]: - 'next/dist/client/components/dynamic', + // 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: 'react', + 'react-dom': 'react-dom', }, }, }, ] : []), - ...(hasServerComponents && (isNodeServer || isEdgeServer) + ...(hasServerComponents && !isClient ? [ // RSC server compilation loaders { @@ -1601,7 +1576,7 @@ export default async function getBaseWebpackConfig( include: [ dir, // To let the internal client components passing through flight loader - /next[\\/]dist/, + NEXT_PROJECT_ROOT_DIST, ], issuerLayer: WEBPACK_LAYERS.server, use: { @@ -1610,6 +1585,72 @@ export default async function getBaseWebpackConfig( }, ] : []), + // Alias `next/dynamic` to React.lazy implementation for RSC + ...(hasServerComponents + ? [ + { + test: codeCondition.test, + include: [appDir], + resolve: { + alias: { + // Alias `next/dynamic` to React.lazy implementation for RSC + [require.resolve('next/dynamic')]: require.resolve( + 'next/dist/client/components/dynamic' + ), + }, + }, + }, + { + // Alias react-dom for ReactDOM.preload usage. + // Alias react for switching between default set and share subset. + oneOf: [ + { + // test: codeCondition.test, + issuerLayer: WEBPACK_LAYERS.server, + test: (req: string) => { + // If it's not a source code file, or has been opted out of + // bundling, don't resolve it. + if ( + !codeCondition.test.test(req) || + isResourceInPackages( + req, + config.experimental.serverComponentsExternalPackages + ) + ) { + return false + } + + return true + }, + resolve: { + // 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', + // 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', + }, + }, + }, + { + test: codeCondition.test, + resolve: { + alias: { + react: 'next/dist/compiled/react', + 'react-dom$': isClient + ? 'next/dist/compiled/react-dom/index' + : 'next/dist/compiled/react-dom/server-rendering-stub', + 'react-dom/client$': + 'next/dist/compiled/react-dom/client', + }, + }, + }, + ], + }, + ] + : []), { test: /\.(js|cjs|mjs)$/, issuerLayer: WEBPACK_LAYERS.api, diff --git a/packages/next/build/webpack/require-hook.ts b/packages/next/build/webpack/require-hook.ts index 0c0d6890f78b..0a75a9134f0a 100644 --- a/packages/next/build/webpack/require-hook.ts +++ b/packages/next/build/webpack/require-hook.ts @@ -2,16 +2,14 @@ // this is in order for userland plugins to attach to the same webpack instance as next.js // the individual compiled modules are as defined for the compilation in bundles/webpack/packages/* -export default function loadRequireHook(aliases: [string, string][] = []) { - const hookPropertyMap = new Map( - [ - ...aliases, - // Use `require.resolve` explicitly to make them statically analyzable - ['styled-jsx', require.resolve('styled-jsx')], - ['styled-jsx/style', require.resolve('styled-jsx/style')], - ].map(([request, replacement]) => [request, replacement]) - ) +const hookPropertyMap = new Map() +let initialized = false +function setupResolve() { + if (initialized) { + return + } + initialized = true const mod = require('module') const resolveFilename = mod._resolveFilename mod._resolveFilename = function ( @@ -25,3 +23,53 @@ export default function loadRequireHook(aliases: [string, string][] = []) { return resolveFilename.call(mod, request, parent, isMain, options) } } + +export function setRequireOverrides(aliases: [string, string][]) { + for (const [key, value] of aliases) { + hookPropertyMap.set(key, value) + } +} + +export function loadRequireHook(aliases: [string, string][] = []) { + const defaultAliases = [ + ...aliases, + // Use `require.resolve` explicitly to make them statically analyzable + ['styled-jsx', require.resolve('styled-jsx')], + ['styled-jsx/style', require.resolve('styled-jsx/style')], + ['styled-jsx/style', require.resolve('styled-jsx/style')], + ] as [string, string][] + + setRequireOverrides(defaultAliases) + + setupResolve() +} + +export function overrideBuiltInReactPackages() { + setRequireOverrides([ + ['react', require.resolve('next/dist/compiled/react')], + [ + 'react/jsx-runtime', + require.resolve('next/dist/compiled/react/jsx-runtime'), + ], + [ + 'react/jsx-dev-runtime', + require.resolve('next/dist/compiled/react/jsx-dev-runtime'), + ], + [ + 'react-dom', + require.resolve('next/dist/compiled/react-dom/server-rendering-stub'), + ], + [ + 'react-dom/client', + require.resolve('next/dist/compiled/react-dom/client'), + ], + [ + 'react-dom/server', + require.resolve('next/dist/compiled/react-dom/server'), + ], + [ + 'react-dom/server.browser', + require.resolve('next/dist/compiled/react-dom/server.browser'), + ], + ]) +} diff --git a/packages/next/client/components/react-dev-overlay/hot-reloader.tsx b/packages/next/client/components/react-dev-overlay/hot-reloader.tsx index 5f678e05a807..128507a72a5b 100644 --- a/packages/next/client/components/react-dev-overlay/hot-reloader.tsx +++ b/packages/next/client/components/react-dev-overlay/hot-reloader.tsx @@ -128,7 +128,7 @@ function performFullReload(err: any, sendMessage: any) { // Attempt to update code on the fly, fall back to a hard reload. function tryApplyUpdates( - onHotUpdateSuccess: any, + onHotUpdateSuccess: (hasUpdates: boolean) => void, sendMessage: any, dispatch: DispatchFn ) { @@ -174,7 +174,7 @@ function tryApplyUpdates( if (isUpdateAvailable()) { // While we were updating, there was a new update! Do it again. tryApplyUpdates( - hasUpdates ? onBuildOk : onHotUpdateSuccess, + hasUpdates ? () => onBuildOk(dispatch) : onHotUpdateSuccess, sendMessage, dispatch ) diff --git a/packages/next/compiled/react-dom/LICENSE b/packages/next/compiled/react-dom/LICENSE new file mode 100644 index 000000000000..b96dcb0480a0 --- /dev/null +++ b/packages/next/compiled/react-dom/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its 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/compiled/react-dom/cjs/react-dom-server-legacy.browser.development.js b/packages/next/compiled/react-dom/cjs/react-dom-server-legacy.browser.development.js new file mode 100644 index 000000000000..341a5ad48243 --- /dev/null +++ b/packages/next/compiled/react-dom/cjs/react-dom-server-legacy.browser.development.js @@ -0,0 +1,8682 @@ +/** + * @license React + * react-dom-server-legacy.browser.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var React = require('react'); +var ReactDOM = require('react-dom'); + +var ReactVersion = '18.3.0-experimental-a8c16a004-20221012'; + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. + +function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } + } +} +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); + } +} + +function scheduleWork(callback) { + callback(); +} +function beginWriting(destination) {} +function writeChunk(destination, chunk) { + writeChunkAndReturn(destination, chunk); +} +function writeChunkAndReturn(destination, chunk) { + return destination.push(chunk); +} +function completeWriting(destination) {} +function close(destination) { + destination.push(null); +} +function stringToChunk(content) { + return content; +} +function stringToPrecomputedChunk(content) { + return content; +} +function closeWithError(destination, error) { + // $FlowFixMe: This is an Error object or the destination accepts other types. + destination.destroy(error); +} + +/* + * The `'' + value` pattern (used in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ +// $FlowFixMe only called in DEV, so void return is not possible. +function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; // $FlowFixMe + + return type; + } +} // $FlowFixMe only called in DEV, so void return is not possible. + + +function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } +} + +function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; +} + +function checkAttributeStringCoercion(value, attributeName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} +function checkCSSPropertyStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} +function checkHtmlStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} + +// ----------------------------------------------------------------------------- +var enableFloat = true; // When a node is unmounted, recurse into the Fiber subtree and clean out + +// $FlowFixMe[method-unbinding] +var hasOwnProperty = Object.prototype.hasOwnProperty; + +// A reserved attribute. +// It is handled by React separately and shouldn't be written to the DOM. +var RESERVED = 0; // A simple string attribute. +// Attributes that aren't in the filter are presumed to have this type. + +var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called +// "enumerated" attributes with "true" and "false" as possible values. +// When true, it should be set to a "true" string. +// When false, it should be set to a "false" string. + +var BOOLEANISH_STRING = 2; // A real boolean attribute. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. + +var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +// For any other value, should be present with that value. + +var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. +// When falsy, it should be removed. + +var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. +// When falsy, it should be removed. + +var POSITIVE_NUMERIC = 6; + +/* eslint-disable max-len */ +var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +/* eslint-enable max-len */ + +var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; +function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } + + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } + + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + + illegalAttributeNameCache[attributeName] = true; + + { + error('Invalid attribute name: `%s`', attributeName); + } + + return false; +} +function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + + switch (typeof value) { + case 'function': + case 'symbol': + // eslint-disable-line + return true; + + case 'boolean': + { + if (isCustomComponentTag) { + return false; + } + + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix = name.toLowerCase().slice(0, 5); + return prefix !== 'data-' && prefix !== 'aria-'; + } + } + + default: + return false; + } +} +function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; +} + +function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL; + this.removeEmptyString = removeEmptyString; +} // When adding attributes to this list, be sure to also add them to +// the `possibleStandardNames` module to ensure casing and incorrect +// name warnings. + + +var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. + +var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular +// elements (not just inputs). Now that ReactDOMInput assigns to the +// defaultValue property -- do we need this? +'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; + +{ + reservedProps.push('innerText', 'textContent'); +} + +reservedProps.forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // A few React string attributes have a different name. +// This is a mapping from React prop names to the attribute names. + +[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { + var name = _ref[0], + attributeName = _ref[1]; + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" HTML attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). + +['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" SVG attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +// Since these are SVG attributes, their attribute names are case-sensitive. + +['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML boolean attributes. + +['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM +// on the client side because the browsers are inconsistent. Instead we call focus(). +'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata +'itemScope'].forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are the few React props that we set as DOM properties +// rather than attributes. These are all booleans. + +['checked', // Note: `option.selected` is not updated if `select.multiple` is +// disabled with `removeAttribute`. We have special logic for handling this. +'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that are "overloaded booleans": they behave like +// booleans, but can also accept a string value. + +['capture', 'download' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be positive numbers. + +['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be numbers. + +['rowSpan', 'start'].forEach(function (name) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); +var CAMELIZE = /[\-\:]([a-z])/g; + +var capitalize = function (token) { + return token[1].toUpperCase(); +}; // This is a list of all SVG attributes that need special casing, namespacing, +// or boolean value assignment. Regular attributes that just accept strings +// and have the same names are omitted, just like in the HTML attribute filter. +// Some of these attributes can be hard to find. This list was created by +// scraping the MDN documentation. + + +['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, null, // attributeNamespace + false, // sanitizeURL + false); +}); // String SVG attributes with the xlink namespace. + +['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL + false); +}); // String SVG attributes with the xml namespace. + +['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL + false); +}); // These attribute exists both in HTML and SVG. +// The attribute name is case-sensitive in SVG so we can't just use +// the React name like we do for attributes that exist only in HTML. + +['tabIndex', 'crossOrigin'].forEach(function (attributeName) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These attributes accept URLs. These must not allow javascript: URLS. +// These will also need to accept Trusted Types object in the future. + +var xlinkHref = 'xlinkHref'; // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + +properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty +'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL +false); +['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { + // $FlowFixMe[invalid-constructor] Flow no longer supports calling new on functions + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + true, // sanitizeURL + true); +}); + +/** + * CSS properties which accept numbers but are not in units of "px". + */ +var isUnitlessNumber = { + animationIterationCount: true, + aspectRatio: true, + borderImageOutset: true, + borderImageSlice: true, + borderImageWidth: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + columns: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + gridArea: true, + gridRow: true, + gridRowEnd: true, + gridRowSpan: true, + gridRowStart: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnSpan: true, + gridColumnStart: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + // SVG-related properties + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeDasharray: true, + strokeDashoffset: true, + strokeMiterlimit: true, + strokeOpacity: true, + strokeWidth: true +}; +/** + * @param {string} prefix vendor-specific prefix, eg: Webkit + * @param {string} key style name, eg: transitionDuration + * @return {string} style name prefixed with `prefix`, properly camelCased, eg: + * WebkitTransitionDuration + */ + +function prefixKey(prefix, key) { + return prefix + key.charAt(0).toUpperCase() + key.substring(1); +} +/** + * Support style names that may come passed in prefixed by adding permutations + * of vendor prefixes. + */ + + +var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an +// infinite loop, because it iterates over the newly added props too. + +Object.keys(isUnitlessNumber).forEach(function (prop) { + prefixes.forEach(function (prefix) { + isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; + }); +}); + +var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true +}; +function checkControlledValueProps(tagName, props) { + { + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + } +} + +function isCustomComponent(tagName, props) { + if (tagName.indexOf('-') === -1) { + return typeof props.is === 'string'; + } + + switch (tagName) { + // These are reserved SVG and MathML elements. + // We don't mind this list too much because we expect it to never grow. + // The alternative is to track the namespace in a few places which is convoluted. + // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts + case 'annotation-xml': + case 'color-profile': + case 'font-face': + case 'font-face-src': + case 'font-face-uri': + case 'font-face-format': + case 'font-face-name': + case 'missing-glyph': + return false; + + default: + return true; + } +} + +var ariaProperties = { + 'aria-current': 0, + // state + 'aria-description': 0, + 'aria-details': 0, + 'aria-disabled': 0, + // state + 'aria-hidden': 0, + // state + 'aria-invalid': 0, + // state + 'aria-keyshortcuts': 0, + 'aria-label': 0, + 'aria-roledescription': 0, + // Widget Attributes + 'aria-autocomplete': 0, + 'aria-checked': 0, + 'aria-expanded': 0, + 'aria-haspopup': 0, + 'aria-level': 0, + 'aria-modal': 0, + 'aria-multiline': 0, + 'aria-multiselectable': 0, + 'aria-orientation': 0, + 'aria-placeholder': 0, + 'aria-pressed': 0, + 'aria-readonly': 0, + 'aria-required': 0, + 'aria-selected': 0, + 'aria-sort': 0, + 'aria-valuemax': 0, + 'aria-valuemin': 0, + 'aria-valuenow': 0, + 'aria-valuetext': 0, + // Live Region Attributes + 'aria-atomic': 0, + 'aria-busy': 0, + 'aria-live': 0, + 'aria-relevant': 0, + // Drag-and-Drop Attributes + 'aria-dropeffect': 0, + 'aria-grabbed': 0, + // Relationship Attributes + 'aria-activedescendant': 0, + 'aria-colcount': 0, + 'aria-colindex': 0, + 'aria-colspan': 0, + 'aria-controls': 0, + 'aria-describedby': 0, + 'aria-errormessage': 0, + 'aria-flowto': 0, + 'aria-labelledby': 0, + 'aria-owns': 0, + 'aria-posinset': 0, + 'aria-rowcount': 0, + 'aria-rowindex': 0, + 'aria-rowspan': 0, + 'aria-setsize': 0 +}; + +var warnedProperties = {}; +var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); +var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); + +function validateProperty(tagName, name) { + { + if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { + return true; + } + + if (rARIACamel.test(name)) { + var ariaName = 'aria-' + name.slice(4).toLowerCase(); + var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM + // DOM properties, then it is an invalid aria-* attribute. + + if (correctName == null) { + error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name); + + warnedProperties[name] = true; + return true; + } // aria-* attributes should be lowercase; suggest the lowercase version. + + + if (name !== correctName) { + error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName); + + warnedProperties[name] = true; + return true; + } + } + + if (rARIA.test(name)) { + var lowerCasedName = name.toLowerCase(); + var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM + // DOM properties, then it is an invalid aria-* attribute. + + if (standardName == null) { + warnedProperties[name] = true; + return false; + } // aria-* attributes should be lowercase; suggest the lowercase version. + + + if (name !== standardName) { + error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName); + + warnedProperties[name] = true; + return true; + } + } + } + + return true; +} + +function warnInvalidARIAProps(type, props) { + { + var invalidProps = []; + + for (var key in props) { + var isValid = validateProperty(type, key); + + if (!isValid) { + invalidProps.push(key); + } + } + + var unknownPropString = invalidProps.map(function (prop) { + return '`' + prop + '`'; + }).join(', '); + + if (invalidProps.length === 1) { + error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); + } else if (invalidProps.length > 1) { + error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); + } + } +} + +function validateProperties(type, props) { + if (isCustomComponent(type, props)) { + return; + } + + warnInvalidARIAProps(type, props); +} + +var didWarnValueNull = false; +function validateProperties$1(type, props) { + { + if (type !== 'input' && type !== 'textarea' && type !== 'select') { + return; + } + + if (props != null && props.value === null && !didWarnValueNull) { + didWarnValueNull = true; + + if (type === 'select' && props.multiple) { + error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type); + } else { + error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type); + } + } + } +} + +// When adding attributes to the HTML or SVG allowed attribute list, be sure to +// also add them to this module to ensure casing and incorrect name +// warnings. +var possibleStandardNames = { + // HTML + accept: 'accept', + acceptcharset: 'acceptCharset', + 'accept-charset': 'acceptCharset', + accesskey: 'accessKey', + action: 'action', + allowfullscreen: 'allowFullScreen', + alt: 'alt', + as: 'as', + async: 'async', + autocapitalize: 'autoCapitalize', + autocomplete: 'autoComplete', + autocorrect: 'autoCorrect', + autofocus: 'autoFocus', + autoplay: 'autoPlay', + autosave: 'autoSave', + capture: 'capture', + cellpadding: 'cellPadding', + cellspacing: 'cellSpacing', + challenge: 'challenge', + charset: 'charSet', + checked: 'checked', + children: 'children', + cite: 'cite', + class: 'className', + classid: 'classID', + classname: 'className', + cols: 'cols', + colspan: 'colSpan', + content: 'content', + contenteditable: 'contentEditable', + contextmenu: 'contextMenu', + controls: 'controls', + controlslist: 'controlsList', + coords: 'coords', + crossorigin: 'crossOrigin', + dangerouslysetinnerhtml: 'dangerouslySetInnerHTML', + data: 'data', + datetime: 'dateTime', + default: 'default', + defaultchecked: 'defaultChecked', + defaultvalue: 'defaultValue', + defer: 'defer', + dir: 'dir', + disabled: 'disabled', + disablepictureinpicture: 'disablePictureInPicture', + disableremoteplayback: 'disableRemotePlayback', + download: 'download', + draggable: 'draggable', + enctype: 'encType', + enterkeyhint: 'enterKeyHint', + for: 'htmlFor', + form: 'form', + formmethod: 'formMethod', + formaction: 'formAction', + formenctype: 'formEncType', + formnovalidate: 'formNoValidate', + formtarget: 'formTarget', + frameborder: 'frameBorder', + headers: 'headers', + height: 'height', + hidden: 'hidden', + high: 'high', + href: 'href', + hreflang: 'hrefLang', + htmlfor: 'htmlFor', + httpequiv: 'httpEquiv', + 'http-equiv': 'httpEquiv', + icon: 'icon', + id: 'id', + imagesizes: 'imageSizes', + imagesrcset: 'imageSrcSet', + innerhtml: 'innerHTML', + inputmode: 'inputMode', + integrity: 'integrity', + is: 'is', + itemid: 'itemID', + itemprop: 'itemProp', + itemref: 'itemRef', + itemscope: 'itemScope', + itemtype: 'itemType', + keyparams: 'keyParams', + keytype: 'keyType', + kind: 'kind', + label: 'label', + lang: 'lang', + list: 'list', + loop: 'loop', + low: 'low', + manifest: 'manifest', + marginwidth: 'marginWidth', + marginheight: 'marginHeight', + max: 'max', + maxlength: 'maxLength', + media: 'media', + mediagroup: 'mediaGroup', + method: 'method', + min: 'min', + minlength: 'minLength', + multiple: 'multiple', + muted: 'muted', + name: 'name', + nomodule: 'noModule', + nonce: 'nonce', + novalidate: 'noValidate', + open: 'open', + optimum: 'optimum', + pattern: 'pattern', + placeholder: 'placeholder', + playsinline: 'playsInline', + poster: 'poster', + preload: 'preload', + profile: 'profile', + radiogroup: 'radioGroup', + readonly: 'readOnly', + referrerpolicy: 'referrerPolicy', + rel: 'rel', + required: 'required', + reversed: 'reversed', + role: 'role', + rows: 'rows', + rowspan: 'rowSpan', + sandbox: 'sandbox', + scope: 'scope', + scoped: 'scoped', + scrolling: 'scrolling', + seamless: 'seamless', + selected: 'selected', + shape: 'shape', + size: 'size', + sizes: 'sizes', + span: 'span', + spellcheck: 'spellCheck', + src: 'src', + srcdoc: 'srcDoc', + srclang: 'srcLang', + srcset: 'srcSet', + start: 'start', + step: 'step', + style: 'style', + summary: 'summary', + tabindex: 'tabIndex', + target: 'target', + title: 'title', + type: 'type', + usemap: 'useMap', + value: 'value', + width: 'width', + wmode: 'wmode', + wrap: 'wrap', + // SVG + about: 'about', + accentheight: 'accentHeight', + 'accent-height': 'accentHeight', + accumulate: 'accumulate', + additive: 'additive', + alignmentbaseline: 'alignmentBaseline', + 'alignment-baseline': 'alignmentBaseline', + allowreorder: 'allowReorder', + alphabetic: 'alphabetic', + amplitude: 'amplitude', + arabicform: 'arabicForm', + 'arabic-form': 'arabicForm', + ascent: 'ascent', + attributename: 'attributeName', + attributetype: 'attributeType', + autoreverse: 'autoReverse', + azimuth: 'azimuth', + basefrequency: 'baseFrequency', + baselineshift: 'baselineShift', + 'baseline-shift': 'baselineShift', + baseprofile: 'baseProfile', + bbox: 'bbox', + begin: 'begin', + bias: 'bias', + by: 'by', + calcmode: 'calcMode', + capheight: 'capHeight', + 'cap-height': 'capHeight', + clip: 'clip', + clippath: 'clipPath', + 'clip-path': 'clipPath', + clippathunits: 'clipPathUnits', + cliprule: 'clipRule', + 'clip-rule': 'clipRule', + color: 'color', + colorinterpolation: 'colorInterpolation', + 'color-interpolation': 'colorInterpolation', + colorinterpolationfilters: 'colorInterpolationFilters', + 'color-interpolation-filters': 'colorInterpolationFilters', + colorprofile: 'colorProfile', + 'color-profile': 'colorProfile', + colorrendering: 'colorRendering', + 'color-rendering': 'colorRendering', + contentscripttype: 'contentScriptType', + contentstyletype: 'contentStyleType', + cursor: 'cursor', + cx: 'cx', + cy: 'cy', + d: 'd', + datatype: 'datatype', + decelerate: 'decelerate', + descent: 'descent', + diffuseconstant: 'diffuseConstant', + direction: 'direction', + display: 'display', + divisor: 'divisor', + dominantbaseline: 'dominantBaseline', + 'dominant-baseline': 'dominantBaseline', + dur: 'dur', + dx: 'dx', + dy: 'dy', + edgemode: 'edgeMode', + elevation: 'elevation', + enablebackground: 'enableBackground', + 'enable-background': 'enableBackground', + end: 'end', + exponent: 'exponent', + externalresourcesrequired: 'externalResourcesRequired', + fill: 'fill', + fillopacity: 'fillOpacity', + 'fill-opacity': 'fillOpacity', + fillrule: 'fillRule', + 'fill-rule': 'fillRule', + filter: 'filter', + filterres: 'filterRes', + filterunits: 'filterUnits', + floodopacity: 'floodOpacity', + 'flood-opacity': 'floodOpacity', + floodcolor: 'floodColor', + 'flood-color': 'floodColor', + focusable: 'focusable', + fontfamily: 'fontFamily', + 'font-family': 'fontFamily', + fontsize: 'fontSize', + 'font-size': 'fontSize', + fontsizeadjust: 'fontSizeAdjust', + 'font-size-adjust': 'fontSizeAdjust', + fontstretch: 'fontStretch', + 'font-stretch': 'fontStretch', + fontstyle: 'fontStyle', + 'font-style': 'fontStyle', + fontvariant: 'fontVariant', + 'font-variant': 'fontVariant', + fontweight: 'fontWeight', + 'font-weight': 'fontWeight', + format: 'format', + from: 'from', + fx: 'fx', + fy: 'fy', + g1: 'g1', + g2: 'g2', + glyphname: 'glyphName', + 'glyph-name': 'glyphName', + glyphorientationhorizontal: 'glyphOrientationHorizontal', + 'glyph-orientation-horizontal': 'glyphOrientationHorizontal', + glyphorientationvertical: 'glyphOrientationVertical', + 'glyph-orientation-vertical': 'glyphOrientationVertical', + glyphref: 'glyphRef', + gradienttransform: 'gradientTransform', + gradientunits: 'gradientUnits', + hanging: 'hanging', + horizadvx: 'horizAdvX', + 'horiz-adv-x': 'horizAdvX', + horizoriginx: 'horizOriginX', + 'horiz-origin-x': 'horizOriginX', + ideographic: 'ideographic', + imagerendering: 'imageRendering', + 'image-rendering': 'imageRendering', + in2: 'in2', + in: 'in', + inlist: 'inlist', + intercept: 'intercept', + k1: 'k1', + k2: 'k2', + k3: 'k3', + k4: 'k4', + k: 'k', + kernelmatrix: 'kernelMatrix', + kernelunitlength: 'kernelUnitLength', + kerning: 'kerning', + keypoints: 'keyPoints', + keysplines: 'keySplines', + keytimes: 'keyTimes', + lengthadjust: 'lengthAdjust', + letterspacing: 'letterSpacing', + 'letter-spacing': 'letterSpacing', + lightingcolor: 'lightingColor', + 'lighting-color': 'lightingColor', + limitingconeangle: 'limitingConeAngle', + local: 'local', + markerend: 'markerEnd', + 'marker-end': 'markerEnd', + markerheight: 'markerHeight', + markermid: 'markerMid', + 'marker-mid': 'markerMid', + markerstart: 'markerStart', + 'marker-start': 'markerStart', + markerunits: 'markerUnits', + markerwidth: 'markerWidth', + mask: 'mask', + maskcontentunits: 'maskContentUnits', + maskunits: 'maskUnits', + mathematical: 'mathematical', + mode: 'mode', + numoctaves: 'numOctaves', + offset: 'offset', + opacity: 'opacity', + operator: 'operator', + order: 'order', + orient: 'orient', + orientation: 'orientation', + origin: 'origin', + overflow: 'overflow', + overlineposition: 'overlinePosition', + 'overline-position': 'overlinePosition', + overlinethickness: 'overlineThickness', + 'overline-thickness': 'overlineThickness', + paintorder: 'paintOrder', + 'paint-order': 'paintOrder', + panose1: 'panose1', + 'panose-1': 'panose1', + pathlength: 'pathLength', + patterncontentunits: 'patternContentUnits', + patterntransform: 'patternTransform', + patternunits: 'patternUnits', + pointerevents: 'pointerEvents', + 'pointer-events': 'pointerEvents', + points: 'points', + pointsatx: 'pointsAtX', + pointsaty: 'pointsAtY', + pointsatz: 'pointsAtZ', + prefix: 'prefix', + preservealpha: 'preserveAlpha', + preserveaspectratio: 'preserveAspectRatio', + primitiveunits: 'primitiveUnits', + property: 'property', + r: 'r', + radius: 'radius', + refx: 'refX', + refy: 'refY', + renderingintent: 'renderingIntent', + 'rendering-intent': 'renderingIntent', + repeatcount: 'repeatCount', + repeatdur: 'repeatDur', + requiredextensions: 'requiredExtensions', + requiredfeatures: 'requiredFeatures', + resource: 'resource', + restart: 'restart', + result: 'result', + results: 'results', + rotate: 'rotate', + rx: 'rx', + ry: 'ry', + scale: 'scale', + security: 'security', + seed: 'seed', + shaperendering: 'shapeRendering', + 'shape-rendering': 'shapeRendering', + slope: 'slope', + spacing: 'spacing', + specularconstant: 'specularConstant', + specularexponent: 'specularExponent', + speed: 'speed', + spreadmethod: 'spreadMethod', + startoffset: 'startOffset', + stddeviation: 'stdDeviation', + stemh: 'stemh', + stemv: 'stemv', + stitchtiles: 'stitchTiles', + stopcolor: 'stopColor', + 'stop-color': 'stopColor', + stopopacity: 'stopOpacity', + 'stop-opacity': 'stopOpacity', + strikethroughposition: 'strikethroughPosition', + 'strikethrough-position': 'strikethroughPosition', + strikethroughthickness: 'strikethroughThickness', + 'strikethrough-thickness': 'strikethroughThickness', + string: 'string', + stroke: 'stroke', + strokedasharray: 'strokeDasharray', + 'stroke-dasharray': 'strokeDasharray', + strokedashoffset: 'strokeDashoffset', + 'stroke-dashoffset': 'strokeDashoffset', + strokelinecap: 'strokeLinecap', + 'stroke-linecap': 'strokeLinecap', + strokelinejoin: 'strokeLinejoin', + 'stroke-linejoin': 'strokeLinejoin', + strokemiterlimit: 'strokeMiterlimit', + 'stroke-miterlimit': 'strokeMiterlimit', + strokewidth: 'strokeWidth', + 'stroke-width': 'strokeWidth', + strokeopacity: 'strokeOpacity', + 'stroke-opacity': 'strokeOpacity', + suppresscontenteditablewarning: 'suppressContentEditableWarning', + suppresshydrationwarning: 'suppressHydrationWarning', + surfacescale: 'surfaceScale', + systemlanguage: 'systemLanguage', + tablevalues: 'tableValues', + targetx: 'targetX', + targety: 'targetY', + textanchor: 'textAnchor', + 'text-anchor': 'textAnchor', + textdecoration: 'textDecoration', + 'text-decoration': 'textDecoration', + textlength: 'textLength', + textrendering: 'textRendering', + 'text-rendering': 'textRendering', + to: 'to', + transform: 'transform', + typeof: 'typeof', + u1: 'u1', + u2: 'u2', + underlineposition: 'underlinePosition', + 'underline-position': 'underlinePosition', + underlinethickness: 'underlineThickness', + 'underline-thickness': 'underlineThickness', + unicode: 'unicode', + unicodebidi: 'unicodeBidi', + 'unicode-bidi': 'unicodeBidi', + unicoderange: 'unicodeRange', + 'unicode-range': 'unicodeRange', + unitsperem: 'unitsPerEm', + 'units-per-em': 'unitsPerEm', + unselectable: 'unselectable', + valphabetic: 'vAlphabetic', + 'v-alphabetic': 'vAlphabetic', + values: 'values', + vectoreffect: 'vectorEffect', + 'vector-effect': 'vectorEffect', + version: 'version', + vertadvy: 'vertAdvY', + 'vert-adv-y': 'vertAdvY', + vertoriginx: 'vertOriginX', + 'vert-origin-x': 'vertOriginX', + vertoriginy: 'vertOriginY', + 'vert-origin-y': 'vertOriginY', + vhanging: 'vHanging', + 'v-hanging': 'vHanging', + videographic: 'vIdeographic', + 'v-ideographic': 'vIdeographic', + viewbox: 'viewBox', + viewtarget: 'viewTarget', + visibility: 'visibility', + vmathematical: 'vMathematical', + 'v-mathematical': 'vMathematical', + vocab: 'vocab', + widths: 'widths', + wordspacing: 'wordSpacing', + 'word-spacing': 'wordSpacing', + writingmode: 'writingMode', + 'writing-mode': 'writingMode', + x1: 'x1', + x2: 'x2', + x: 'x', + xchannelselector: 'xChannelSelector', + xheight: 'xHeight', + 'x-height': 'xHeight', + xlinkactuate: 'xlinkActuate', + 'xlink:actuate': 'xlinkActuate', + xlinkarcrole: 'xlinkArcrole', + 'xlink:arcrole': 'xlinkArcrole', + xlinkhref: 'xlinkHref', + 'xlink:href': 'xlinkHref', + xlinkrole: 'xlinkRole', + 'xlink:role': 'xlinkRole', + xlinkshow: 'xlinkShow', + 'xlink:show': 'xlinkShow', + xlinktitle: 'xlinkTitle', + 'xlink:title': 'xlinkTitle', + xlinktype: 'xlinkType', + 'xlink:type': 'xlinkType', + xmlbase: 'xmlBase', + 'xml:base': 'xmlBase', + xmllang: 'xmlLang', + 'xml:lang': 'xmlLang', + xmlns: 'xmlns', + 'xml:space': 'xmlSpace', + xmlnsxlink: 'xmlnsXlink', + 'xmlns:xlink': 'xmlnsXlink', + xmlspace: 'xmlSpace', + y1: 'y1', + y2: 'y2', + y: 'y', + ychannelselector: 'yChannelSelector', + z: 'z', + zoomandpan: 'zoomAndPan' +}; + +var validateProperty$1 = function () {}; + +{ + var warnedProperties$1 = {}; + var EVENT_NAME_REGEX = /^on./; + var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; + var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); + var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); + + validateProperty$1 = function (tagName, name, value, eventRegistry) { + if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { + return true; + } + + var lowerCasedName = name.toLowerCase(); + + if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') { + error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); + + warnedProperties$1[name] = true; + return true; + } // We can't rely on the event system being injected on the server. + + + if (eventRegistry != null) { + var registrationNameDependencies = eventRegistry.registrationNameDependencies, + possibleRegistrationNames = eventRegistry.possibleRegistrationNames; + + if (registrationNameDependencies.hasOwnProperty(name)) { + return true; + } + + var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; + + if (registrationName != null) { + error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName); + + warnedProperties$1[name] = true; + return true; + } + + if (EVENT_NAME_REGEX.test(name)) { + error('Unknown event handler property `%s`. It will be ignored.', name); + + warnedProperties$1[name] = true; + return true; + } + } else if (EVENT_NAME_REGEX.test(name)) { + // If no event plugins have been injected, we are in a server environment. + // So we can't tell if the event name is correct for sure, but we can filter + // out known bad ones like `onclick`. We can't suggest a specific replacement though. + if (INVALID_EVENT_NAME_REGEX.test(name)) { + error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name); + } + + warnedProperties$1[name] = true; + return true; + } // Let the ARIA attribute hook validate ARIA attributes + + + if (rARIA$1.test(name) || rARIACamel$1.test(name)) { + return true; + } + + if (lowerCasedName === 'innerhtml') { + error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); + + warnedProperties$1[name] = true; + return true; + } + + if (lowerCasedName === 'aria') { + error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.'); + + warnedProperties$1[name] = true; + return true; + } + + if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') { + error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value); + + warnedProperties$1[name] = true; + return true; + } + + if (typeof value === 'number' && isNaN(value)) { + error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name); + + warnedProperties$1[name] = true; + return true; + } + + var propertyInfo = getPropertyInfo(name); + var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config. + + if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { + var standardName = possibleStandardNames[lowerCasedName]; + + if (standardName !== name) { + error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName); + + warnedProperties$1[name] = true; + return true; + } + } else if (!isReserved && name !== lowerCasedName) { + // Unknown attributes should have lowercase casing since that's how they + // will be cased anyway with server rendering. + error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName); + + warnedProperties$1[name] = true; + return true; + } + + if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + if (value) { + error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name); + } else { + error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); + } + + warnedProperties$1[name] = true; + return true; + } // Now that we've validated casing, do not validate + // data types for reserved props + + + if (isReserved) { + return true; + } // Warn when a known attribute is a bad type + + + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + warnedProperties$1[name] = true; + return false; + } // Warn when passing the strings 'false' or 'true' into a boolean prop + + + if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) { + error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value); + + warnedProperties$1[name] = true; + return true; + } + + return true; + }; +} + +var warnUnknownProperties = function (type, props, eventRegistry) { + { + var unknownProps = []; + + for (var key in props) { + var isValid = validateProperty$1(type, key, props[key], eventRegistry); + + if (!isValid) { + unknownProps.push(key); + } + } + + var unknownPropString = unknownProps.map(function (prop) { + return '`' + prop + '`'; + }).join(', '); + + if (unknownProps.length === 1) { + error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); + } else if (unknownProps.length > 1) { + error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); + } + } +}; + +function validateProperties$2(type, props, eventRegistry) { + if (isCustomComponent(type, props)) { + return; + } + + warnUnknownProperties(type, props, eventRegistry); +} + +var warnValidStyle = function () {}; + +{ + // 'msTransform' is correct, but the other prefixes should be capitalized + var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; + var msPattern = /^-ms-/; + var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon + + var badStyleValueWithSemicolonPattern = /;\s*$/; + var warnedStyleNames = {}; + var warnedStyleValues = {}; + var warnedForNaNValue = false; + var warnedForInfinityValue = false; + + var camelize = function (string) { + return string.replace(hyphenPattern, function (_, character) { + return character.toUpperCase(); + }); + }; + + var warnHyphenatedStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + + error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests + // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix + // is converted to lowercase `ms`. + camelize(name.replace(msPattern, 'ms-'))); + }; + + var warnBadVendoredStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + + error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)); + }; + + var warnStyleValueWithSemicolon = function (name, value) { + if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { + return; + } + + warnedStyleValues[value] = true; + + error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')); + }; + + var warnStyleValueIsNaN = function (name, value) { + if (warnedForNaNValue) { + return; + } + + warnedForNaNValue = true; + + error('`NaN` is an invalid value for the `%s` css style property.', name); + }; + + var warnStyleValueIsInfinity = function (name, value) { + if (warnedForInfinityValue) { + return; + } + + warnedForInfinityValue = true; + + error('`Infinity` is an invalid value for the `%s` css style property.', name); + }; + + warnValidStyle = function (name, value) { + if (name.indexOf('-') > -1) { + warnHyphenatedStyleName(name); + } else if (badVendoredStyleNamePattern.test(name)) { + warnBadVendoredStyleName(name); + } else if (badStyleValueWithSemicolonPattern.test(value)) { + warnStyleValueWithSemicolon(name, value); + } + + if (typeof value === 'number') { + if (isNaN(value)) { + warnStyleValueIsNaN(name, value); + } else if (!isFinite(value)) { + warnStyleValueIsInfinity(name, value); + } + } + }; +} + +var warnValidStyle$1 = warnValidStyle; + +// code copied and modified from escape-html +var matchHtmlRegExp = /["'&<>]/; +/** + * Escapes special characters and HTML entities in a given html string. + * + * @param {string} string HTML string to escape for later insertion + * @return {string} + * @public + */ + +function escapeHtml(string) { + { + checkHtmlStringCoercion(string); + } + + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: + // " + escape = '"'; + break; + + case 38: + // & + escape = '&'; + break; + + case 39: + // ' + escape = '''; // modified from escape-html; used to be ''' + + break; + + case 60: + // < + escape = '<'; + break; + + case 62: + // > + escape = '>'; + break; + + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index ? html + str.substring(lastIndex, index) : html; +} // end code copied and modified from escape-html + +/** + * Escapes text to prevent scripting attacks. + * + * @param {*} text Text value to escape. + * @return {string} An escaped string. + */ + + +function escapeTextForBrowser(text) { + if (typeof text === 'boolean' || typeof text === 'number') { + // this shortcircuit helps perf for types that we know will never have + // special characters, especially given that this function is used often + // for numeric dom ids. + return '' + text; + } + + return escapeHtml(text); +} + +var uppercasePattern = /([A-Z])/g; +var msPattern$1 = /^ms-/; +/** + * Hyphenates a camelcased CSS property name, for example: + * + * > hyphenateStyleName('backgroundColor') + * < "background-color" + * > hyphenateStyleName('MozTransition') + * < "-moz-transition" + * > hyphenateStyleName('msTransition') + * < "-ms-transition" + * + * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix + * is converted to `-ms-`. + */ + +function hyphenateStyleName(name) { + return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-'); +} + +// and any newline or tab are filtered out as if they're not part of the URL. +// https://url.spec.whatwg.org/#url-parsing +// Tab or newline are defined as \r\n\t: +// https://infra.spec.whatwg.org/#ascii-tab-or-newline +// A C0 control is a code point in the range \u0000 NULL to \u001F +// INFORMATION SEPARATOR ONE, inclusive: +// https://infra.spec.whatwg.org/#c0-control-or-space + +/* eslint-disable max-len */ + +var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; +var didWarn = false; + +function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + + error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); + } + } +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +var assign = Object.assign; + +function validatePreloadResourceDifference(originalProps, originalImplicit, latestProps, latestImplicit) { + { + var href = originalProps.href; + var originalWarningName = getResourceNameForWarning('preload', originalProps, originalImplicit); + var latestWarningName = getResourceNameForWarning('preload', latestProps, latestImplicit); + + if (latestProps.as !== originalProps.as) { + error('A %s is using the same href "%s" as a %s. This is always an error and React will only keep the first preload' + ' for any given href, discarding subsequent instances. To fix, find where you are using this href in link' + ' tags or in calls to ReactDOM.preload() or ReactDOM.preinit() and either make the Resource types agree or' + ' update the hrefs to be distinct for different Resource types.', latestWarningName, href, originalWarningName); + } else { + var missingProps = null; + var extraProps = null; + var differentProps = null; + + if (originalProps.media != null && latestProps.media == null) { + missingProps = missingProps || {}; + missingProps.media = originalProps.media; + } + + for (var propName in latestProps) { + var propValue = latestProps[propName]; + var originalValue = originalProps[propName]; + + if (propValue != null && propValue !== originalValue) { + if (originalValue == null) { + extraProps = extraProps || {}; + extraProps[propName] = propValue; + } else { + differentProps = differentProps || {}; + differentProps[propName] = { + original: originalValue, + latest: propValue + }; + } + } + } + + if (missingProps || extraProps || differentProps) { + warnDifferentProps(href, originalWarningName, latestWarningName, extraProps, missingProps, differentProps); + } + } + } +} +function validateStyleResourceDifference(originalProps, latestProps) { + { + var href = originalProps.href; // eslint-disable-next-line no-labels + + var originalWarningName = getResourceNameForWarning('style', originalProps, false); + var latestWarningName = getResourceNameForWarning('style', latestProps, false); + var missingProps = null; + var extraProps = null; + var differentProps = null; + + if (originalProps.media != null && latestProps.media == null) { + missingProps = missingProps || {}; + missingProps.media = originalProps.media; + } + + for (var propName in latestProps) { + var propValue = latestProps[propName]; + var originalValue = originalProps[propName]; + + if (propValue != null && propValue !== originalValue) { + propName = propName === 'data-rprec' ? 'precedence' : propName; + + if (originalValue == null) { + extraProps = extraProps || {}; + extraProps[propName] = propValue; + } else { + differentProps = differentProps || {}; + differentProps[propName] = { + original: originalValue, + latest: propValue + }; + } + } + } + + if (missingProps || extraProps || differentProps) { + warnDifferentProps(href, originalWarningName, latestWarningName, extraProps, missingProps, differentProps); + } + } +} +function validateStyleAndHintProps(preloadProps, styleProps, implicitPreload) { + { + var href = preloadProps.href; + var originalWarningName = getResourceNameForWarning('preload', preloadProps, implicitPreload); + var latestWarningName = getResourceNameForWarning('style', styleProps, false); + + if (preloadProps.as !== 'style') { + error('While creating a %s for href "%s" a %s for this same href was found. When preloading a stylesheet the' + ' "as" prop must be of type "style". This most likely ocurred by rending a preload link with an incorrect' + ' "as" prop or by calling ReactDOM.preload with an incorrect "as" option.', latestWarningName, href, originalWarningName); + } + + var missingProps = null; + var extraProps = null; + var differentProps = null; + + for (var propName in styleProps) { + var styleValue = styleProps[propName]; + var preloadValue = preloadProps[propName]; + + switch (propName) { + // Check for difference on specific props that cross over or influence + // the relationship between the preload and stylesheet + case 'crossOrigin': + case 'referrerPolicy': + case 'media': + case 'title': + { + if (preloadValue !== styleValue && !(preloadValue == null && styleValue == null)) { + if (styleValue == null) { + missingProps = missingProps || {}; + missingProps[propName] = preloadValue; + } else if (preloadValue == null) { + extraProps = extraProps || {}; + extraProps[propName] = styleValue; + } else { + differentProps = differentProps || {}; + differentProps[propName] = { + original: preloadValue, + latest: styleValue + }; + } + } + } + } + } + + if (missingProps || extraProps || differentProps) { + warnDifferentProps(href, originalWarningName, latestWarningName, extraProps, missingProps, differentProps); + } + } +} + +function warnDifferentProps(href, originalName, latestName, extraProps, missingProps, differentProps) { + { + var juxtaposedNameStatement = latestName === originalName ? 'an earlier instance of this Resource' : "a " + originalName + " with the same href"; + var comparisonStatement = ''; + + if (missingProps !== null && typeof missingProps === 'object') { + for (var propName in missingProps) { + comparisonStatement += "\n " + propName + ": missing or null in latest props, \"" + missingProps[propName] + "\" in original props"; + } + } + + if (extraProps !== null && typeof extraProps === 'object') { + for (var _propName in extraProps) { + comparisonStatement += "\n " + _propName + ": \"" + extraProps[_propName] + "\" in latest props, missing or null in original props"; + } + } + + if (differentProps !== null && typeof differentProps === 'object') { + for (var _propName2 in differentProps) { + comparisonStatement += "\n " + _propName2 + ": \"" + differentProps[_propName2].latest + "\" in latest props, \"" + differentProps[_propName2].original + "\" in original props"; + } + } + + error('A %s with href "%s" has props that disagree with those found on %s. Resources always use the props' + ' that were provided the first time they are encountered so any differences will be ignored. Please' + ' update Resources that share an href to have props that agree. The differences are described below.%s', latestName, href, juxtaposedNameStatement, comparisonStatement); + } +} + +function getResourceNameForWarning(type, props, implicit) { + { + switch (type) { + case 'style': + { + return 'style Resource'; + } + + case 'preload': + { + if (implicit) { + return "preload for a " + props.as + " Resource"; + } + + return "preload Resource (as \"" + props.as + "\")"; + } + } + } + + return 'Resource'; +} +function validateLinkPropsForStyleResource(props) { + { + // This should only be called when we know we are opting into Resource semantics (i.e. precedence is not null) + var href = props.href, + onLoad = props.onLoad, + onError = props.onError, + disabled = props.disabled; + var allProps = ['onLoad', 'onError', 'disabled']; + var includedProps = []; + if (onLoad) includedProps.push('onLoad'); + if (onError) includedProps.push('onError'); + if (disabled != null) includedProps.push('disabled'); + var allPropsUnionPhrase = propNamesListJoin(allProps, 'or'); + var includedPropsPhrase = propNamesListJoin(includedProps, 'and'); + includedPropsPhrase += includedProps.length === 1 ? ' prop' : ' props'; + + if (includedProps.length) { + error('A link (rel="stylesheet") element with href "%s" has the precedence prop but also included the %s.' + ' When using %s React will opt out of Resource behavior. If you meant for this' + ' element to be treated as a Resource remove the %s. Otherwise remove the precedence prop.', href, includedPropsPhrase, allPropsUnionPhrase, includedPropsPhrase); + + return true; + } + } + + return false; +} + +function propNamesListJoin(list, combinator) { + switch (list.length) { + case 0: + return ''; + + case 1: + return list[0]; + + case 2: + return list[0] + ' ' + combinator + ' ' + list[1]; + + default: + return list.slice(0, -1).join(', ') + ', ' + combinator + ' ' + list[list.length - 1]; + } +} + +function validateLinkPropsForPreloadResource(linkProps) { + { + var href = linkProps.href, + as = linkProps.as; + + if (as === 'font') { + var name = getResourceNameForWarning('preload', linkProps, false); + + if (!hasOwnProperty.call(linkProps, 'crossOrigin')) { + error('A %s with href "%s" did not specify the crossOrigin prop. Font preloads must always use' + ' anonymouse CORS mode. To fix add an empty string, "anonymous", or any other string' + ' value except "use-credentials" for the crossOrigin prop of all font preloads.', name, href); + } else if (linkProps.crossOrigin === 'use-credentials') { + error('A %s with href "%s" specified a crossOrigin value of "use-credentials". Font preloads must always use' + ' anonymouse CORS mode. To fix use an empty string, "anonymous", or any other string' + ' value except "use-credentials" for the crossOrigin prop of all font preloads.', name, href); + } + } + } +} +function validatePreloadArguments(href, options) { + { + if (!href || typeof href !== 'string') { + var typeOfArg = getValueDescriptorExpectingObjectForWarning(href); + + error('ReactDOM.preload() expected the first argument to be a string representing an href but found %s instead.', typeOfArg); + } else if (typeof options !== 'object' || options === null) { + var _typeOfArg = getValueDescriptorExpectingObjectForWarning(options); + + error('ReactDOM.preload() expected the second argument to be an options argument containing at least an "as" property' + ' specifying the Resource type. It found %s instead. The href for the preload call where this warning originated is "%s".', _typeOfArg, href); + } else { + var as = options.as; + + switch (as) { + // Font specific validation of options + case 'font': + { + if (options.crossOrigin === 'use-credentials') { + error('ReactDOM.preload() was called with an "as" type of "font" and with a "crossOrigin" option of "use-credentials".' + ' Fonts preloading must use crossOrigin "anonymous" to be functional. Please update your font preload to omit' + ' the crossOrigin option or change it to any other value than "use-credentials" (Browsers default all other values' + ' to anonymous mode). The href for the preload call where this warning originated is "%s"', href); + } + + break; + } + + case 'script': + case 'style': + { + break; + } + // We have an invalid as type and need to warn + + default: + { + var typeOfAs = getValueDescriptorExpectingEnumForWarning(as); + + error('ReactDOM.preload() expected a valid "as" type in the options (second) argument but found %s instead.' + ' Please use one of the following valid values instead: %s. The href for the preload call where this' + ' warning originated is "%s".', typeOfAs, '"style", "font", or "script"', href); + } + } + } + } +} +function validatePreinitArguments(href, options) { + { + if (!href || typeof href !== 'string') { + var typeOfArg = getValueDescriptorExpectingObjectForWarning(href); + + error('ReactDOM.preinit() expected the first argument to be a string representing an href but found %s instead.', typeOfArg); + } else if (typeof options !== 'object' || options === null) { + var _typeOfArg2 = getValueDescriptorExpectingObjectForWarning(options); + + error('ReactDOM.preinit() expected the second argument to be an options argument containing at least an "as" property' + ' specifying the Resource type. It found %s instead. The href for the preload call where this warning originated is "%s".', _typeOfArg2, href); + } else { + var as = options.as; + + switch (as) { + case 'style': + { + break; + } + // We have an invalid as type and need to warn + + default: + { + var typeOfAs = getValueDescriptorExpectingEnumForWarning(as); + + error('ReactDOM.preinit() expected the second argument to be an options argument containing at least an "as" property' + ' specifying the Resource type. It found %s instead. Currently, the only valid resource type for preinit is "style".' + ' The href for the preinit call where this warning originated is "%s".', typeOfAs, href); + } + } + } + } +} + +function getValueDescriptorExpectingObjectForWarning(thing) { + return thing === null ? 'null' : thing === undefined ? 'undefined' : thing === '' ? 'an empty string' : "something with type \"" + typeof thing + "\""; +} + +function getValueDescriptorExpectingEnumForWarning(thing) { + return thing === null ? 'null' : thing === undefined ? 'undefined' : thing === '' ? 'an empty string' : typeof thing === 'string' ? JSON.stringify(thing) : "something with type \"" + typeof thing + "\""; +} + +// @TODO add bootstrap script to implicit preloads +function createResources() { + return { + // persistent + preloadsMap: new Map(), + stylesMap: new Map(), + // cleared on flush + explicitPreloads: new Set(), + implicitPreloads: new Set(), + precedences: new Map(), + // like a module global for currently rendering boundary + boundaryResources: null + }; +} +function createBoundaryResources() { + return new Set(); +} +function mergeBoundaryResources(target, source) { + source.forEach(function (resource) { + return target.add(resource); + }); +} +var currentResources = null; +var currentResourcesStack = []; +function prepareToRenderResources(resources) { + currentResourcesStack.push(currentResources); + currentResources = resources; +} +function finishRenderingResources() { + currentResources = currentResourcesStack.pop(); +} +function setCurrentlyRenderingBoundaryResourcesTarget(resources, boundaryResources) { + resources.boundaryResources = boundaryResources; +} +var ReactDOMServerDispatcher = { + preload: preload, + preinit: preinit +}; + +function preload(href, options) { + if (!currentResources) { + // While we expect that preload calls are primarily going to be observed + // during render because effects and events don't run on the server it is + // still possible that these get called in module scope. This is valid on + // the client since there is still a document to interact with but on the + // server we need a request to associate the call to. Because of this we + // simply return and do not warn. + return; + } + + { + validatePreloadArguments(href, options); + } + + if (typeof href === 'string' && href && typeof options === 'object' && options !== null) { + var as = options.as; // $FlowFixMe[incompatible-use] found when upgrading Flow + + var resource = currentResources.preloadsMap.get(href); + + if (resource) { + { + var originallyImplicit = resource._dev_implicit_construction === true; + var latestProps = preloadPropsFromPreloadOptions(href, as, options); + validatePreloadResourceDifference(resource.props, originallyImplicit, latestProps, false); + } + } else { + resource = createPreloadResource( // $FlowFixMe[incompatible-call] found when upgrading Flow + currentResources, href, as, preloadPropsFromPreloadOptions(href, as, options)); + } // $FlowFixMe[incompatible-call] found when upgrading Flow + + + captureExplicitPreloadResourceDependency(currentResources, resource); + } +} + +function preinit(href, options) { + if (!currentResources) { + // While we expect that preinit calls are primarily going to be observed + // during render because effects and events don't run on the server it is + // still possible that these get called in module scope. This is valid on + // the client since there is still a document to interact with but on the + // server we need a request to associate the call to. Because of this we + // simply return and do not warn. + return; + } + + { + validatePreinitArguments(href, options); + } + + if (typeof href === 'string' && href && typeof options === 'object' && options !== null) { + var as = options.as; + + switch (as) { + case 'style': + { + var precedence = options.precedence || 'default'; // $FlowFixMe[incompatible-use] found when upgrading Flow + + var resource = currentResources.stylesMap.get(href); + + if (resource) { + { + var latestProps = stylePropsFromPreinitOptions(href, precedence, options); + validateStyleResourceDifference(resource.props, latestProps); + } + } else { + var resourceProps = stylePropsFromPreinitOptions(href, precedence, options); + resource = createStyleResource( // $FlowFixMe[incompatible-call] found when upgrading Flow + currentResources, href, precedence, resourceProps); + } // Do not associate preinit style resources with any specific boundary regardless of where it is called + // $FlowFixMe[incompatible-call] found when upgrading Flow + + + captureStyleResourceDependency(currentResources, null, resource); + return; + } + } + } +} + +function preloadPropsFromPreloadOptions(href, as, options) { + return { + href: href, + rel: 'preload', + as: as, + crossOrigin: as === 'font' ? '' : options.crossOrigin, + integrity: options.integrity + }; +} + +function preloadPropsFromRawProps(href, as, rawProps) { + var props = assign({}, rawProps); + + props.href = href; + props.rel = 'preload'; + props.as = as; + + if (as === 'font') { + // Font preloads always need CORS anonymous mode so we set it here + // regardless of the props provided. This should warn elsewhere in + // dev + props.crossOrigin = ''; + } + + return props; +} + +function preloadAsStylePropsFromProps(href, props) { + return { + rel: 'preload', + as: 'style', + href: href, + crossOrigin: props.crossOrigin, + integrity: props.integrity, + media: props.media, + hrefLang: props.hrefLang, + referrerPolicy: props.referrerPolicy + }; +} + +function createPreloadResource(resources, href, as, props) { + var preloadsMap = resources.preloadsMap; + + { + if (preloadsMap.has(href)) { + error('createPreloadResource was called when a preload Resource matching the same href already exists. This is a bug in React.'); + } + } + + var resource = { + type: 'preload', + as: as, + href: href, + flushed: false, + props: props + }; + preloadsMap.set(href, resource); + return resource; +} + +function stylePropsFromRawProps(href, precedence, rawProps) { + var props = assign({}, rawProps); + + props.href = href; + props.rel = 'stylesheet'; + props['data-rprec'] = precedence; + delete props.precedence; + return props; +} + +function stylePropsFromPreinitOptions(href, precedence, options) { + return { + rel: 'stylesheet', + href: href, + 'data-rprec': precedence, + crossOrigin: options.crossOrigin + }; +} + +function createStyleResource(resources, href, precedence, props) { + { + if (resources.stylesMap.has(href)) { + error('createStyleResource was called when a style Resource matching the same href already exists. This is a bug in React.'); + } + } + + var stylesMap = resources.stylesMap, + preloadsMap = resources.preloadsMap; + var hint = preloadsMap.get(href); + + if (hint) { + // If a preload for this style Resource already exists there are certain props we want to adopt + // on the style Resource, primarily focussed on making sure the style network pathways utilize + // the preload pathways. For instance if you have diffreent crossOrigin attributes for a preload + // and a stylesheet the stylesheet will make a new request even if the preload had already loaded + var preloadProps = hint.props; + if (props.crossOrigin == null) props.crossOrigin = preloadProps.crossOrigin; + if (props.referrerPolicy == null) props.referrerPolicy = preloadProps.referrerPolicy; + if (props.media == null) props.media = preloadProps.media; + if (props.title == null) props.title = preloadProps.title; + + { + validateStyleAndHintProps(preloadProps, props, hint._dev_implicit_construction); + } + } else { + var preloadResourceProps = preloadAsStylePropsFromProps(href, props); + hint = createPreloadResource(resources, href, 'style', preloadResourceProps); + + { + hint._dev_implicit_construction = true; + } + + captureImplicitPreloadResourceDependency(resources, hint); + } + + var resource = { + type: 'style', + href: href, + precedence: precedence, + flushed: false, + inShell: false, + props: props, + hint: hint + }; + stylesMap.set(href, resource); + return resource; +} + +function captureStyleResourceDependency(resources, boundaryResources, styleResource) { + var precedences = resources.precedences; + var precedence = styleResource.precedence; + + if (boundaryResources) { + boundaryResources.add(styleResource); + + if (!precedences.has(precedence)) { + precedences.set(precedence, new Set()); + } + } else { + var set = precedences.get(precedence); + + if (!set) { + set = new Set(); + precedences.set(precedence, set); + } + + set.add(styleResource); + } +} + +function captureExplicitPreloadResourceDependency(resources, preloadResource) { + resources.explicitPreloads.add(preloadResource); +} + +function captureImplicitPreloadResourceDependency(resources, preloadResource) { + resources.implicitPreloads.add(preloadResource); +} // Construct a resource from link props. + + +function resourcesFromLink(props) { + if (!currentResources) { + throw new Error('"currentResources" was expected to exist. This is a bug in React.'); + } + + var rel = props.rel, + href = props.href; + + if (!href || typeof href !== 'string') { + return false; + } + + switch (rel) { + case 'stylesheet': + { + var onLoad = props.onLoad, + onError = props.onError, + precedence = props.precedence, + disabled = props.disabled; + + if (typeof precedence !== 'string' || onLoad || onError || disabled != null) { + // This stylesheet is either not opted into Resource semantics or has conflicting properties which + // disqualify it for such. We can still create a preload resource to help it load faster on the + // client + { + validateLinkPropsForStyleResource(props); + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + + var preloadResource = currentResources.preloadsMap.get(href); + + if (!preloadResource) { + preloadResource = createPreloadResource( // $FlowFixMe[incompatible-call] found when upgrading Flow + currentResources, href, 'style', preloadAsStylePropsFromProps(href, props)); + + { + preloadResource._dev_implicit_construction = true; + } + } + + captureImplicitPreloadResourceDependency( // $FlowFixMe[incompatible-call] found when upgrading Flow + currentResources, preloadResource); + return false; + } else { + // We are able to convert this link element to a resource exclusively. We construct the relevant Resource + // and return true indicating that this link was fully consumed. + var resource = currentResources.stylesMap.get(href); + + if (resource) { + { + var resourceProps = stylePropsFromRawProps(href, precedence, props); + validateStyleResourceDifference(resource.props, resourceProps); + } + } else { + var _resourceProps = stylePropsFromRawProps(href, precedence, props); + + resource = createStyleResource( // $FlowFixMe[incompatible-call] found when upgrading Flow + currentResources, href, precedence, _resourceProps); + } + + captureStyleResourceDependency( // $FlowFixMe[incompatible-call] found when upgrading Flow + currentResources, // $FlowFixMe[incompatible-use] found when upgrading Flow + currentResources.boundaryResources, resource); + return true; + } + } + + case 'preload': + { + var as = props.as, + _onLoad = props.onLoad, + _onError = props.onError; + + if (_onLoad || _onError) { + // these props signal an opt-out of Resource semantics. We don't warn because there is no + // conflicting opt-in like there is with Style Resources + return false; + } + + switch (as) { + case 'script': + case 'style': + case 'font': + { + { + validateLinkPropsForPreloadResource(props); + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + + var _resource = currentResources.preloadsMap.get(href); + + if (_resource) { + { + var originallyImplicit = _resource._dev_implicit_construction === true; + var latestProps = preloadPropsFromRawProps(href, as, props); + validatePreloadResourceDifference(_resource.props, originallyImplicit, latestProps, false); + } + } else { + _resource = createPreloadResource( // $FlowFixMe[incompatible-call] found when upgrading Flow + currentResources, href, as, preloadPropsFromRawProps(href, as, props)); + } // $FlowFixMe[incompatible-call] found when upgrading Flow + + + captureExplicitPreloadResourceDependency(currentResources, _resource); + return true; + } + } + + return false; + } + } + + return false; +} +function hoistResources(resources, source) { + if (resources.boundaryResources) { + mergeBoundaryResources(resources.boundaryResources, source); + source.clear(); + } +} +function hoistResourcesToRoot(resources, boundaryResources) { + boundaryResources.forEach(function (resource) { + // all precedences are set upon discovery. so we know we will have a set here + var set = resources.precedences.get(resource.precedence); + set.add(resource); + }); + boundaryResources.clear(); +} + +var ReactDOMSharedInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +var ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher; +function prepareToRender(resources) { + prepareToRenderResources(resources); + var previousHostDispatcher = ReactDOMCurrentDispatcher.current; + ReactDOMCurrentDispatcher.current = ReactDOMServerDispatcher; + return previousHostDispatcher; +} +function cleanupAfterRender(previousDispatcher) { + finishRenderingResources(); + ReactDOMCurrentDispatcher.current = previousDispatcher; +} // Used to distinguish these contexts from ones used in other renderers. + +var startInlineScript = stringToPrecomputedChunk(''); +var startScriptSrc = stringToPrecomputedChunk(''); +/** + * This escaping function is designed to work with bootstrapScriptContent only. + * because we know we are escaping the entire script. We can avoid for instance + * escaping html comment string sequences that are valid javascript as well because + * if there are no sebsequent '); +function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentCompleteSegmentFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentCompleteSegmentFunction = true; + writeChunk(destination, completeSegmentScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, completeSegmentScript1Partial); + } + + writeChunk(destination, responseState.segmentPrefix); + var formattedID = stringToChunk(contentSegmentID.toString(16)); + writeChunk(destination, formattedID); + writeChunk(destination, completeSegmentScript2); + writeChunk(destination, responseState.placeholderPrefix); + writeChunk(destination, formattedID); + return writeChunkAndReturn(destination, completeSegmentScript3); +} +var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("'); +var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("'); +var completeBoundaryWithStylesScript1FullBoth = stringToPrecomputedChunk(completeBoundaryFunction + ';' + styleInsertionFunction + ';$RR("'); +var completeBoundaryWithStylesScript1FullPartial = stringToPrecomputedChunk(styleInsertionFunction + ';$RR("'); +var completeBoundaryWithStylesScript1Partial = stringToPrecomputedChunk('$RR("'); +var completeBoundaryScript2 = stringToPrecomputedChunk('","'); +var completeBoundaryScript2a = stringToPrecomputedChunk('",'); +var completeBoundaryScript3 = stringToPrecomputedChunk('"'); +var completeBoundaryScript4 = stringToPrecomputedChunk(')'); +function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID, boundaryResources) { + var hasStyleDependencies; + + { + hasStyleDependencies = hasStyleResourceDependencies(boundaryResources); + } + + writeChunk(destination, responseState.startInlineScript); + + if ( hasStyleDependencies) { + if (!responseState.sentCompleteBoundaryFunction) { + responseState.sentCompleteBoundaryFunction = true; + responseState.sentStyleInsertionFunction = true; + writeChunk(destination, completeBoundaryWithStylesScript1FullBoth); + } else if (!responseState.sentStyleInsertionFunction) { + responseState.sentStyleInsertionFunction = true; + writeChunk(destination, completeBoundaryWithStylesScript1FullPartial); + } else { + writeChunk(destination, completeBoundaryWithStylesScript1Partial); + } + } else { + if (!responseState.sentCompleteBoundaryFunction) { + responseState.sentCompleteBoundaryFunction = true; + writeChunk(destination, completeBoundaryScript1Full); + } else { + writeChunk(destination, completeBoundaryScript1Partial); + } + } + + if (boundaryID === null) { + throw new Error('An ID must have been assigned before we can complete the boundary.'); + } + + var formattedContentID = stringToChunk(contentSegmentID.toString(16)); + writeChunk(destination, boundaryID); + writeChunk(destination, completeBoundaryScript2); + writeChunk(destination, responseState.segmentPrefix); + writeChunk(destination, formattedContentID); + + if ( hasStyleDependencies) { + writeChunk(destination, completeBoundaryScript2a); + writeStyleResourceDependencies(destination, boundaryResources); + } else { + writeChunk(destination, completeBoundaryScript3); + } + + return writeChunkAndReturn(destination, completeBoundaryScript4); +} +var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("'); +var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("'); +var clientRenderScript1A = stringToPrecomputedChunk('"'); +var clientRenderScript2 = stringToPrecomputedChunk(')'); +var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(','); +function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentClientRenderFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentClientRenderFunction = true; + writeChunk(destination, clientRenderScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, clientRenderScript1Partial); + } + + if (boundaryID === null) { + throw new Error('An ID must have been assigned before we can complete the boundary.'); + } + + writeChunk(destination, boundaryID); + writeChunk(destination, clientRenderScript1A); + + if (errorDigest || errorMessage || errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || ''))); + } + + if (errorMessage || errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || ''))); + } + + if (errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack))); + } + + return writeChunkAndReturn(destination, clientRenderScript2); +} +var regexForJSStringsInInstructionScripts = /[<\u2028\u2029]/g; + +function escapeJSStringsForInstructionScripts(input) { + var escaped = JSON.stringify(input); + return escaped.replace(regexForJSStringsInInstructionScripts, function (match) { + switch (match) { + // santizing breaking out of strings and script tags + case '<': + return "\\u003c"; + + case "\u2028": + return "\\u2028"; + + case "\u2029": + return "\\u2029"; + + default: + { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React'); + } + } + }); +} + +var regexForJSStringsInScripts = /[&><\u2028\u2029]/g; + +function escapeJSObjectForInstructionScripts(input) { + var escaped = JSON.stringify(input); + return escaped.replace(regexForJSStringsInScripts, function (match) { + switch (match) { + // santizing breaking out of strings and script tags + case '&': + return "\\u0026"; + + case '>': + return "\\u003e"; + + case '<': + return "\\u003c"; + + case "\u2028": + return "\\u2028"; + + case "\u2029": + return "\\u2029"; + + default: + { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React'); + } + } + }); +} + +function writeInitialResources(destination, resources, responseState) { + var explicitPreloadsTarget = []; + var remainingTarget = []; + var precedences = resources.precedences, + explicitPreloads = resources.explicitPreloads, + implicitPreloads = resources.implicitPreloads; // Flush stylesheets first by earliest precedence + + precedences.forEach(function (precedenceResources) { + precedenceResources.forEach(function (resource) { + // resources should not already be flushed so we elide this check + pushLinkImpl(remainingTarget, resource.props, responseState); + resource.flushed = true; + resource.inShell = true; + resource.hint.flushed = true; + }); + }); + explicitPreloads.forEach(function (resource) { + if (!resource.flushed) { + pushLinkImpl(explicitPreloadsTarget, resource.props, responseState); + resource.flushed = true; + } + }); + explicitPreloads.clear(); + implicitPreloads.forEach(function (resource) { + if (!resource.flushed) { + pushLinkImpl(remainingTarget, resource.props, responseState); + resource.flushed = true; + } + }); + implicitPreloads.clear(); + var i; + var r = true; + + for (i = 0; i < explicitPreloadsTarget.length - 1; i++) { + writeChunk(destination, explicitPreloadsTarget[i]); + } + + if (i < explicitPreloadsTarget.length) { + r = writeChunkAndReturn(destination, explicitPreloadsTarget[i]); + } + + for (i = 0; i < remainingTarget.length - 1; i++) { + writeChunk(destination, remainingTarget[i]); + } + + if (i < remainingTarget.length) { + r = writeChunkAndReturn(destination, remainingTarget[i]); + } + + return r; +} +function writeImmediateResources(destination, resources, responseState) { + var explicitPreloads = resources.explicitPreloads, + implicitPreloads = resources.implicitPreloads; + var target = []; + explicitPreloads.forEach(function (resource) { + if (!resource.flushed) { + pushLinkImpl(target, resource.props, responseState); + resource.flushed = true; + } + }); + explicitPreloads.clear(); + implicitPreloads.forEach(function (resource) { + if (!resource.flushed) { + pushLinkImpl(target, resource.props, responseState); + resource.flushed = true; + } + }); + implicitPreloads.clear(); + var i = 0; + + for (; i < target.length - 1; i++) { + writeChunk(destination, target[i]); + } + + if (i < target.length) { + return writeChunkAndReturn(destination, target[i]); + } + + return false; +} + +function hasStyleResourceDependencies(boundaryResources) { + var iter = boundaryResources.values(); // At the moment boundaries only accumulate style resources + // so we assume the type is correct and don't check it + + while (true) { + var _iter$next = iter.next(), + resource = _iter$next.value; + + if (!resource) break; // If every style Resource flushed in the shell we do not need to send + // any dependencies + + if (!resource.inShell) { + return true; + } + } + + return false; +} + +var arrayFirstOpenBracket = stringToPrecomputedChunk('['); +var arraySubsequentOpenBracket = stringToPrecomputedChunk(',['); +var arrayInterstitial = stringToPrecomputedChunk(','); +var arrayCloseBracket = stringToPrecomputedChunk(']'); + +function writeStyleResourceDependencies(destination, boundaryResources) { + writeChunk(destination, arrayFirstOpenBracket); + var nextArrayOpenBrackChunk = arrayFirstOpenBracket; + boundaryResources.forEach(function (resource) { + if (resource.inShell) ; else if (resource.flushed) { + writeChunk(destination, nextArrayOpenBrackChunk); + writeStyleResourceDependencyHrefOnly(destination, resource.href); + writeChunk(destination, arrayCloseBracket); + nextArrayOpenBrackChunk = arraySubsequentOpenBracket; + } else { + writeChunk(destination, nextArrayOpenBrackChunk); + writeStyleResourceDependency(destination, resource.href, resource.precedence, resource.props); + writeChunk(destination, arrayCloseBracket); + nextArrayOpenBrackChunk = arraySubsequentOpenBracket; + resource.flushed = true; + resource.hint.flushed = true; + } + }); + writeChunk(destination, arrayCloseBracket); +} + +function writeStyleResourceDependencyHrefOnly(destination, href) { + // We should actually enforce this earlier when the resource is created but for + // now we make sure we are actually dealing with a string here. + { + checkAttributeStringCoercion(href, 'href'); + } + + var coercedHref = '' + href; + writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(coercedHref))); +} + +function writeStyleResourceDependency(destination, href, precedence, props) { + { + checkAttributeStringCoercion(href, 'href'); + } + + var coercedHref = '' + href; + sanitizeURL(coercedHref); + writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(coercedHref))); + + { + checkAttributeStringCoercion(precedence, 'precedence'); + } + + var coercedPrecedence = '' + precedence; + writeChunk(destination, arrayInterstitial); + writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(coercedPrecedence))); + + for (var propKey in props) { + if (hasOwnProperty.call(props, propKey)) { + var propValue = props[propKey]; + + if (propValue == null) { + continue; + } + + switch (propKey) { + case 'href': + case 'rel': + case 'precedence': + case 'data-rprec': + { + break; + } + + case 'children': + case 'dangerouslySetInnerHTML': + throw new Error('link' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.'); + // eslint-disable-next-line-no-fallthrough + + default: + writeStyleResourceAttribute(destination, propKey, propValue); + break; + } + } + } + + return null; +} + +function writeStyleResourceAttribute(destination, name, value) { + var attributeName = name.toLowerCase(); + var attributeValue; + + switch (typeof value) { + case 'function': + case 'symbol': + return; + } + + switch (name) { + // Reserved names + case 'innerHTML': + case 'dangerouslySetInnerHTML': + case 'suppressContentEditableWarning': + case 'suppressHydrationWarning': + case 'style': + // Ignored + return; + // Attribute renames + + case 'className': + attributeName = 'class'; + break; + // Booleans + + case 'hidden': + if (value === false) { + return; + } + + attributeValue = ''; + break; + // Santized URLs + + case 'src': + case 'href': + { + { + checkAttributeStringCoercion(value, attributeName); + } + + attributeValue = '' + value; + sanitizeURL(attributeValue); + break; + } + + default: + { + if (!isAttributeNameSafe(name)) { + return; + } + } + } + + if ( // shouldIgnoreAttribute + // We have already filtered out null/undefined and reserved words. + name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { + return; + } + + { + checkAttributeStringCoercion(value, attributeName); + } + + attributeValue = '' + value; + writeChunk(destination, arrayInterstitial); + writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(attributeName))); + writeChunk(destination, arrayInterstitial); + writeChunk(destination, stringToChunk(escapeJSObjectForInstructionScripts(attributeValue))); +} + +function createResponseState$1(generateStaticMarkup, identifierPrefix) { + var responseState = createResponseState(identifierPrefix, undefined); + return { + // Keep this in sync with ReactDOMServerFormatConfig + bootstrapChunks: responseState.bootstrapChunks, + startInlineScript: responseState.startInlineScript, + placeholderPrefix: responseState.placeholderPrefix, + segmentPrefix: responseState.segmentPrefix, + boundaryPrefix: responseState.boundaryPrefix, + idPrefix: responseState.idPrefix, + nextSuspenseID: responseState.nextSuspenseID, + sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction, + sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction, + sentClientRenderFunction: responseState.sentClientRenderFunction, + sentStyleInsertionFunction: responseState.sentStyleInsertionFunction, + // This is an extra field for the legacy renderer + generateStaticMarkup: generateStaticMarkup + }; +} +function createRootFormatContext() { + return { + insertionMode: HTML_MODE, + // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode. + selectedValue: null + }; +} +function pushTextInstance$1(target, text, responseState, textEmbedded) { + if (responseState.generateStaticMarkup) { + target.push(stringToChunk(escapeTextForBrowser(text))); + return false; + } else { + return pushTextInstance(target, text, responseState, textEmbedded); + } +} +function pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) { + if (responseState.generateStaticMarkup) { + return; + } else { + return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded); + } +} +function writeStartCompletedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + // A completed boundary is done and doesn't need a representation in the HTML + // if we're not going to be hydrating it. + return true; + } + + return writeStartCompletedSuspenseBoundary(destination); +} +function writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format. +errorDigest, errorMessage, errorComponentStack) { + if (responseState.generateStaticMarkup) { + // A client rendered boundary is done and doesn't need a representation in the HTML + // since we'll never hydrate it. This is arguably an error in static generation. + return true; + } + + return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack); +} +function writeEndCompletedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + return true; + } + + return writeEndCompletedSuspenseBoundary(destination); +} +function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + return true; + } + + return writeEndClientRenderedSuspenseBoundary(destination); +} + +// 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_PORTAL_TYPE = Symbol.for('react.portal'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); +var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_CONTEXT_TYPE = Symbol.for('react.context'); +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_SCOPE_TYPE = Symbol.for('react.scope'); +var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); +var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); +var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); +var REACT_CACHE_TYPE = Symbol.for('react.cache'); +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; +} + +function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; +} // Keep in sync with react-reconciler/getComponentNameFromFiber + + +function getContextName(type) { + return type.displayName || 'Context'; +} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + +function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + case REACT_CACHE_TYPE: + { + return 'Cache'; + } + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + case REACT_SERVER_CONTEXT_TYPE: + { + var context2 = type; + return (context2.displayName || context2._globalName) + '.Provider'; + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; +} + +// Helpers to patch console.logs to avoid logging during side-effect free +// replaying on render function. This currently only patches the object +// lazily which won't cover if the log function was extracted eagerly. +// We could also eagerly patch the method. +var disabledDepth = 0; +var prevLog; +var prevInfo; +var prevWarn; +var prevError; +var prevGroup; +var prevGroupCollapsed; +var prevGroupEnd; + +function disabledLog() {} + +disabledLog.__reactDisabledLog = true; +function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } +} +function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } +} + +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var prefix; +function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } +} +var reentry = false; +var componentFrameCache; + +{ + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); +} + +function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } // $FlowFixMe[prop-missing] found when upgrading Flow + + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } // TODO(luna): This will currently only throw if the function component + // tries to access React/ReactDOM/props. We should probably make this throw + // in simple components too + + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; +} + +function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } +} +function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } +} + +function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); +} + +function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; +} + +var loggedTypeFailures = {}; +var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } +} + +function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } +} + +var warnedAboutMissingGetChildContext; + +{ + warnedAboutMissingGetChildContext = {}; +} // $FlowFixMe[incompatible-exact] + + +var emptyContextObject = {}; + +{ + Object.freeze(emptyContextObject); +} + +function getMaskedContext(type, unmaskedContext) { + { + var contextTypes = type.contextTypes; + + if (!contextTypes) { + return emptyContextObject; + } + + var context = {}; + + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; + } + + { + var name = getComponentNameFromType(type) || 'Unknown'; + checkPropTypes(contextTypes, context, 'context', name); + } + + return context; + } +} +function processChildContext(instance, type, parentContext, childContextTypes) { + { + // TODO (bvaughn) Replace this behavior with an invariant() in the future. + // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== 'function') { + { + var componentName = getComponentNameFromType(type) || 'Unknown'; + + if (!warnedAboutMissingGetChildContext[componentName]) { + warnedAboutMissingGetChildContext[componentName] = true; + + error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); + } + } + + return parentContext; + } + + var childContext = instance.getChildContext(); + + for (var contextKey in childContext) { + if (!(contextKey in childContextTypes)) { + throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); + } + } + + { + var name = getComponentNameFromType(type) || 'Unknown'; + checkPropTypes(childContextTypes, childContext, 'child context', name); + } + + return assign({}, parentContext, childContext); + } +} + +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. + + +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._currentValue2 = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue2 = 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: 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._currentValue2; + context._currentValue2 = nextValue; + + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer2 = 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(context) { + 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.'); + } + + { + if (prevSnapshot.context !== context) { + error('The parent context is not the expected context. This is probably a bug in React.'); + } + } + + { + var _value = prevSnapshot.parentValue; + + if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue2 = _value; + } + + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer2 = rendererSigil; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext(context) { + var value = context._currentValue2; + return value; +} + +/** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ +function get(key) { + return key._reactInternals; +} +function set(key, value) { + key._reactInternals = value; +} + +var didWarnAboutNoopUpdateForComponent = {}; +var didWarnAboutDeprecatedWillMount = {}; +var didWarnAboutUninitializedState; +var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; +var didWarnAboutLegacyLifecyclesAndDerivedState; +var didWarnAboutUndefinedDerivedState; +var warnOnUndefinedDerivedState; +var warnOnInvalidCallback; +var didWarnAboutDirectlyAssigningPropsToState; +var didWarnAboutContextTypeAndContextTypes; +var didWarnAboutInvalidateContextType; + +{ + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + var didWarnOnInvalidCallback = new Set(); + + warnOnInvalidCallback = function (callback, callerName) { + if (callback === null || typeof callback === 'function') { + return; + } + + var key = callerName + '_' + callback; + + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); + + error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); + } + }; + + warnOnUndefinedDerivedState = function (type, partialState) { + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || 'Component'; + + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); + + error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); + } + } + }; +} + +function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass'; + var warningKey = componentName + '.' + callerName; + + if (didWarnAboutNoopUpdateForComponent[warningKey]) { + return; + } + + error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName); + + didWarnAboutNoopUpdateForComponent[warningKey] = true; + } +} + +var classComponentUpdater = { + isMounted: function (inst) { + return false; + }, + enqueueSetState: function (inst, payload, callback) { + var internals = get(inst); + + if (internals.queue === null) { + warnNoop(inst, 'setState'); + } else { + internals.queue.push(payload); + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + } + }, + enqueueReplaceState: function (inst, payload, callback) { + var internals = get(inst); + internals.replace = true; + internals.queue = [payload]; + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + }, + enqueueForceUpdate: function (inst, callback) { + var internals = get(inst); + + if (internals.queue === null) { + warnNoop(inst, 'forceUpdate'); + } else { + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + } + } +}; + +function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) { + var partialState = getDerivedStateFromProps(nextProps, prevState); + + { + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. + + + var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); + return newState; +} + +function constructClassInstance(ctor, props, maskedLegacyContext) { + var context = emptyContextObject; + var contextType = ctor.contextType; + + { + if ('contextType' in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a + + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ''; + + if (contextType === undefined) { + addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; + } else if (typeof contextType !== 'object') { + addendum = ' However, it is set to a ' + typeof contextType + '.'; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = ' Did you accidentally pass the Context.Provider instead?'; + } else if (contextType._context !== undefined) { + // + addendum = ' Did you accidentally pass the Context.Consumer instead?'; + } else { + addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; + } + + error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); + } + } + } + + if (typeof contextType === 'object' && contextType !== null) { + context = readContext(contextType); + } else { + context = maskedLegacyContext; + } + + var instance = new ctor(props, context); + + { + if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) { + var componentName = getComponentNameFromType(ctor) || 'Component'; + + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); + + error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); + } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. + + + if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; + + if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { + foundWillMountName = 'componentWillMount'; + } else if (typeof instance.UNSAFE_componentWillMount === 'function') { + foundWillMountName = 'UNSAFE_componentWillMount'; + } + + if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + foundWillReceivePropsName = 'componentWillReceiveProps'; + } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; + } + + if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + foundWillUpdateName = 'componentWillUpdate'; + } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { + foundWillUpdateName = 'UNSAFE_componentWillUpdate'; + } + + if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { + var _componentName = getComponentNameFromType(ctor) || 'Component'; + + var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; + + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + + error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); + } + } + } + } + + return instance; +} + +function checkClassInstance(instance, ctor, newProps) { + { + var name = getComponentNameFromType(ctor) || 'Component'; + var renderPresent = instance.render; + + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === 'function') { + error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); + } else { + error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); + } + } + + if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { + error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); + } + + if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { + error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); + } + + if (instance.propTypes) { + error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); + } + + if (instance.contextType) { + error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); + } + + { + if (instance.contextTypes) { + error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); + } + + if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { + didWarnAboutContextTypeAndContextTypes.add(ctor); + + error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); + } + } + + if (typeof instance.componentShouldUpdate === 'function') { + error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); + } + + if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { + error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); + } + + if (typeof instance.componentDidUnmount === 'function') { + error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); + } + + if (typeof instance.componentDidReceiveProps === 'function') { + error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); + } + + if (typeof instance.componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); + } + + if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); + } + + var hasMutatedProps = instance.props !== newProps; + + if (instance.props !== undefined && hasMutatedProps) { + error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); + } + + if (instance.defaultProps) { + error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); + } + + if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); + + error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); + } + + if (typeof instance.getDerivedStateFromProps === 'function') { + error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } + + if (typeof instance.getDerivedStateFromError === 'function') { + error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } + + if (typeof ctor.getSnapshotBeforeUpdate === 'function') { + error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); + } + + var _state = instance.state; + + if (_state && (typeof _state !== 'object' || isArray(_state))) { + error('%s.state: must be set to an object or null', name); + } + + if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { + error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); + } + } +} + +function callComponentWillMount(type, instance) { + var oldState = instance.state; + + if (typeof instance.componentWillMount === 'function') { + { + if ( instance.componentWillMount.__suppressDeprecationWarning !== true) { + var componentName = getComponentNameFromType(type) || 'Unknown'; + + if (!didWarnAboutDeprecatedWillMount[componentName]) { + warn( // keep this warning in sync with ReactStrictModeWarning.js + 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName); + + didWarnAboutDeprecatedWillMount[componentName] = true; + } + } + } + + instance.componentWillMount(); + } + + if (typeof instance.UNSAFE_componentWillMount === 'function') { + instance.UNSAFE_componentWillMount(); + } + + if (oldState !== instance.state) { + { + error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component'); + } + + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } +} + +function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) { + if (internalInstance.queue !== null && internalInstance.queue.length > 0) { + var oldQueue = internalInstance.queue; + var oldReplace = internalInstance.replace; + internalInstance.queue = null; + internalInstance.replace = false; + + if (oldReplace && oldQueue.length === 1) { + inst.state = oldQueue[0]; + } else { + var nextState = oldReplace ? oldQueue[0] : inst.state; + var dontMutate = true; + + for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { + var partial = oldQueue[i]; + var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial; + + if (partialState != null) { + if (dontMutate) { + dontMutate = false; + nextState = assign({}, nextState, partialState); + } else { + assign(nextState, partialState); + } + } + } + + inst.state = nextState; + } + } else { + internalInstance.queue = null; + } +} // Invokes the mount life-cycles on a previously never rendered instance. + + +function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { + { + checkClassInstance(instance, ctor, newProps); + } + + var initialState = instance.state !== undefined ? instance.state : null; + instance.updater = classComponentUpdater; + instance.props = newProps; + instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. + // The internal instance will be used to manage updates that happen during this mount. + + var internalInstance = { + queue: [], + replace: false + }; + set(instance, internalInstance); + var contextType = ctor.contextType; + + if (typeof contextType === 'object' && contextType !== null) { + instance.context = readContext(contextType); + } else { + instance.context = maskedLegacyContext; + } + + { + if (instance.state === newProps) { + var componentName = getComponentNameFromType(ctor) || 'Component'; + + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); + + error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); + } + } + } + + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + + if (typeof getDerivedStateFromProps === 'function') { + instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps); + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. + + + if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { + callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's + // process them now. + + processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext); + } +} + +// Ids are base 32 strings whose binary representation corresponds to the +// position of a node in a tree. +// Every time the tree forks into multiple children, we add additional bits to +// the left of the sequence that represent the position of the child within the +// current level of children. +// +// 00101 00010001011010101 +// ╰─┬─╯ ╰───────┬───────╯ +// Fork 5 of 20 Parent id +// +// The leading 0s are important. In the above example, you only need 3 bits to +// represent slot 5. However, you need 5 bits to represent all the forks at +// the current level, so we must account for the empty bits at the end. +// +// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise, +// the zeroth id at a level would be indistinguishable from its parent. +// +// If a node has only one child, and does not materialize an id (i.e. does not +// contain a useId hook), then we don't need to allocate any space in the +// sequence. It's treated as a transparent indirection. For example, these two +// trees produce the same ids: +// +// <> <> +// +// +// +// +// +// +// However, we cannot skip any node that materializes an id. Otherwise, a parent +// id that does not fork would be indistinguishable from its child id. For +// example, this tree does not fork, but the parent and child must have +// different ids. +// +// +// +// +// +// To handle this scenario, every time we materialize an id, we allocate a +// new level with a single slot. You can think of this as a fork with only one +// prong, or an array of children with length 1. +// +// It's possible for the size of the sequence to exceed 32 bits, the max +// size for bitwise operations. When this happens, we make more room by +// converting the right part of the id to a string and storing it in an overflow +// variable. We use a base 32 string representation, because 32 is the largest +// power of 2 that is supported by toString(). We want the base to be large so +// that the resulting ids are compact, and we want the base to be a power of 2 +// because every log2(base) bits corresponds to a single character, i.e. every +// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without +// affecting the final result. +var emptyTreeContext = { + id: 1, + overflow: '' +}; +function getTreeId(context) { + var overflow = context.overflow; + var idWithLeadingBit = context.id; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; +} +function pushTreeContext(baseContext, totalChildren, index) { + var baseIdWithLeadingBit = baseContext.id; + var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. + + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. + + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. + + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. + + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. + + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. + + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + return { + id: 1 << restOfLength | id, + overflow: overflow + }; + } else { + // Normal path + var newBits = slot << baseLength; + + var _id = newBits | baseId; + + var _overflow = baseOverflow; + return { + id: 1 << length | _id, + overflow: _overflow + }; + } +} + +function getBitLength(number) { + return 32 - clz32(number); +} + +function getLeadingBit(id) { + return 1 << getBitLength(id) - 1; +} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. + + +var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. +// Based on: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 + +var log = Math.log; +var LN2 = Math.LN2; + +function clz32Fallback(x) { + var asUint = x >>> 0; + + if (asUint === 0) { + return 32; + } + + return 31 - (log(asUint) / LN2 | 0) | 0; +} + +// Corresponds to ReactFiberWakeable and ReactFlightWakeable 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. +// TODO: Sparse arrays are bad for performance. +function createThenableState() { + // The ThenableState is created the first time a component suspends. If it + // suspends again, we'll reuse the same state. + return []; +} +function trackSuspendedWakeable(wakeable) { + // If this wakeable isn't already a thenable, turn it into one now. Then, + // when we resume the work loop, we can check if its status is + // still pending. + // TODO: Get rid of the Wakeable type? It's superseded by UntrackedThenable. + var thenable = wakeable; // 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': + case 'rejected': + // A thenable that already resolved shouldn't have been thrown, so this is + // unexpected. Suggests a mistake in a userspace data library. Don't track + // this thenable, because if we keep trying it will likely infinite loop + // without ever resolving. + // TODO: Log a warning? + 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; + } + } +} +function trackUsedThenable(thenableState, thenable, index) { + // This is only a separate function from trackSuspendedWakeable for symmetry + // with Fiber. + thenableState[index] = thenable; +} +function getPreviouslyUsedThenableAtIndex(thenableState, index) { + if (thenableState !== null) { + var thenable = thenableState[index]; + + if (thenable !== undefined) { + return thenable; + } + } + + return null; +} + +/** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ +function is(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare + ; +} + +var objectIs = // $FlowFixMe[method-unbinding] +typeof Object.is === 'function' ? Object.is : is; + +var currentlyRenderingComponent = null; +var currentlyRenderingTask = null; +var firstWorkInProgressHook = null; +var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook + +var isReRender = false; // Whether an update was scheduled during the currently executing render pass. + +var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component + +var localIdCounter = 0; // Counts the number of use(thenable) calls in this component + +var thenableIndexCounter = 0; +var thenableState = null; // Lazily created map of render-phase updates + +var renderPhaseUpdates = null; // Counter to prevent infinite loops. + +var numberOfReRenders = 0; +var RE_RENDER_LIMIT = 25; +var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook + +var currentHookNameInDev; + +function resolveCurrentlyRenderingComponent() { + if (currentlyRenderingComponent === null) { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } + + { + if (isInHookUserCodeInDev) { + error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); + } + } + + return currentlyRenderingComponent; +} + +function areHookInputsEqual(nextDeps, prevDeps) { + if (prevDeps === null) { + { + error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); + } + + return false; + } + + { + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]"); + } + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } + + return false; + } + + return true; +} + +function createHook() { + if (numberOfReRenders > 0) { + throw new Error('Rendered more hooks than during the previous render'); + } + + return { + memoizedState: null, + queue: null, + next: null + }; +} + +function createWorkInProgressHook() { + if (workInProgressHook === null) { + // This is the first hook in the list + if (firstWorkInProgressHook === null) { + isReRender = false; + firstWorkInProgressHook = workInProgressHook = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = firstWorkInProgressHook; + } + } else { + if (workInProgressHook.next === null) { + isReRender = false; // Append to the end of the list + + workInProgressHook = workInProgressHook.next = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = workInProgressHook.next; + } + } + + return workInProgressHook; +} + +function prepareToUseHooks(task, componentIdentity, prevThenableState) { + currentlyRenderingComponent = componentIdentity; + currentlyRenderingTask = task; + + { + isInHookUserCodeInDev = false; + } // The following should have already been reset + // didScheduleRenderPhaseUpdate = false; + // firstWorkInProgressHook = null; + // numberOfReRenders = 0; + // renderPhaseUpdates = null; + // workInProgressHook = null; + + + localIdCounter = 0; + thenableIndexCounter = 0; + thenableState = prevThenableState; +} +function finishHooks(Component, props, children, refOrContext) { + // This must be called after every function component to prevent hooks from + // being used in classes. + while (didScheduleRenderPhaseUpdate) { + // Updates were scheduled during the render phase. They are stored in + // the `renderPhaseUpdates` map. Call the component again, reusing the + // work-in-progress hooks and applying the additional updates on top. Keep + // restarting until no more updates are scheduled. + didScheduleRenderPhaseUpdate = false; + localIdCounter = 0; + thenableIndexCounter = 0; + numberOfReRenders += 1; // Start over from the beginning of the list + + workInProgressHook = null; + children = Component(props, refOrContext); + } + + resetHooksState(); + return children; +} +function getThenableStateAfterSuspending() { + var state = thenableState; + thenableState = null; + return state; +} +function checkDidRenderIdHook() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + return didRenderIdHook; +} // Reset the internal hooks state if an error occurs while rendering a component + +function resetHooksState() { + { + isInHookUserCodeInDev = false; + } + + currentlyRenderingComponent = null; + currentlyRenderingTask = null; + didScheduleRenderPhaseUpdate = false; + firstWorkInProgressHook = null; + numberOfReRenders = 0; + renderPhaseUpdates = null; + workInProgressHook = null; +} + +function readContext$1(context) { + { + if (isInHookUserCodeInDev) { + 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(context); +} + +function useContext(context) { + { + currentHookNameInDev = 'useContext'; + } + + resolveCurrentlyRenderingComponent(); + return readContext(context); +} + +function basicStateReducer(state, action) { + // $FlowFixMe: Flow doesn't like mixed types + return typeof action === 'function' ? action(state) : action; +} + +function useState(initialState) { + { + currentHookNameInDev = 'useState'; + } + + return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers + initialState); +} +function useReducer(reducer, initialArg, init) { + { + if (reducer !== basicStateReducer) { + currentHookNameInDev = 'useReducer'; + } + } + + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + + if (isReRender) { + // This is a re-render. Apply the new render phase updates to the previous + // current hook. + var queue = workInProgressHook.queue; + var dispatch = queue.dispatch; + + if (renderPhaseUpdates !== null) { + // Render phase updates are stored in a map of queue -> linked list + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + + if (firstRenderPhaseUpdate !== undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.delete(queue); // $FlowFixMe[incompatible-use] found when upgrading Flow + + var newState = workInProgressHook.memoizedState; + var update = firstRenderPhaseUpdate; + + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; + + { + isInHookUserCodeInDev = true; + } + + newState = reducer(newState, action); + + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-type] we bail out when we get a null + + + update = update.next; + } while (update !== null); // $FlowFixMe[incompatible-use] found when upgrading Flow + + + workInProgressHook.memoizedState = newState; + return [newState, dispatch]; + } + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + + return [workInProgressHook.memoizedState, dispatch]; + } else { + { + isInHookUserCodeInDev = true; + } + + var initialState; + + if (reducer === basicStateReducer) { + // Special case for `useState`. + initialState = typeof initialArg === 'function' ? initialArg() : initialArg; + } else { + initialState = init !== undefined ? init(initialArg) : initialArg; + } + + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + + workInProgressHook.memoizedState = initialState; // $FlowFixMe[incompatible-use] found when upgrading Flow + + var _queue = workInProgressHook.queue = { + last: null, + dispatch: null + }; + + var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue); // $FlowFixMe[incompatible-use] found when upgrading Flow + + + return [workInProgressHook.memoizedState, _dispatch]; + } +} + +function useMemo(nextCreate, deps) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + + if (workInProgressHook !== null) { + var prevState = workInProgressHook.memoizedState; + + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; + + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } + } + + { + isInHookUserCodeInDev = true; + } + + var nextValue = nextCreate(); + + { + isInHookUserCodeInDev = false; + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + + workInProgressHook.memoizedState = [nextValue, nextDeps]; + return nextValue; +} + +function useRef(initialValue) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var previousRef = workInProgressHook.memoizedState; + + if (previousRef === null) { + var ref = { + current: initialValue + }; + + { + Object.seal(ref); + } // $FlowFixMe[incompatible-use] found when upgrading Flow + + + workInProgressHook.memoizedState = ref; + return ref; + } else { + return previousRef; + } +} + +function useLayoutEffect(create, inputs) { + { + currentHookNameInDev = 'useLayoutEffect'; + + error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.'); + } +} + +function dispatchAction(componentIdentity, queue, action) { + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); + } + + if (componentIdentity === currentlyRenderingComponent) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdate = true; + var update = { + action: action, + next: null + }; + + if (renderPhaseUpdates === null) { + renderPhaseUpdates = new Map(); + } + + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + + if (firstRenderPhaseUpdate === undefined) { + // $FlowFixMe[incompatible-use] found when upgrading Flow + renderPhaseUpdates.set(queue, update); + } else { + // Append the update to the end of the list. + var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + + while (lastRenderPhaseUpdate.next !== null) { + lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; + } + + lastRenderPhaseUpdate.next = update; + } + } +} + +function useCallback(callback, deps) { + return useMemo(function () { + return callback; + }, deps); +} + +function throwOnUseEventCall() { + throw new Error("A function wrapped in useEvent can't be called during rendering."); +} + +function useEvent(callback) { + return throwOnUseEventCall; +} // TODO Decide on how to implement this hook for server rendering. +// If a mutation occurs during render, consider triggering a Suspense boundary +// and falling back to client rendering. + +function useMutableSource(source, getSnapshot, subscribe) { + resolveCurrentlyRenderingComponent(); + return getSnapshot(source._source); +} + +function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + if (getServerSnapshot === undefined) { + throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); + } + + return getServerSnapshot(); +} + +function useDeferredValue(value) { + resolveCurrentlyRenderingComponent(); + return value; +} + +function unsupportedStartTransition() { + throw new Error('startTransition cannot be called during server rendering.'); +} + +function useTransition() { + resolveCurrentlyRenderingComponent(); + return [false, unsupportedStartTransition]; +} + +function useId() { + var task = currentlyRenderingTask; + var treeId = getTreeId(task.treeContext); + var responseState = currentResponseState; + + if (responseState === null) { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.'); + } + + var localId = localIdCounter++; + return makeId(responseState, treeId, localId); +} + +function use(usable) { + if (usable !== null && typeof usable === 'object') { + // $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; + + switch (thenable.status) { + case 'fulfilled': + { + var fulfilledValue = thenable.value; + return fulfilledValue; + } + + case 'rejected': + { + var rejectedError = thenable.reason; + throw rejectedError; + } + + default: + { + var prevThenableAtIndex = getPreviouslyUsedThenableAtIndex(thenableState, index); + + if (prevThenableAtIndex !== null) { + switch (prevThenableAtIndex.status) { + case 'fulfilled': + { + var _fulfilledValue = prevThenableAtIndex.value; + return _fulfilledValue; + } + + case 'rejected': + { + var _rejectedError = prevThenableAtIndex.reason; + throw _rejectedError; + } + + default: + { + // The thenable still hasn't resolved. Suspend with the same + // thenable as last time to avoid redundant listeners. + throw prevThenableAtIndex; + } + } + } else { + // This is the first time something has been used at this index. + // Stash the thenable at the current index so we can reuse it during + // the next attempt. + if (thenableState === null) { + thenableState = createThenableState(); + } + + trackUsedThenable(thenableState, thenable, index); // Suspend. + // TODO: 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. + + throw thenable; + } + } + } + } else if (usable.$$typeof === REACT_CONTEXT_TYPE || usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) { + var context = usable; + return readContext$1(context); + } + } // eslint-disable-next-line react-internal/safe-string-coercion + + + throw new Error('An unsupported type was passed to use(): ' + String(usable)); +} + +function unsupportedRefresh() { + throw new Error('Cache cannot be refreshed during server rendering.'); +} + +function useCacheRefresh() { + return unsupportedRefresh; +} + +function useMemoCache(size) { + return new Array(size); +} + +function noop() {} + +var HooksDispatcher = { + readContext: readContext$1, + useContext: useContext, + useMemo: useMemo, + useReducer: useReducer, + useRef: useRef, + useState: useState, + useInsertionEffect: noop, + useLayoutEffect: useLayoutEffect, + useCallback: useCallback, + // useImperativeHandle is not run in the server environment + useImperativeHandle: noop, + // Effects are not run in the server environment. + useEffect: noop, + // Debugging effect + useDebugValue: noop, + useDeferredValue: useDeferredValue, + useTransition: useTransition, + useId: useId, + // Subscriptions are not setup in a server environment. + useMutableSource: useMutableSource, + useSyncExternalStore: useSyncExternalStore +}; + +{ + HooksDispatcher.useCacheRefresh = useCacheRefresh; +} + +{ + HooksDispatcher.useEvent = useEvent; +} + +{ + HooksDispatcher.useMemoCache = useMemoCache; +} + +{ + HooksDispatcher.use = use; +} + +var currentResponseState = null; +function setCurrentResponseState(responseState) { + currentResponseState = responseState; +} + +function getCacheSignal() { + throw new Error('Not implemented.'); +} + +function getCacheForType(resourceType) { + throw new Error('Not implemented.'); +} + +var DefaultCacheDispatcher = { + getCacheSignal: getCacheSignal, + getCacheForType: getCacheForType +}; + +function getStackByComponentStackNode(componentStack) { + try { + var info = ''; + var node = componentStack; + + do { + switch (node.tag) { + case 0: + info += describeBuiltInComponentFrame(node.type, null, null); + break; + + case 1: + info += describeFunctionComponentFrame(node.type, null, null); + break; + + case 2: + info += describeClassComponentFrame(node.type, null, null); + break; + } // $FlowFixMe[incompatible-type] we bail out when we get a null + + + node = node.parent; + } while (node); + + return info; + } catch (x) { + return '\nError generating stack: ' + x.message + '\n' + x.stack; + } +} + +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var ReactCurrentCache = ReactSharedInternals.ReactCurrentCache; +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; +var PENDING = 0; +var COMPLETED = 1; +var FLUSHED = 2; +var ABORTED = 3; +var ERRORED = 4; +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +// This is a default heuristic for how to split up the HTML content into progressive +// loading. Our goal is to be able to display additional new content about every 500ms. +// Faster than that is unnecessary and should be throttled on the client. It also +// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower +// end device but higher end suffer less from the overhead than lower end does from +// not getting small enough pieces. We error on the side of low end. +// We base this on low end 3G speeds which is about 500kbits per second. We assume +// that there can be a reasonable drop off from max bandwidth which leaves you with +// as little as 80%. We can receive half of that each 500ms - at best. In practice, +// a little bandwidth is lost to processing and contention - e.g. CSS and images that +// are downloaded along with the main content. So we estimate about half of that to be +// the lower end throughput. In other words, we expect that you can at least show +// about 12.5kb of content per 500ms. Not counting starting latency for the first +// paint. +// 500 * 1024 / 8 * .8 * 0.5 / 2 +var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper + + return null; +} + +function noop$1() {} + +function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) { + var pingedTasks = []; + var abortSet = new Set(); + var resources = createResources(); + var request = { + destination: null, + responseState: responseState, + progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize, + status: OPEN, + fatalError: null, + nextSegmentId: 0, + allPendingTasks: 0, + pendingRootTasks: 0, + resources: resources, + completedRootSegment: null, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + clientRenderedBoundaries: [], + completedBoundaries: [], + partialBoundaries: [], + preamble: [], + postamble: [], + onError: onError === undefined ? defaultErrorHandler : onError, + onAllReady: onAllReady === undefined ? noop$1 : onAllReady, + onShellReady: onShellReady === undefined ? noop$1 : onShellReady, + onShellError: onShellError === undefined ? noop$1 : onShellError, + onFatalError: onFatalError === undefined ? noop$1 : onFatalError + }; // This segment represents the root fallback. + + var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge + false, false); // There is no parent so conceptually, we're unblocked to flush this segment. + + rootSegment.parentFlushed = true; + var rootTask = createTask(request, null, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext); + pingedTasks.push(rootTask); + return request; +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createSuspenseBoundary(request, fallbackAbortableTasks) { + return { + id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID, + rootSegmentID: -1, + parentFlushed: false, + pendingTasks: 0, + forceClientRender: false, + completedSegments: [], + byteSize: 0, + fallbackAbortableTasks: fallbackAbortableTasks, + errorDigest: null, + resources: createBoundaryResources() + }; +} + +function createTask(request, thenableState, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) { + request.allPendingTasks++; + + if (blockedBoundary === null) { + request.pendingRootTasks++; + } else { + blockedBoundary.pendingTasks++; + } + + var task = { + node: node, + ping: function () { + return pingTask(request, task); + }, + blockedBoundary: blockedBoundary, + blockedSegment: blockedSegment, + abortSet: abortSet, + legacyContext: legacyContext, + context: context, + treeContext: treeContext, + thenableState: thenableState + }; + + { + task.componentStack = null; + } + + abortSet.add(task); + return task; +} + +function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) { + return { + status: PENDING, + id: -1, + // lazily assigned later + index: index, + parentFlushed: false, + chunks: [], + children: [], + formatContext: formatContext, + boundary: boundary, + lastPushedText: lastPushedText, + textEmbedded: textEmbedded + }; +} // DEV-only global reference to the currently executing task + + +var currentTaskInDEV = null; + +function getCurrentStackInDEV() { + { + if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) { + return ''; + } + + return getStackByComponentStackNode(currentTaskInDEV.componentStack); + } +} + +function pushBuiltInComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 0, + parent: task.componentStack, + type: type + }; + } +} + +function pushFunctionComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 1, + parent: task.componentStack, + type: type + }; + } +} + +function pushClassComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 2, + parent: task.componentStack, + type: type + }; + } +} + +function popComponentStackInDEV(task) { + { + if (task.componentStack === null) { + error('Unexpectedly popped too many stack frames. This is a bug in React.'); + } else { + task.componentStack = task.componentStack.parent; + } + } +} // stash the component stack of an unwinding error until it is processed + + +var lastBoundaryErrorComponentStackDev = null; + +function captureBoundaryErrorDetailsDev(boundary, error) { + { + var errorMessage; + + if (typeof error === 'string') { + errorMessage = error; + } else if (error && typeof error.message === 'string') { + errorMessage = error.message; + } else { + // eslint-disable-next-line react-internal/safe-string-coercion + errorMessage = String(error); + } + + var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV(); + lastBoundaryErrorComponentStackDev = null; + boundary.errorMessage = errorMessage; + boundary.errorComponentStack = errorComponentStack; + } +} + +function logRecoverableError(request, error) { + // If this callback errors, we intentionally let that error bubble up to become a fatal error + // so that someone fixes the error reporting instead of hiding it. + var errorDigest = request.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 fatalError(request, error) { + // This is called outside error handling code such as if the root errors outside + // a suspense boundary or if the root suspense boundary's fallback errors. + // It's also called if React itself or its host configs errors. + var onShellError = request.onShellError; + onShellError(error); + var onFatalError = request.onFatalError; + onFatalError(error); + + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function renderSuspenseBoundary(request, task, props) { + pushBuiltInComponentStackInDEV(task, 'Suspense'); + var parentBoundary = task.blockedBoundary; + var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for + // the fallback so that we can later replace that segment with the content. + // This also lets us split out the main content even if it doesn't suspend, + // in case it ends up generating a large subtree of content. + + var fallback = props.fallback; + var content = props.children; + var fallbackAbortSet = new Set(); + var newBoundary = createSuspenseBoundary(request, fallbackAbortSet); + var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback. + + var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them + false, false); + parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent + + parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately. + + var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them + false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is + // no parent segment so there's nothing to wait on. + + contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks. + // I suspect that there might be some efficiency benefits from not creating the suspended task + // and instead just using the stack if possible. + // TODO: Call this directly instead of messing with saving and restoring contexts. + // We can reuse the current context and task to render the content immediately without + // context switching. We just need to temporarily switch which boundary and which segment + // we're writing to. If something suspends, it'll spawn new suspended task with that context. + + task.blockedBoundary = newBoundary; + task.blockedSegment = contentRootSegment; + + { + setCurrentlyRenderingBoundaryResourcesTarget(request.resources, newBoundary.resources); + } + + try { + // We use the safe form because we don't handle suspending here. Only error handling. + renderNode(request, task, content); + pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded); + contentRootSegment.status = COMPLETED; + + if (enableFloat) { + if (newBoundary.pendingTasks === 0) { + hoistCompletedBoundaryResources(request, newBoundary); + } + } + + queueCompletedSegment(newBoundary, contentRootSegment); + + if (newBoundary.pendingTasks === 0) { + // This must have been the last segment we were waiting on. This boundary is now complete. + // Therefore we won't need the fallback. We early return so that we don't have to create + // the fallback. + popComponentStackInDEV(task); + return; + } + } catch (error) { + contentRootSegment.status = ERRORED; + newBoundary.forceClientRender = true; + newBoundary.errorDigest = logRecoverableError(request, error); + + { + captureBoundaryErrorDetailsDev(newBoundary, error); + } // We don't need to decrement any task numbers because we didn't spawn any new task. + // We don't need to schedule any task because we know the parent has written yet. + // We do need to fallthrough to create the fallback though. + + } finally { + { + setCurrentlyRenderingBoundaryResourcesTarget(request.resources, parentBoundary ? parentBoundary.resources : null); + } + + task.blockedBoundary = parentBoundary; + task.blockedSegment = parentSegment; + } // We create suspended task for the fallback because we don't want to actually work + // on it yet in case we finish the main content, so we queue for later. + + + var suspendedFallbackTask = createTask(request, null, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext); + + { + suspendedFallbackTask.componentStack = task.componentStack; + } // TODO: This should be queued at a separate lower priority queue so that we only work + // on preparing fallbacks if we don't have any more main content to task on. + + + request.pingedTasks.push(suspendedFallbackTask); + popComponentStackInDEV(task); +} + +function hoistCompletedBoundaryResources(request, completedBoundary) { + if (request.completedRootSegment !== null || request.pendingRootTasks > 0) { + // The Shell has not flushed yet. we can hoist Resources for this boundary + // all the way to the Root. + hoistResourcesToRoot(request.resources, completedBoundary.resources); + } // We don't hoist if the root already flushed because late resources will be hoisted + // as boundaries flush + +} + +function renderHostElement(request, task, type, props) { + pushBuiltInComponentStackInDEV(task, type); + var segment = task.blockedSegment; + var children = pushStartInstance(segment.chunks, request.preamble, type, props, request.responseState, segment.formatContext, segment.lastPushedText); + segment.lastPushedText = false; + var prevContext = segment.formatContext; + segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still + // need to pop back up and finish this subtree of HTML. + + renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need + // the correct context. Therefore this is not in a finally. + + segment.formatContext = prevContext; + pushEndInstance(segment.chunks, request.postamble, type); + segment.lastPushedText = false; + popComponentStackInDEV(task); +} + +function shouldConstruct$1(Component) { + return Component.prototype && Component.prototype.isReactComponent; +} + +function renderWithHooks(request, task, prevThenableState, Component, props, secondArg) { + var componentIdentity = {}; + prepareToUseHooks(task, componentIdentity, prevThenableState); + var result = Component(props, secondArg); + return finishHooks(Component, props, result, secondArg); +} + +function finishClassComponent(request, task, instance, Component, props) { + var nextChildren = instance.render(); + + { + if (instance.props !== props) { + if (!didWarnAboutReassigningProps) { + error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component'); + } + + didWarnAboutReassigningProps = true; + } + } + + { + var childContextTypes = Component.childContextTypes; + + if (childContextTypes !== null && childContextTypes !== undefined) { + var previousContext = task.legacyContext; + var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes); + task.legacyContext = mergedContext; + renderNodeDestructive(request, task, null, nextChildren); + task.legacyContext = previousContext; + return; + } + } + + renderNodeDestructive(request, task, null, nextChildren); +} + +function renderClassComponent(request, task, Component, props) { + pushClassComponentStackInDEV(task, Component); + var maskedContext = getMaskedContext(Component, task.legacyContext) ; + var instance = constructClassInstance(Component, props, maskedContext); + mountClassInstance(instance, Component, props, maskedContext); + finishClassComponent(request, task, instance, Component, props); + popComponentStackInDEV(task); +} + +var didWarnAboutBadClass = {}; +var didWarnAboutModulePatternComponent = {}; +var didWarnAboutContextTypeOnFunctionComponent = {}; +var didWarnAboutGetDerivedStateOnFunctionComponent = {}; +var didWarnAboutReassigningProps = false; +var didWarnAboutGenerators = false; +var didWarnAboutMaps = false; +var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern +// components for some reason. + +function renderIndeterminateComponent(request, task, prevThenableState, Component, props) { + var legacyContext; + + { + legacyContext = getMaskedContext(Component, task.legacyContext); + } + + pushFunctionComponentStackInDEV(task, Component); + + { + if (Component.prototype && typeof Component.prototype.render === 'function') { + var componentName = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutBadClass[componentName]) { + error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); + + didWarnAboutBadClass[componentName] = true; + } + } + } + + var value = renderWithHooks(request, task, prevThenableState, Component, props, legacyContext); + var hasId = checkDidRenderIdHook(); + + { + // Support for module components is deprecated and is removed behind a flag. + // Whether or not it would crash later, we want to show a good message in DEV first. + if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + var _componentName = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutModulePatternComponent[_componentName]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); + + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + } + + if ( // Run these checks in production only if the flag is off. + // Eventually we'll delete this branch altogether. + typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + { + var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutModulePatternComponent[_componentName2]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); + + didWarnAboutModulePatternComponent[_componentName2] = true; + } + } + + mountClassInstance(value, Component, props, legacyContext); + finishClassComponent(request, task, value, Component, props); + } else { + + { + validateFunctionComponentInDev(Component); + } // We're now successfully past this task, and we don't have to pop back to + // the previous task every again, so we can use the destructive recursive form. + + + if (hasId) { + // This component materialized an id. We treat this as its own level, with + // a single "child" slot. + var prevTreeContext = task.treeContext; + var totalChildren = 1; + var index = 0; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); + + try { + renderNodeDestructive(request, task, null, value); + } finally { + task.treeContext = prevTreeContext; + } + } else { + renderNodeDestructive(request, task, null, value); + } + } + + popComponentStackInDEV(task); +} + +function validateFunctionComponentInDev(Component) { + { + if (Component) { + if (Component.childContextTypes) { + error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); + } + } + + if (typeof Component.getDerivedStateFromProps === 'function') { + var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { + error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); + + didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; + } + } + + if (typeof Component.contextType === 'object' && Component.contextType !== null) { + var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { + error('%s: Function components do not support contextType.', _componentName4); + + didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; + } + } + } +} + +function resolveDefaultProps(Component, baseProps) { + if (Component && Component.defaultProps) { + // Resolve default props. Taken from ReactElement + var props = assign({}, baseProps); + var defaultProps = Component.defaultProps; + + for (var propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + + return props; + } + + return baseProps; +} + +function renderForwardRef(request, task, prevThenableState, type, props, ref) { + pushFunctionComponentStackInDEV(task, type.render); + var children = renderWithHooks(request, task, prevThenableState, type.render, props, ref); + var hasId = checkDidRenderIdHook(); + + if (hasId) { + // This component materialized an id. We treat this as its own level, with + // a single "child" slot. + var prevTreeContext = task.treeContext; + var totalChildren = 1; + var index = 0; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); + + try { + renderNodeDestructive(request, task, null, children); + } finally { + task.treeContext = prevTreeContext; + } + } else { + renderNodeDestructive(request, task, null, children); + } + + popComponentStackInDEV(task); +} + +function renderMemo(request, task, prevThenableState, type, props, ref) { + var innerType = type.type; + var resolvedProps = resolveDefaultProps(innerType, props); + renderElement(request, task, prevThenableState, innerType, resolvedProps, ref); +} + +function renderContextConsumer(request, task, context, props) { + // The logic below for Context differs depending on PROD or DEV mode. In + // DEV mode, we create a separate object for Context.Consumer that acts + // like a proxy to Context. This proxy object adds unnecessary code in PROD + // so we use the old behaviour (Context.Consumer references Context) to + // reduce size and overhead. The separate object references context via + // a property called "_context", which also gives us the ability to check + // in DEV mode if this property exists or not and warn if it does not. + { + if (context._context === undefined) { + // This may be because it's a Context (rather than a Consumer). + // Or it may be because it's older React where they're the same thing. + // We only want to warn if we're sure it's a new React. + if (context !== context.Consumer) { + if (!hasWarnedAboutUsingContextAsConsumer) { + hasWarnedAboutUsingContextAsConsumer = true; + + error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + } + } else { + context = context._context; + } + } + + var render = props.children; + + { + if (typeof render !== 'function') { + error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); + } + } + + var newValue = readContext(context); + var newChildren = render(newValue); + renderNodeDestructive(request, task, null, newChildren); +} + +function renderContextProvider(request, task, type, props) { + var context = type._context; + var value = props.value; + var children = props.children; + var prevSnapshot; + + { + prevSnapshot = task.context; + } + + task.context = pushProvider(context, value); + renderNodeDestructive(request, task, null, children); + task.context = popProvider(context); + + { + if (prevSnapshot !== task.context) { + error('Popping the context provider did not return back to the original snapshot. This is a bug in React.'); + } + } +} + +function renderLazyComponent(request, task, prevThenableState, lazyComponent, props, ref) { + pushBuiltInComponentStackInDEV(task, 'Lazy'); + var payload = lazyComponent._payload; + var init = lazyComponent._init; + var Component = init(payload); + var resolvedProps = resolveDefaultProps(Component, props); + renderElement(request, task, prevThenableState, Component, resolvedProps, ref); + popComponentStackInDEV(task); +} + +function renderOffscreen(request, task, props) { + var mode = props.mode; + + if (mode === 'hidden') ; else { + // A visible Offscreen boundary is treated exactly like a fragment: a + // pure indirection. + renderNodeDestructive(request, task, null, props.children); + } +} + +function renderElement(request, task, prevThenableState, type, props, ref) { + if (typeof type === 'function') { + if (shouldConstruct$1(type)) { + renderClassComponent(request, task, type, props); + return; + } else { + renderIndeterminateComponent(request, task, prevThenableState, type, props); + return; + } + } + + if (typeof type === 'string') { + renderHostElement(request, task, type, props); + return; + } + + switch (type) { + // LegacyHidden acts the same as a fragment. This only works because we + // currently assume that every instance of LegacyHidden is accompanied by a + // host component wrapper. In the hidden mode, the host component is given a + // `hidden` attribute, which ensures that the initial HTML is not visible. + // To support the use of LegacyHidden as a true fragment, without an extra + // DOM node, we would have to hide the initial HTML in some other way. + // TODO: Delete in LegacyHidden. It's an unstable API only used in the + // www build. As a migration step, we could add a special prop to Offscreen + // that simulates the old behavior (no hiding, no change to effects). + case REACT_LEGACY_HIDDEN_TYPE: + case REACT_DEBUG_TRACING_MODE_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_PROFILER_TYPE: + case REACT_FRAGMENT_TYPE: + { + renderNodeDestructive(request, task, null, props.children); + return; + } + + case REACT_OFFSCREEN_TYPE: + { + renderOffscreen(request, task, props); + return; + } + + case REACT_SUSPENSE_LIST_TYPE: + { + pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries. + + renderNodeDestructive(request, task, null, props.children); + popComponentStackInDEV(task); + return; + } + + case REACT_SCOPE_TYPE: + { + + throw new Error('ReactDOMServer does not yet support scope components.'); + } + // eslint-disable-next-line-no-fallthrough + + case REACT_SUSPENSE_TYPE: + { + { + renderSuspenseBoundary(request, task, props); + } + + return; + } + } + + if (typeof type === 'object' && type !== null) { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + { + renderForwardRef(request, task, prevThenableState, type, props, ref); + return; + } + + case REACT_MEMO_TYPE: + { + renderMemo(request, task, prevThenableState, type, props, ref); + return; + } + + case REACT_PROVIDER_TYPE: + { + renderContextProvider(request, task, type, props); + return; + } + + case REACT_CONTEXT_TYPE: + { + renderContextConsumer(request, task, type, props); + return; + } + + case REACT_LAZY_TYPE: + { + renderLazyComponent(request, task, prevThenableState, type, props); + return; + } + } + } + + var info = ''; + + { + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; + } + } + + throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); +} + +function validateIterable(iterable, iteratorFn) { + { + // We don't support rendering Generators because it's a mutation. + // See https://github.com/facebook/react/issues/12995 + if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag + iterable[Symbol.toStringTag] === 'Generator') { + if (!didWarnAboutGenerators) { + error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); + } + + didWarnAboutGenerators = true; + } // Warn about using Maps as children + + + if (iterable.entries === iteratorFn) { + if (!didWarnAboutMaps) { + error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } + + didWarnAboutMaps = true; + } + } +} + +function renderNodeDestructive(request, task, // The thenable state reused from the previous attempt, if any. This is almost +// always null, except when called by retryTask. +prevThenableState, node) { + { + // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture + // a component stack at the right place in the tree. We don't do this in renderNode + // becuase it is not called at every layer of the tree and we may lose frames + try { + return renderNodeDestructiveImpl(request, task, prevThenableState, node); + } catch (x) { + if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else { + // This is an error, stash the component stack if it is null. + lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV(); + } // rethrow so normal suspense logic can handle thrown value accordingly + + + throw x; + } + } +} // This function by it self renders a node and consumes the task by mutating it +// to update the current execution state. + + +function renderNodeDestructiveImpl(request, task, prevThenableState, node) { + // Stash the node we're working on. We'll pick up from this task in case + // something suspends. + task.node = node; // Handle object types + + if (typeof node === 'object' && node !== null) { + switch (node.$$typeof) { + case REACT_ELEMENT_TYPE: + { + var element = node; + var type = element.type; + var props = element.props; + var ref = element.ref; + renderElement(request, task, prevThenableState, type, props, ref); + return; + } + + case REACT_PORTAL_TYPE: + throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.'); + // eslint-disable-next-line-no-fallthrough + + case REACT_LAZY_TYPE: + { + var lazyNode = node; + var payload = lazyNode._payload; + var init = lazyNode._init; + var resolvedNode; + + { + try { + resolvedNode = init(payload); + } catch (x) { + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be + // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position + // vs Component position. We do not want the frame for Errors so we exclusively do this in + // the wakeable branch + pushBuiltInComponentStackInDEV(task, 'Lazy'); + } + + throw x; + } + } + + renderNodeDestructive(request, task, null, resolvedNode); + return; + } + } + + if (isArray(node)) { + renderChildrenArray(request, task, node); + return; + } + + var iteratorFn = getIteratorFn(node); + + if (iteratorFn) { + { + validateIterable(node, iteratorFn); + } + + var iterator = iteratorFn.call(node); + + if (iterator) { + // We need to know how many total children are in this set, so that we + // can allocate enough id slots to acommodate them. So we must exhaust + // the iterator before we start recursively rendering the children. + // TODO: This is not great but I think it's inherent to the id + // generation algorithm. + var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that. + + if (!step.done) { + var children = []; + + do { + children.push(step.value); + step = iterator.next(); + } while (!step.done); + + renderChildrenArray(request, task, children); + return; + } + + return; + } + } // $FlowFixMe[method-unbinding] + + + var childString = Object.prototype.toString.call(node); + throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } + + if (typeof node === 'string') { + var segment = task.blockedSegment; + segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText); + return; + } + + if (typeof node === 'number') { + var _segment = task.blockedSegment; + _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText); + return; + } + + { + if (typeof node === 'function') { + error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); + } + } +} + +function renderChildrenArray(request, task, children) { + var totalChildren = children.length; + + for (var i = 0; i < totalChildren; i++) { + var prevTreeContext = task.treeContext; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i); + + try { + // We need to use the non-destructive form so that we can safely pop back + // up and render the sibling if something suspends. + renderNode(request, task, children[i]); + } finally { + task.treeContext = prevTreeContext; + } + } +} + +function spawnNewSuspendedTask(request, task, thenableState, x) { + // Something suspended, we'll need to create a new segment and resolve it later. + var segment = task.blockedSegment; + var insertionIndex = segment.chunks.length; + var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed + segment.lastPushedText, // Assume we are text embedded at the trailing edge + true); + segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it + + segment.lastPushedText = false; + var newTask = createTask(request, thenableState, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext); + trackSuspendedWakeable(x); + + { + if (task.componentStack !== null) { + // We pop one task off the stack because the node that suspended will be tried again, + // which will add it back onto the stack. + newTask.componentStack = task.componentStack.parent; + } + } + + var ping = newTask.ping; + x.then(ping, ping); +} // This is a non-destructive form of rendering a node. If it suspends it spawns +// a new task and restores the context of this task to what it was before. + + +function renderNode(request, task, node) { + // TODO: Store segment.children.length here and reset it in case something + // suspended partially through writing something. + // Snapshot the current context in case something throws to interrupt the + // process. + var previousFormatContext = task.blockedSegment.formatContext; + var previousLegacyContext = task.legacyContext; + var previousContext = task.context; + var previousComponentStack = null; + + { + previousComponentStack = task.componentStack; + } + + try { + return renderNodeDestructive(request, task, null, node); + } catch (x) { + resetHooksState(); + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + var thenableState = getThenableStateAfterSuspending(); + spawnNewSuspendedTask(request, task, thenableState, x); // Restore the context. We assume that this will be restored by the inner + // functions in case nothing throws so we don't use "finally" here. + + task.blockedSegment.formatContext = previousFormatContext; + task.legacyContext = previousLegacyContext; + task.context = previousContext; // Restore all active ReactContexts to what they were before. + + switchContext(previousContext); + + { + task.componentStack = previousComponentStack; + } + + return; + } else { + // Restore the context. We assume that this will be restored by the inner + // functions in case nothing throws so we don't use "finally" here. + task.blockedSegment.formatContext = previousFormatContext; + task.legacyContext = previousLegacyContext; + task.context = previousContext; // Restore all active ReactContexts to what they were before. + + switchContext(previousContext); + + { + task.componentStack = previousComponentStack; + } // We assume that we don't need the correct context. + // Let's terminate the rest of the tree and don't render any siblings. + + + throw x; + } + } +} + +function erroredTask(request, boundary, segment, error) { + // Report the error to a global handler. + var errorDigest = logRecoverableError(request, error); + + if (boundary === null) { + fatalError(request, error); + } else { + boundary.pendingTasks--; + + if (!boundary.forceClientRender) { + boundary.forceClientRender = true; + boundary.errorDigest = errorDigest; + + { + captureBoundaryErrorDetailsDev(boundary, error); + } // Regardless of what happens next, this boundary won't be displayed, + // so we can flush it, if the parent already flushed. + + + if (boundary.parentFlushed) { + // We don't have a preference where in the queue this goes since it's likely + // to error on the client anyway. However, intentionally client-rendered + // boundaries should be flushed earlier so that they can start on the client. + // We reuse the same queue for errors. + request.clientRenderedBoundaries.push(boundary); + } + } + } + + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + var onAllReady = request.onAllReady; + onAllReady(); + } +} + +function abortTaskSoft(task) { + // This aborts task without aborting the parent boundary that it blocks. + // It's used for when we didn't need this task to complete the tree. + // If task was needed, then it should use abortTask instead. + var request = this; + var boundary = task.blockedBoundary; + var segment = task.blockedSegment; + segment.status = ABORTED; + finishedTask(request, boundary, segment); +} + +function abortTask(task, request, error) { + // This aborts the task and aborts the parent that it blocks, putting it into + // client rendered mode. + var boundary = task.blockedBoundary; + var segment = task.blockedSegment; + segment.status = ABORTED; + + if (boundary === null) { + request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close + // the request; + + if (request.status !== CLOSING && request.status !== CLOSED) { + logRecoverableError(request, error); + fatalError(request, error); + } + } else { + boundary.pendingTasks--; + + if (!boundary.forceClientRender) { + boundary.forceClientRender = true; + boundary.errorDigest = request.onError(error); + + { + var errorPrefix = 'The server did not finish this Suspense boundary: '; + var errorMessage; + + if (error && typeof error.message === 'string') { + errorMessage = errorPrefix + error.message; + } else { + // eslint-disable-next-line react-internal/safe-string-coercion + errorMessage = errorPrefix + String(error); + } + + var previousTaskInDev = currentTaskInDEV; + currentTaskInDEV = task; + + try { + captureBoundaryErrorDetailsDev(boundary, errorMessage); + } finally { + currentTaskInDEV = previousTaskInDev; + } + } + + if (boundary.parentFlushed) { + request.clientRenderedBoundaries.push(boundary); + } + } // If this boundary was still pending then we haven't already cancelled its fallbacks. + // We'll need to abort the fallbacks, which will also error that parent boundary. + + + boundary.fallbackAbortableTasks.forEach(function (fallbackTask) { + return abortTask(fallbackTask, request, error); + }); + boundary.fallbackAbortableTasks.clear(); + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + var onAllReady = request.onAllReady; + onAllReady(); + } + } +} + +function queueCompletedSegment(boundary, segment) { + if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) { + // This is an empty segment. There's nothing to write, so we can instead transfer the ID + // to the child. That way any existing references point to the child. + var childSegment = segment.children[0]; + childSegment.id = segment.id; + childSegment.parentFlushed = true; + + if (childSegment.status === COMPLETED) { + queueCompletedSegment(boundary, childSegment); + } + } else { + var completedSegments = boundary.completedSegments; + completedSegments.push(segment); + } +} + +function finishedTask(request, boundary, segment) { + if (boundary === null) { + if (segment.parentFlushed) { + if (request.completedRootSegment !== null) { + throw new Error('There can only be one root segment. This is a bug in React.'); + } + + request.completedRootSegment = segment; + } + + request.pendingRootTasks--; + + if (request.pendingRootTasks === 0) { + // We have completed the shell so the shell can't error anymore. + request.onShellError = noop$1; + var onShellReady = request.onShellReady; + onShellReady(); + } + } else { + boundary.pendingTasks--; + + if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) { + // This must have been the last segment we were waiting on. This boundary is now complete. + if (segment.parentFlushed) { + // Our parent segment already flushed, so we need to schedule this segment to be emitted. + // If it is a segment that was aborted, we'll write other content instead so we don't need + // to emit it. + if (segment.status === COMPLETED) { + queueCompletedSegment(boundary, segment); + } + } + + { + hoistCompletedBoundaryResources(request, boundary); + } + + if (boundary.parentFlushed) { + // The segment might be part of a segment that didn't flush yet, but if the boundary's + // parent flushed, we need to schedule the boundary to be emitted. + request.completedBoundaries.push(boundary); + } // We can now cancel any pending task on the fallback since we won't need to show it anymore. + // This needs to happen after we read the parentFlushed flags because aborting can finish + // work which can trigger user code, which can start flushing, which can change those flags. + + + boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request); + boundary.fallbackAbortableTasks.clear(); + } else { + if (segment.parentFlushed) { + // Our parent already flushed, so we need to schedule this segment to be emitted. + // If it is a segment that was aborted, we'll write other content instead so we don't need + // to emit it. + if (segment.status === COMPLETED) { + queueCompletedSegment(boundary, segment); + var completedSegments = boundary.completedSegments; + + if (completedSegments.length === 1) { + // This is the first time since we last flushed that we completed anything. + // We can schedule this boundary to emit its partially completed segments early + // in case the parent has already been flushed. + if (boundary.parentFlushed) { + request.partialBoundaries.push(boundary); + } + } + } + } + } + } + + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + // This needs to be called at the very end so that we can synchronously write the result + // in the callback if needed. + var onAllReady = request.onAllReady; + onAllReady(); + } +} + +function retryTask(request, task) { + { + var blockedBoundary = task.blockedBoundary; + setCurrentlyRenderingBoundaryResourcesTarget(request.resources, blockedBoundary ? blockedBoundary.resources : null); + } + + var segment = task.blockedSegment; + + if (segment.status !== PENDING) { + // We completed this by other means before we had a chance to retry it. + return; + } // We restore the context to what it was when we suspended. + // We don't restore it after we leave because it's likely that we'll end up + // needing a very similar context soon again. + + + switchContext(task.context); + var prevTaskInDEV = null; + + { + prevTaskInDEV = currentTaskInDEV; + currentTaskInDEV = task; + } + + try { + // We call the destructive form that mutates this task. That way if something + // suspends again, we can reuse the same task instead of spawning a new one. + // Reset the task's thenable state before continuing, so that if a later + // component suspends we can reuse the same task object. If the same + // component suspends again, the thenable state will be restored. + var prevThenableState = task.thenableState; + task.thenableState = null; + renderNodeDestructive(request, task, prevThenableState, task.node); + pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded); + task.abortSet.delete(task); + segment.status = COMPLETED; + finishedTask(request, task.blockedBoundary, segment); + } catch (x) { + resetHooksState(); + + 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); + var wakeable = x; + trackSuspendedWakeable(wakeable); + task.thenableState = getThenableStateAfterSuspending(); + } else { + task.abortSet.delete(task); + segment.status = ERRORED; + erroredTask(request, task.blockedBoundary, segment, x); + } + } finally { + { + setCurrentlyRenderingBoundaryResourcesTarget(request.resources, null); + } + + { + currentTaskInDEV = prevTaskInDEV; + } + } +} + +function performWork(request) { + if (request.status === CLOSED) { + return; + } + + var prevContext = getActiveContext(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = HooksDispatcher; + var prevCacheDispatcher; + + { + prevCacheDispatcher = ReactCurrentCache.current; + ReactCurrentCache.current = DefaultCacheDispatcher; + } + + var previousHostDispatcher = prepareToRender(request.resources); + var prevGetCurrentStackImpl; + + { + prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack; + ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV; + } + + var prevResponseState = currentResponseState; + setCurrentResponseState(request.responseState); + + try { + var pingedTasks = request.pingedTasks; + var i; + + for (i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + pingedTasks.splice(0, i); + + if (request.destination !== null) { + flushCompletedQueues(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + setCurrentResponseState(prevResponseState); + ReactCurrentDispatcher$1.current = prevDispatcher; + + { + ReactCurrentCache.current = prevCacheDispatcher; + } + + cleanupAfterRender(previousHostDispatcher); + + { + ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl; + } + + if (prevDispatcher === HooksDispatcher) { + // This means that we were in a reentrant work loop. This could happen + // in a renderer that supports synchronous work like renderToString, + // when it's called from within another renderer. + // Normally we don't bother switching the contexts to their root/default + // values when leaving because we'll likely need the same or similar + // context again. However, when we're inside a synchronous loop like this + // we'll to restore the context to what it was before returning. + switchContext(prevContext); + } + } +} + +function flushSubtree(request, destination, segment) { + segment.parentFlushed = true; + + switch (segment.status) { + case PENDING: + { + // We're emitting a placeholder for this segment to be filled in later. + // Therefore we'll need to assign it an ID - to refer to it by. + var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately + + segment.lastPushedText = false; + segment.textEmbedded = false; + return writePlaceholder(destination, request.responseState, segmentID); + } + + case COMPLETED: + { + segment.status = FLUSHED; + var r = true; + var chunks = segment.chunks; + var chunkIdx = 0; + var children = segment.children; + + for (var childIdx = 0; childIdx < children.length; childIdx++) { + var nextChild = children[childIdx]; // Write all the chunks up until the next child. + + for (; chunkIdx < nextChild.index; chunkIdx++) { + writeChunk(destination, chunks[chunkIdx]); + } + + r = flushSegment(request, destination, nextChild); + } // Finally just write all the remaining chunks + + + for (; chunkIdx < chunks.length - 1; chunkIdx++) { + writeChunk(destination, chunks[chunkIdx]); + } + + if (chunkIdx < chunks.length) { + r = writeChunkAndReturn(destination, chunks[chunkIdx]); + } + + return r; + } + + default: + { + throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.'); + } + } +} + +function flushSegment(request, destination, segment) { + var boundary = segment.boundary; + + if (boundary === null) { + // Not a suspense boundary. + return flushSubtree(request, destination, segment); + } + + boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to + // emit the content or the fallback now. + + if (boundary.forceClientRender) { + // Emit a client rendered suspense boundary wrapper. + // We never queue the inner boundary so we'll never emit its content or partial segments. + writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState); + } else if (boundary.pendingTasks > 0) { + // This boundary is still loading. Emit a pending suspense boundary wrapper. + // Assign an ID to refer to the future content by. + boundary.rootSegmentID = request.nextSegmentId++; + + if (boundary.completedSegments.length > 0) { + // If this is at least partially complete, we can queue it to be partially emitted early. + request.partialBoundaries.push(boundary); + } /// This is the first time we should have referenced this ID. + + + var id = boundary.id = assignSuspenseBoundaryID(request.responseState); + writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndPendingSuspenseBoundary(destination, request.responseState); + } else if (boundary.byteSize > request.progressiveChunkSize) { + // This boundary is large and will be emitted separately so that we can progressively show + // other content. We add it to the queue during the flush because we have to ensure that + // the parent flushes first so that there's something to inject it into. + // We also have to make sure that it's emitted into the queue in a deterministic slot. + // I.e. we can't insert it here when it completes. + // Assign an ID to refer to the future content by. + boundary.rootSegmentID = request.nextSegmentId++; + request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper. + + writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndPendingSuspenseBoundary(destination, request.responseState); + } else { + { + hoistResources(request.resources, boundary.resources); + } // We can inline this boundary's content as a complete boundary. + + + writeStartCompletedSuspenseBoundary$1(destination, request.responseState); + var completedSegments = boundary.completedSegments; + + if (completedSegments.length !== 1) { + throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.'); + } + + var contentSegment = completedSegments[0]; + flushSegment(request, destination, contentSegment); + return writeEndCompletedSuspenseBoundary$1(destination, request.responseState); + } +} + +function flushInitialResources(destination, resources, responseState) { + writeInitialResources(destination, resources, responseState); +} + +function flushImmediateResources(destination, request) { + writeImmediateResources(destination, request.resources, request.responseState); +} + +function flushClientRenderedBoundary(request, destination, boundary) { + return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); +} + +function flushSegmentContainer(request, destination, segment) { + writeStartSegment(destination, request.responseState, segment.formatContext, segment.id); + flushSegment(request, destination, segment); + return writeEndSegment(destination, segment.formatContext); +} + +function flushCompletedBoundary(request, destination, boundary) { + { + setCurrentlyRenderingBoundaryResourcesTarget(request.resources, boundary.resources); + } + + var completedSegments = boundary.completedSegments; + var i = 0; + + for (; i < completedSegments.length; i++) { + var segment = completedSegments[i]; + flushPartiallyCompletedSegment(request, destination, boundary, segment); + } + + completedSegments.length = 0; + return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID, boundary.resources); +} + +function flushPartialBoundary(request, destination, boundary) { + { + setCurrentlyRenderingBoundaryResourcesTarget(request.resources, boundary.resources); + } + + var completedSegments = boundary.completedSegments; + var i = 0; + + for (; i < completedSegments.length; i++) { + var segment = completedSegments[i]; + + if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) { + i++; + completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority + // might want to write later. + + return false; + } + } + + completedSegments.splice(0, i); + return true; +} + +function flushPartiallyCompletedSegment(request, destination, boundary, segment) { + if (segment.status === FLUSHED) { + // We've already flushed this inline. + return true; + } + + var segmentID = segment.id; + + if (segmentID === -1) { + // This segment wasn't previously referred to. This happens at the root of + // a boundary. We make kind of a leap here and assume this is the root. + var rootSegmentID = segment.id = boundary.rootSegmentID; + + if (rootSegmentID === -1) { + throw new Error('A root segment ID must have been assigned by now. This is a bug in React.'); + } + + return flushSegmentContainer(request, destination, segment); + } else { + flushSegmentContainer(request, destination, segment); + return writeCompletedSegmentInstruction(destination, request.responseState, segmentID); + } +} + +function flushCompletedQueues(request, destination) { + + try { + // The structure of this is to go through each queue one by one and write + // until the sink tells us to stop. When we should stop, we still finish writing + // that item fully and then yield. At that point we remove the already completed + // items up until the point we completed them. + var i; + var completedRootSegment = request.completedRootSegment; + + if (completedRootSegment !== null) { + if (request.pendingRootTasks === 0) { + if (enableFloat) { + var preamble = request.preamble; + + for (i = 0; i < preamble.length; i++) { + // we expect the preamble to be tiny and will ignore backpressure + writeChunk(destination, preamble[i]); + } + + flushInitialResources(destination, request.resources, request.responseState); + } + + flushSegment(request, destination, completedRootSegment); + request.completedRootSegment = null; + writeCompletedRoot(destination, request.responseState); + } else { + // We haven't flushed the root yet so we don't need to check any other branches further down + return; + } + } else if (enableFloat) { + flushImmediateResources(destination, request); + } // We emit client rendering instructions for already emitted boundaries first. + // This is so that we can signal to the client to start client rendering them as + // soon as possible. + + + var clientRenderedBoundaries = request.clientRenderedBoundaries; + + for (i = 0; i < clientRenderedBoundaries.length; i++) { + var boundary = clientRenderedBoundaries[i]; + + if (!flushClientRenderedBoundary(request, destination, boundary)) { + request.destination = null; + i++; + clientRenderedBoundaries.splice(0, i); + return; + } + } + + clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries + // that are completely done since we can actually show them, than it is to emit + // any individual segments from a partially complete boundary. + + var completedBoundaries = request.completedBoundaries; + + for (i = 0; i < completedBoundaries.length; i++) { + var _boundary = completedBoundaries[i]; + + if (!flushCompletedBoundary(request, destination, _boundary)) { + request.destination = null; + i++; + completedBoundaries.splice(0, i); + return; + } + } + + completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before + // we continue with lower priorities. + + completeWriting(destination); + beginWriting(destination); // TODO: Here we'll emit data used by hydration. + // Next we emit any segments of any boundaries that are partially complete + // but not deeply complete. + + var partialBoundaries = request.partialBoundaries; + + for (i = 0; i < partialBoundaries.length; i++) { + var _boundary2 = partialBoundaries[i]; + + if (!flushPartialBoundary(request, destination, _boundary2)) { + request.destination = null; + i++; + partialBoundaries.splice(0, i); + return; + } + } + + partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had + // boundaries added to it in case they were too larged to be inlined. + // New ones might be added in this loop. + + var largeBoundaries = request.completedBoundaries; + + for (i = 0; i < largeBoundaries.length; i++) { + var _boundary3 = largeBoundaries[i]; + + if (!flushCompletedBoundary(request, destination, _boundary3)) { + request.destination = null; + i++; + largeBoundaries.splice(0, i); + return; + } + } + + largeBoundaries.splice(0, i); + } finally { + if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because + // either they have pending task or they're complete. + ) { + { + var postamble = request.postamble; + + for (var _i = 0; _i < postamble.length; _i++) { + writeChunk(destination, postamble[_i]); + } + } + + { + if (request.abortableTasks.size !== 0) { + error('There was still abortable task at the root when we closed. This is a bug in React.'); + } + } // We're done. + + + close(destination); + } + } +} + +function startWork(request) { + scheduleWork(function () { + return performWork(request); + }); +} +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 { + flushCompletedQueues(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} // This is called to early terminate a request. It puts all pending boundaries in client rendered state. + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + + if (abortableTasks.size > 0) { + var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + + abortableTasks.forEach(function (task) { + return abortTask(task, request, _error); + }); + abortableTasks.clear(); + } + + if (request.destination !== null) { + flushCompletedQueues(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function onError() {// Non-fatal errors are ignored. +} + +function renderToStringImpl(children, options, generateStaticMarkup, abortReason) { + var didFatal = false; + var fatalError = null; + var result = ''; + var destination = { + push: function (chunk) { + if (chunk !== null) { + result += chunk; + } + + return true; + }, + destroy: function (error) { + didFatal = true; + fatalError = error; + } + }; + var readyToStream = false; + + function onShellReady() { + readyToStream = true; + } + + var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined); + startWork(request); // If anything suspended and is still pending, we'll abort it before writing. + // That way we write only client-rendered boundaries from the start. + + abort(request, abortReason); + startFlowing(request, destination); + + if (didFatal && fatalError !== abortReason) { + throw fatalError; + } + + if (!readyToStream) { + // Note: This error message is the one we use on the client. It doesn't + // really make sense here. But this is the legacy server renderer, anyway. + // We're going to delete it soon. + throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.'); + } + + return result; +} + +function renderToString(children, options) { + return renderToStringImpl(children, options, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); +} + +function renderToStaticMarkup(children, options) { + return renderToStringImpl(children, options, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); +} + +function renderToNodeStream() { + throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.'); +} + +function renderToStaticNodeStream() { + throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.'); +} + +exports.renderToNodeStream = renderToNodeStream; +exports.renderToStaticMarkup = renderToStaticMarkup; +exports.renderToStaticNodeStream = renderToStaticNodeStream; +exports.renderToString = renderToString; +exports.version = ReactVersion; + })(); +} diff --git a/packages/next/compiled/react-dom/cjs/react-dom-server-legacy.browser.production.min.js b/packages/next/compiled/react-dom/cjs/react-dom-server-legacy.browser.production.min.js new file mode 100644 index 000000000000..6fcd87364e75 --- /dev/null +++ b/packages/next/compiled/react-dom/cjs/react-dom-server-legacy.browser.production.min.js @@ -0,0 +1,113 @@ +/** + * @license React + * react-dom-server-legacy.browser.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("react"),ba=require("react-dom");function m(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c