Unverified Commit db9040b0 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable @typescript-eslint/no-use-before-define variables,enums,typedefs for core files (#39511)

* Enable @typescript-eslint/no-use-before-define typedefs and enums

* Enable variables

* Move in client/index

* Revert "Move in client/index"

This reverts commit 592d70cf3d9cd39e741905faf9229f664c9b4ebd.

* Move wrapApp

* Revert "Revert "Move in client/index""

This reverts commit 14b6105eb45ab87b3b4a1d6f2907d8b9e9657888.

* Fix classes cases
parent d510758b
......@@ -69,10 +69,10 @@
"warn",
{
"functions": false,
"classes": false,
"variables": false,
"enums": false,
"typedefs": false
"classes": true,
"variables": true,
"enums": true,
"typedefs": true
}
],
"no-unused-vars": "off",
......
......@@ -15,6 +15,8 @@ import type {
VariableDeclaration,
} from '@swc/core'
export class NoSuchDeclarationError extends Error {}
/**
* Extracts the value of an exported const variable named `exportedName`
* (e.g. "export const config = { runtime: 'experimental-edge' }") from swc's AST.
......@@ -138,7 +140,6 @@ export class UnsupportedValueError extends Error {
this.path = codePath
}
}
export class NoSuchDeclarationError extends Error {}
function extractValue(node: Node, path?: string[]): any {
if (isNullLiteral(node)) {
......
......@@ -226,6 +226,7 @@ function getMiddlewareRegExpStrings(
}
}
let warnedAboutExperimentalEdgeApiFunctions = false
function warnAboutExperimentalEdgeApiFunctions() {
if (warnedAboutExperimentalEdgeApiFunctions) {
return
......@@ -234,8 +235,6 @@ function warnAboutExperimentalEdgeApiFunctions() {
warnedAboutExperimentalEdgeApiFunctions = true
}
let warnedAboutExperimentalEdgeApiFunctions = false
const warnedUnsupportedValueMap = new Map<string, boolean>()
function warnAboutUnsupportedValue(
pageFilePath: string,
......
......@@ -135,6 +135,35 @@ function getCodeAnalizer(params: {
} = params
const { hooks } = parser
/**
* For an expression this will check the graph to ensure it is being used
* by exports. Then it will store in the module buildInfo a boolean to
* express that it contains dynamic code and, if it is available, the
* module path that is using it.
*/
const handleExpression = () => {
if (!isInMiddlewareLayer(parser)) {
return
}
wp.optimize.InnerGraph.onUsage(parser.state, (used = true) => {
const buildInfo = getModuleBuildInfo(parser.state.module)
if (buildInfo.usingIndirectEval === true || used === false) {
return
}
if (!buildInfo.usingIndirectEval || used === true) {
buildInfo.usingIndirectEval = used
return
}
buildInfo.usingIndirectEval = new Set([
...Array.from(buildInfo.usingIndirectEval),
...Array.from(used),
])
})
}
/**
* This expression handler allows to wrap a dynamic code expression with a
* function call where we can warn about dynamic code not being allowed
......@@ -216,35 +245,6 @@ function getCodeAnalizer(params: {
}
}
/**
* For an expression this will check the graph to ensure it is being used
* by exports. Then it will store in the module buildInfo a boolean to
* express that it contains dynamic code and, if it is available, the
* module path that is using it.
*/
const handleExpression = () => {
if (!isInMiddlewareLayer(parser)) {
return
}
wp.optimize.InnerGraph.onUsage(parser.state, (used = true) => {
const buildInfo = getModuleBuildInfo(parser.state.module)
if (buildInfo.usingIndirectEval === true || used === false) {
return
}
if (!buildInfo.usingIndirectEval || used === true) {
buildInfo.usingIndirectEval = used
return
}
buildInfo.usingIndirectEval = new Set([
...Array.from(buildInfo.usingIndirectEval),
...Array.from(used),
])
})
}
/**
* Declares an environment variable that is being used in this module
* through this static analysis.
......
......@@ -319,6 +319,116 @@ function handleLoading(
})
}
const ImageElement = ({
imgAttributes,
heightInt,
widthInt,
qualityInt,
className,
imgStyle,
blurStyle,
isLazy,
fill,
placeholder,
loading,
srcString,
config,
unoptimized,
loader,
onLoadingCompleteRef,
setBlurComplete,
setShowAltText,
onLoad,
onError,
noscriptSizes,
...rest
}: ImageElementProps) => {
loading = isLazy ? 'lazy' : loading
return (
<>
<img
{...rest}
{...imgAttributes}
width={widthInt}
height={heightInt}
decoding="async"
data-nimg={`future${fill ? '-fill' : ''}`}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
style={{ ...imgStyle, ...blurStyle }}
ref={useCallback(
(img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
if (img?.complete) {
handleLoading(
img,
srcString,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
}
},
[srcString, placeholder, onLoadingCompleteRef, setBlurComplete]
)}
onLoad={(event) => {
const img = event.currentTarget as ImgElementWithDataProp
handleLoading(
img,
srcString,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
if (onLoad) {
onLoad(event)
}
}}
onError={(event) => {
// if the real image fails to load, this will ensure "alt" is visible
setShowAltText(true)
if (placeholder === 'blur') {
// If the real image fails to load, this will still remove the placeholder.
setBlurComplete(true)
}
if (onError) {
onError(event)
}
}}
/>
{placeholder === 'blur' && (
<noscript>
<img
{...rest}
{...generateImgAttrs({
config,
src: srcString,
unoptimized,
width: widthInt,
quality: qualityInt,
sizes: noscriptSizes,
loader,
})}
width={widthInt}
height={heightInt}
decoding="async"
data-nimg={`future${fill ? '-fill' : ''}`}
style={imgStyle}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
/>
</noscript>
)}
</>
)
}
export default function Image({
src,
sizes,
......@@ -694,116 +804,6 @@ export default function Image({
)
}
const ImageElement = ({
imgAttributes,
heightInt,
widthInt,
qualityInt,
className,
imgStyle,
blurStyle,
isLazy,
fill,
placeholder,
loading,
srcString,
config,
unoptimized,
loader,
onLoadingCompleteRef,
setBlurComplete,
setShowAltText,
onLoad,
onError,
noscriptSizes,
...rest
}: ImageElementProps) => {
loading = isLazy ? 'lazy' : loading
return (
<>
<img
{...rest}
{...imgAttributes}
width={widthInt}
height={heightInt}
decoding="async"
data-nimg={`future${fill ? '-fill' : ''}`}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
style={{ ...imgStyle, ...blurStyle }}
ref={useCallback(
(img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
if (img?.complete) {
handleLoading(
img,
srcString,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
}
},
[srcString, placeholder, onLoadingCompleteRef, setBlurComplete]
)}
onLoad={(event) => {
const img = event.currentTarget as ImgElementWithDataProp
handleLoading(
img,
srcString,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
if (onLoad) {
onLoad(event)
}
}}
onError={(event) => {
// if the real image fails to load, this will ensure "alt" is visible
setShowAltText(true)
if (placeholder === 'blur') {
// If the real image fails to load, this will still remove the placeholder.
setBlurComplete(true)
}
if (onError) {
onError(event)
}
}}
/>
{placeholder === 'blur' && (
<noscript>
<img
{...rest}
{...generateImgAttrs({
config,
src: srcString,
unoptimized,
width: widthInt,
quality: qualityInt,
sizes: noscriptSizes,
loader,
})}
width={widthInt}
height={heightInt}
decoding="async"
data-nimg={`future${fill ? '-fill' : ''}`}
style={imgStyle}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
/>
</noscript>
)}
</>
)
}
function defaultLoader({
config,
src,
......
......@@ -349,6 +349,120 @@ function handleLoading(
})
}
const ImageElement = ({
imgAttributes,
heightInt,
widthInt,
qualityInt,
layout,
className,
imgStyle,
blurStyle,
isLazy,
placeholder,
loading,
srcString,
config,
unoptimized,
loader,
onLoadingCompleteRef,
setBlurComplete,
setIntersection,
onLoad,
onError,
isVisible,
noscriptSizes,
...rest
}: ImageElementProps) => {
loading = isLazy ? 'lazy' : loading
return (
<>
<img
{...rest}
{...imgAttributes}
decoding="async"
data-nimg={layout}
className={className}
style={{ ...imgStyle, ...blurStyle }}
ref={useCallback(
(img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
setIntersection(img)
if (img?.complete) {
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
}
},
[
setIntersection,
srcString,
layout,
placeholder,
onLoadingCompleteRef,
setBlurComplete,
]
)}
onLoad={(event) => {
const img = event.currentTarget as ImgElementWithDataProp
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
if (onLoad) {
onLoad(event)
}
}}
onError={(event) => {
if (placeholder === 'blur') {
// If the real image fails to load, this will still remove the placeholder.
setBlurComplete(true)
}
if (onError) {
onError(event)
}
}}
/>
{(isLazy || placeholder === 'blur') && (
<noscript>
<img
{...rest}
{...generateImgAttrs({
config,
src: srcString,
unoptimized,
layout,
width: widthInt,
quality: qualityInt,
sizes: noscriptSizes,
loader,
})}
decoding="async"
data-nimg={layout}
style={imgStyle}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
/>
</noscript>
)}
</>
)
}
export default function Image({
src,
sizes,
......@@ -846,120 +960,6 @@ export default function Image({
)
}
const ImageElement = ({
imgAttributes,
heightInt,
widthInt,
qualityInt,
layout,
className,
imgStyle,
blurStyle,
isLazy,
placeholder,
loading,
srcString,
config,
unoptimized,
loader,
onLoadingCompleteRef,
setBlurComplete,
setIntersection,
onLoad,
onError,
isVisible,
noscriptSizes,
...rest
}: ImageElementProps) => {
loading = isLazy ? 'lazy' : loading
return (
<>
<img
{...rest}
{...imgAttributes}
decoding="async"
data-nimg={layout}
className={className}
style={{ ...imgStyle, ...blurStyle }}
ref={useCallback(
(img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
}
setIntersection(img)
if (img?.complete) {
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
}
},
[
setIntersection,
srcString,
layout,
placeholder,
onLoadingCompleteRef,
setBlurComplete,
]
)}
onLoad={(event) => {
const img = event.currentTarget as ImgElementWithDataProp
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadingCompleteRef,
setBlurComplete
)
if (onLoad) {
onLoad(event)
}
}}
onError={(event) => {
if (placeholder === 'blur') {
// If the real image fails to load, this will still remove the placeholder.
setBlurComplete(true)
}
if (onError) {
onError(event)
}
}}
/>
{(isLazy || placeholder === 'blur') && (
<noscript>
<img
{...rest}
{...generateImgAttrs({
config,
src: srcString,
unoptimized,
layout,
width: widthInt,
quality: qualityInt,
sizes: noscriptSizes,
loader,
})}
decoding="async"
data-nimg={layout}
style={imgStyle}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
/>
</noscript>
)}
</>
)
}
function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src
}
......
......@@ -80,6 +80,7 @@ let headManager: {
getIsSsr?: () => boolean
}
let initialMatchesMiddleware = false
let lastAppProps: AppProps
let lastRenderReject: (() => void) | null
let webpackHMR: any
......@@ -288,6 +289,18 @@ export async function initialize(opts: { webpackHMR?: any } = {}): Promise<{
return { assetPrefix: prefix }
}
const wrapApp =
(App: AppComponent) =>
(wrappedAppProps: Record<string, any>): JSX.Element => {
const appProps: AppProps = {
...wrappedAppProps,
Component: CachedComponent,
err: initialData.err,
router,
}
return <AppContainer>{renderApp(App, appProps)}</AppContainer>
}
export async function hydrate(opts?: { beforeRender?: () => Promise<void> }) {
let initialErr = initialData.err
......@@ -663,18 +676,6 @@ function renderApp(App: AppComponent, appProps: AppProps) {
return <App {...appProps} />
}
const wrapApp =
(App: AppComponent) =>
(wrappedAppProps: Record<string, any>): JSX.Element => {
const appProps: AppProps = {
...wrappedAppProps,
Component: CachedComponent,
err: initialData.err,
router,
}
return <AppContainer>{renderApp(App, appProps)}</AppContainer>
}
let RSCComponent: (props: any) => JSX.Element
if (process.env.__NEXT_RSC) {
const getCacheKey = () => {
......@@ -818,7 +819,6 @@ if (process.env.__NEXT_RSC) {
}
}
let lastAppProps: AppProps
function doRender(input: RenderRouteInfo): Promise<any> {
let { App, Component, props, err, __N_RSC }: RenderRouteInfo = input
let styleSheets: StyleSheetTuple[] | undefined =
......
......@@ -72,6 +72,9 @@ export function useIntersection<T extends Element>({
return [setElement, visible, resetVisible]
}
const observers = new Map<Identifier, Observer>()
const idList: Identifier[] = []
function observe(
element: Element,
callback: ObserveCallback,
......@@ -99,10 +102,6 @@ function observe(
}
}
const observers = new Map<Identifier, Observer>()
const idList: Identifier[] = []
function createObserver(options: UseIntersectionObserverInit): Observer {
const id = {
root: options.root || null,
......
......@@ -5,6 +5,16 @@ import {
const regexpPlainIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/
export class SerializableError extends Error {
constructor(page: string, method: string, path: string, message: string) {
super(
path
? `Error serializing \`${path}\` returned from \`${method}\` in "${page}".\nReason: ${message}`
: `Error serializing props returned from \`${method}\` in "${page}".\nReason: ${message}`
)
}
}
export function isSerializableProps(
page: string,
method: string,
......@@ -131,13 +141,3 @@ export function isSerializableProps(
return isSerializable(new Map(), input, '')
}
export class SerializableError extends Error {
constructor(page: string, method: string, path: string, message: string) {
super(
path
? `Error serializing \`${path}\` returned from \`${method}\` in "${page}".\nReason: ${message}`
: `Error serializing props returned from \`${method}\` in "${page}".\nReason: ${message}`
)
}
}
This diff is collapsed.
......@@ -24,6 +24,46 @@ function _getInitialProps({
return { statusCode }
}
const styles: { [k: string]: React.CSSProperties } = {
error: {
fontFamily:
'-apple-system, BlinkMacSystemFont, Roboto, "Segoe UI", "Fira Sans", Avenir, "Helvetica Neue", "Lucida Grande", sans-serif',
height: '100vh',
textAlign: 'center',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
desc: {
display: 'inline-block',
textAlign: 'left',
lineHeight: '49px',
height: '49px',
verticalAlign: 'middle',
},
h1: {
display: 'inline-block',
margin: 0,
marginRight: '20px',
padding: '0 23px 0 0',
fontSize: '24px',
fontWeight: 500,
verticalAlign: 'top',
lineHeight: '49px',
},
h2: {
fontSize: '14px',
fontWeight: 'normal',
lineHeight: '49px',
margin: 0,
padding: 0,
},
}
/**
* `Error` component used for handling errors.
*/
......@@ -94,43 +134,3 @@ export default class Error<P = {}> extends React.Component<P & ErrorProps> {
)
}
}
const styles: { [k: string]: React.CSSProperties } = {
error: {
fontFamily:
'-apple-system, BlinkMacSystemFont, Roboto, "Segoe UI", "Fira Sans", Avenir, "Helvetica Neue", "Lucida Grande", sans-serif',
height: '100vh',
textAlign: 'center',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
desc: {
display: 'inline-block',
textAlign: 'left',
lineHeight: '49px',
height: '49px',
verticalAlign: 'middle',
},
h1: {
display: 'inline-block',
margin: 0,
marginRight: '20px',
padding: '0 23px 0 0',
fontSize: '24px',
fontWeight: 500,
verticalAlign: 'top',
lineHeight: '49px',
},
h2: {
fontSize: '14px',
fontWeight: 'normal',
lineHeight: '49px',
margin: 0,
padding: 0,
},
}
......@@ -141,6 +141,25 @@ type RequestContext = {
renderOpts: RenderOptsPartial
}
class NoFallbackError extends Error {}
// Internal wrapper around build errors at development
// time, to prevent us from propagating or logging them
export class WrappedBuildError extends Error {
innerError: Error
constructor(innerError: Error) {
super()
this.innerError = innerError
}
}
type ResponsePayload = {
type: 'html' | 'json'
body: RenderResult
revalidateOptions?: any
}
export default abstract class Server<ServerOptions extends Options = Options> {
protected dir: string
protected quiet: boolean
......@@ -2139,22 +2158,3 @@ export function prepareServerlessUrl(
}
export { stringifyQuery } from './server-route-utils'
class NoFallbackError extends Error {}
// Internal wrapper around build errors at development
// time, to prevent us from propagating or logging them
export class WrappedBuildError extends Error {
innerError: Error
constructor(innerError: Error) {
super()
this.innerError = innerError
}
}
type ResponsePayload = {
type: 'html' | 'json'
body: RenderResult
revalidateOptions?: any
}
......@@ -26,6 +26,39 @@ import type ws from 'ws'
import { isMiddlewareFilename } from '../../build/utils'
import { nonNullable } from '../../lib/non-nullable'
class EventStream {
clients: Set<ws>
constructor() {
this.clients = new Set()
}
everyClient(fn: (client: ws) => void) {
for (const client of this.clients) {
fn(client)
}
}
close() {
this.everyClient((client) => {
client.close()
})
this.clients.clear()
}
handler(client: ws) {
this.clients.add(client)
client.addEventListener('close', () => {
this.clients.delete(client)
})
}
publish(payload: any) {
this.everyClient((client) => {
client.send(JSON.stringify(payload))
})
}
}
export class WebpackHotMiddleware {
eventStream: EventStream
clientLatestStats: { ts: number; stats: webpack.Stats } | null
......@@ -162,39 +195,6 @@ export class WebpackHotMiddleware {
}
}
class EventStream {
clients: Set<ws>
constructor() {
this.clients = new Set()
}
everyClient(fn: (client: ws) => void) {
for (const client of this.clients) {
fn(client)
}
}
close() {
this.everyClient((client) => {
client.close()
})
this.clients.clear()
}
handler(client: ws) {
this.clients.add(client)
client.addEventListener('close', () => {
this.clients.delete(client)
})
}
publish(payload: any) {
this.everyClient((client) => {
client.send(JSON.stringify(payload))
})
}
}
function isMiddlewareStats(stats: webpack.Stats) {
for (const key of stats.compilation.entrypoints.keys()) {
if (isMiddlewareFilename(key)) {
......
......@@ -124,6 +124,64 @@ export const entries: {
}
} = {}
// Make sure only one invalidation happens at a time∫
// Otherwise, webpack hash gets changed and it'll force the client to reload.
class Invalidator {
private multiCompiler: webpack.MultiCompiler
private building: boolean
public rebuildAgain: boolean
constructor(multiCompiler: webpack.MultiCompiler) {
this.multiCompiler = multiCompiler
// contains an array of types of compilers currently building
this.building = false
this.rebuildAgain = false
}
invalidate(keys: string[] = []) {
// If there's a current build is processing, we won't abort it by invalidating.
// (If aborted, it'll cause a client side hard reload)
// But let it to invalidate just after the completion.
// So, it can re-build the queued pages at once.
if (this.building) {
this.rebuildAgain = true
return
}
this.building = true
if (!keys || keys.length === 0) {
this.multiCompiler.compilers[0].watching?.invalidate()
this.multiCompiler.compilers[1].watching?.invalidate()
this.multiCompiler.compilers[2].watching?.invalidate()
return
}
for (const key of keys) {
if (key === 'client') {
this.multiCompiler.compilers[0].watching?.invalidate()
} else if (key === 'server') {
this.multiCompiler.compilers[1].watching?.invalidate()
} else if (key === 'edgeServer') {
this.multiCompiler.compilers[2].watching?.invalidate()
}
}
}
startBuilding() {
this.building = true
}
doneBuilding() {
this.building = false
if (this.rebuildAgain) {
this.rebuildAgain = false
this.invalidate()
}
}
}
let invalidator: Invalidator
export const getInvalidator = () => invalidator
......@@ -433,64 +491,6 @@ function disposeInactiveEntries(maxInactiveAge: number) {
})
}
// Make sure only one invalidation happens at a time∫
// Otherwise, webpack hash gets changed and it'll force the client to reload.
class Invalidator {
private multiCompiler: webpack.MultiCompiler
private building: boolean
public rebuildAgain: boolean
constructor(multiCompiler: webpack.MultiCompiler) {
this.multiCompiler = multiCompiler
// contains an array of types of compilers currently building
this.building = false
this.rebuildAgain = false
}
invalidate(keys: string[] = []) {
// If there's a current build is processing, we won't abort it by invalidating.
// (If aborted, it'll cause a client side hard reload)
// But let it to invalidate just after the completion.
// So, it can re-build the queued pages at once.
if (this.building) {
this.rebuildAgain = true
return
}
this.building = true
if (!keys || keys.length === 0) {
this.multiCompiler.compilers[0].watching?.invalidate()
this.multiCompiler.compilers[1].watching?.invalidate()
this.multiCompiler.compilers[2].watching?.invalidate()
return
}
for (const key of keys) {
if (key === 'client') {
this.multiCompiler.compilers[0].watching?.invalidate()
} else if (key === 'server') {
this.multiCompiler.compilers[1].watching?.invalidate()
} else if (key === 'edgeServer') {
this.multiCompiler.compilers[2].watching?.invalidate()
}
}
}
startBuilding() {
this.building = true
}
doneBuilding() {
this.building = false
if (this.rebuildAgain) {
this.rebuildAgain = false
this.invalidate()
}
}
}
/**
* Attempts to find a page file path from the given pages absolute directory,
* a page and allowed extensions. If the page can't be found it will throw an
......
......@@ -573,40 +573,9 @@ export async function renderToHTML(
isPreview,
getRequestMeta(req, '__nextIsLocaleDomain')
)
const jsxStyleRegistry = createStyleRegistry()
const ctx = {
err,
req: isAutoExport ? undefined : req,
res: isAutoExport ? undefined : res,
pathname,
query,
asPath,
locale: renderOpts.locale,
locales: renderOpts.locales,
defaultLocale: renderOpts.defaultLocale,
AppTree: (props: any) => {
return (
<AppContainerWithIsomorphicFiberStructure>
{renderPageTree(App, OriginComponent, { ...props, router })}
</AppContainerWithIsomorphicFiberStructure>
)
},
defaultGetInitialProps: async (
docCtx: DocumentContext,
options: { nonce?: string } = {}
): Promise<DocumentInitialProps> => {
const enhanceApp = (AppComp: any) => {
return (props: any) => <AppComp {...props} />
}
const { html, head } = await docCtx.renderPage({ enhanceApp })
const styles = jsxStyleRegistry.styles({ nonce: options.nonce })
jsxStyleRegistry.flush()
return { html, head, styles }
},
}
let props: any
let scriptLoader: any = {}
const jsxStyleRegistry = createStyleRegistry()
const ampState = {
ampFirst: pageConfig.amp === true,
hasQuery: Boolean(query.amp),
......@@ -615,10 +584,8 @@ export async function renderToHTML(
// Disable AMP under the web environment
const inAmpMode = process.env.NEXT_RUNTIME !== 'edge' && isInAmpMode(ampState)
const reactLoadableModules: string[] = []
let head: JSX.Element[] = defaultHead(inAmpMode)
const reactLoadableModules: string[] = []
let initialScripts: any = {}
if (hasPageScripts) {
......@@ -628,16 +595,6 @@ export async function renderToHTML(
.map((script: any) => script.props)
}
let scriptLoader: any = {}
const nextExport =
!isSSG && (renderOpts.nextExport || (dev && (isAutoExport || isFallback)))
const styledJsxFlushEffect = () => {
const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return <>{styles}</>
}
const AppContainer = ({ children }: { children: JSX.Element }) => (
<RouterContext.Provider value={router}>
<AmpStateContext.Provider value={ampState}>
......@@ -700,6 +657,50 @@ export async function renderToHTML(
)
}
const ctx = {
err,
req: isAutoExport ? undefined : req,
res: isAutoExport ? undefined : res,
pathname,
query,
asPath,
locale: renderOpts.locale,
locales: renderOpts.locales,
defaultLocale: renderOpts.defaultLocale,
AppTree: (props: any) => {
return (
<AppContainerWithIsomorphicFiberStructure>
{renderPageTree(App, OriginComponent, { ...props, router })}
</AppContainerWithIsomorphicFiberStructure>
)
},
defaultGetInitialProps: async (
docCtx: DocumentContext,
options: { nonce?: string } = {}
): Promise<DocumentInitialProps> => {
const enhanceApp = (AppComp: any) => {
return (props: any) => <AppComp {...props} />
}
const { html, head: renderPageHead } = await docCtx.renderPage({
enhanceApp,
})
const styles = jsxStyleRegistry.styles({ nonce: options.nonce })
jsxStyleRegistry.flush()
return { html, head: renderPageHead, styles }
},
}
let props: any
const nextExport =
!isSSG && (renderOpts.nextExport || (dev && (isAutoExport || isFallback)))
const styledJsxFlushEffect = () => {
const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return <>{styles}</>
}
props = await loadGetInitialProps(App, {
AppTree: ctx.AppTree,
Component,
......@@ -1299,7 +1300,7 @@ export async function renderToHTML(
}
const { docProps } = (documentInitialPropsRes as any) || {}
const documentElement = () => {
const documentElement = (htmlProps: any) => {
if (process.env.NEXT_RUNTIME === 'edge') {
return (Document as any)()
} else {
......
......@@ -98,6 +98,34 @@ export const createHeaderRoute = ({
}
}
// since initial query values are decoded by querystring.parse
// we need to re-encode them here but still allow passing through
// values from rewrites/redirects
export const stringifyQuery = (req: BaseNextRequest, query: ParsedUrlQuery) => {
const initialQuery = getRequestMeta(req, '__NEXT_INIT_QUERY') || {}
const initialQueryValues: Array<string | string[]> =
Object.values(initialQuery)
return stringifyQs(query, undefined, undefined, {
encodeURIComponent(value) {
if (
value in initialQuery ||
initialQueryValues.some((initialQueryVal: string | string[]) => {
// `value` always refers to a query value, even if it's nested in an array
return Array.isArray(initialQueryVal)
? initialQueryVal.includes(value)
: initialQueryVal === value
})
) {
// Encode keys and values from initial query
return encodeURIComponent(value)
}
return value
},
})
}
export const createRedirectRoute = ({
rule,
restrictedRedirectPaths,
......@@ -151,31 +179,3 @@ export const createRedirectRoute = ({
},
}
}
// since initial query values are decoded by querystring.parse
// we need to re-encode them here but still allow passing through
// values from rewrites/redirects
export const stringifyQuery = (req: BaseNextRequest, query: ParsedUrlQuery) => {
const initialQuery = getRequestMeta(req, '__NEXT_INIT_QUERY') || {}
const initialQueryValues: Array<string | string[]> =
Object.values(initialQuery)
return stringifyQs(query, undefined, undefined, {
encodeURIComponent(value) {
if (
value in initialQuery ||
initialQueryValues.some((initialQueryVal: string | string[]) => {
// `value` always refers to a query value, even if it's nested in an array
return Array.isArray(initialQueryVal)
? initialQueryVal.includes(value)
: initialQueryVal === value
})
) {
// Encode keys and values from initial query
return encodeURIComponent(value)
}
return value
},
})
}
......@@ -9,6 +9,31 @@ import { relativizeURL } from '../../shared/lib/router/utils/relativize-url'
import { waitUntilSymbol } from './spec-extension/fetch-event'
import { NextURL } from './next-url'
class NextRequestHint extends NextRequest {
sourcePage: string
constructor(params: {
init: RequestInit
input: Request | string
page: string
}) {
super(params.input, params.init)
this.sourcePage = params.page
}
get request() {
throw new PageSignatureError({ page: this.sourcePage })
}
respondWith() {
throw new PageSignatureError({ page: this.sourcePage })
}
waitUntil() {
throw new PageSignatureError({ page: this.sourcePage })
}
}
export async function adapter(params: {
handler: NextMiddleware
page: string
......@@ -205,28 +230,3 @@ function getUnsupportedModuleErrorMessage(module: string) {
return `The edge runtime does not support Node.js '${module}' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`
}
class NextRequestHint extends NextRequest {
sourcePage: string
constructor(params: {
init: RequestInit
input: Request | string
page: string
}) {
super(params.input, params.init)
this.sourcePage = params.page
}
get request() {
throw new PageSignatureError({ page: this.sourcePage })
}
respondWith() {
throw new PageSignatureError({ page: this.sourcePage })
}
waitUntil() {
throw new PageSignatureError({ page: this.sourcePage })
}
}
......@@ -20,6 +20,13 @@ interface ModuleContext {
warnedEvals: Set<string>
}
/**
* A Map of cached module contexts indexed by the module name. It allows
* to have a different cache scoped per module name or depending on the
* provided module key on creation.
*/
const moduleContexts = new Map<string, ModuleContext>()
/**
* For a given path a context, this function checks if there is any module
* context that contains the path with an older content and, if that's the
......@@ -37,13 +44,6 @@ export function clearModuleContext(path: string, content: Buffer | string) {
}
}
/**
* A Map of cached module contexts indexed by the module name. It allows
* to have a different cache scoped per module name or depending on the
* provided module key on creation.
*/
const moduleContexts = new Map<string, ModuleContext>()
interface ModuleContextOptions {
moduleName: string
onWarning: (warn: Error) => void
......
......@@ -638,6 +638,10 @@ declare module 'webpack4' {
*/
type Rule = RuleSetRule
abstract class Plugin {
apply(compiler: Compiler): void
}
namespace Options {
type Devtool =
| 'eval'
......@@ -1447,10 +1451,6 @@ declare module 'webpack4' {
invalidate(): void
}
abstract class Plugin {
apply(compiler: Compiler): void
}
abstract class ResolvePlugin {
apply(resolver: any /* EnhancedResolve.Resolver */): void
}
......
......@@ -50,6 +50,16 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
type ErrorType = 'runtime' | 'build'
const shouldPreventDisplay = (
errorType?: ErrorType | null,
preventType?: ErrorType[] | null
) => {
if (!preventType || !errorType) {
return false
}
return preventType.includes(errorType)
}
const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
children,
preventDisplay,
......@@ -115,14 +125,4 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
)
}
const shouldPreventDisplay = (
errorType?: ErrorType | null,
preventType?: ErrorType[] | null
) => {
if (!preventType || !errorType) {
return false
}
return preventType.includes(errorType)
}
export default ReactDevOverlay
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment