Skip to content

Commit

Permalink
Merge branch 'canary' into update/serverless-url-handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Timer authored Jan 25, 2020
2 parents 38507a6 + f143ca6 commit f4ab825
Show file tree
Hide file tree
Showing 12 changed files with 63 additions and 65 deletions.
2 changes: 1 addition & 1 deletion packages/next/build/babel/plugins/next-page-config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NodePath, PluginObj } from '@babel/core'
import * as BabelTypes from '@babel/types'
import { PageConfig } from '../../../types'
import { PageConfig } from 'next/types'

const configKeys = new Set(['amp'])
const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'
Expand Down
10 changes: 6 additions & 4 deletions packages/next/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import { generateBuildId } from './generate-build-id'
import { isWriteable } from './is-writeable'
import createSpinner from './spinner'
import {
isPageStatic,
collectPages,
getPageSizeInKb,
hasCustomAppGetInitialProps,
Expand Down Expand Up @@ -416,7 +417,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
const staticCheckWorkers = new Worker(staticCheckWorker, {
numWorkers: config.experimental.cpus,
enableWorkerThreads: config.experimental.workerThreads,
})
}) as Worker & { isPageStatic: typeof isPageStatic }

staticCheckWorkers.getStdout().pipe(process.stdout)
staticCheckWorkers.getStderr().pipe(process.stderr)

Expand Down Expand Up @@ -481,7 +483,7 @@ export default async function build(dir: string, conf = null): Promise<void> {

if (nonReservedPage) {
try {
let result: any = await (staticCheckWorkers as any).isPageStatic(
let result = await staticCheckWorkers.isPageStatic(
page,
serverBundle,
runtimeEnvConfig
Expand All @@ -492,15 +494,15 @@ export default async function build(dir: string, conf = null): Promise<void> {
hybridAmpPages.add(page)
}

if (result.prerender) {
if (result.hasStaticProps) {
ssgPages.add(page)
isSsg = true

if (result.prerenderRoutes) {
additionalSsgPaths.set(page, result.prerenderRoutes)
ssgPageRoutes = result.prerenderRoutes
}
} else if (result.static && customAppGetInitialProps === false) {
} else if (result.isStatic && customAppGetInitialProps === false) {
staticPages.add(page)
isStatic = true
}
Expand Down
8 changes: 4 additions & 4 deletions packages/next/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,9 +479,9 @@ export async function isPageStatic(
serverBundle: string,
runtimeEnvConfig: any
): Promise<{
static?: boolean
prerender?: boolean
isStatic?: boolean
isHybridAmp?: boolean
hasStaticProps?: boolean
prerenderRoutes?: string[] | undefined
}> {
try {
Expand Down Expand Up @@ -593,10 +593,10 @@ export async function isPageStatic(

const config = mod.config || {}
return {
static: !hasStaticProps && !hasGetInitialProps,
isStatic: !hasStaticProps && !hasGetInitialProps,
isHybridAmp: config.amp === 'hybrid',
prerenderRoutes: prerenderPaths,
prerender: hasStaticProps,
hasStaticProps,
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') return {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from '../../../next-server/lib/constants'
import { isDynamicRoute } from '../../../next-server/lib/router/utils'
import { API_ROUTE } from '../../../lib/constants'
import escapeRegexp from 'escape-string-regexp'

export type ServerlessLoaderQuery = {
page: string
Expand Down Expand Up @@ -46,7 +47,7 @@ const nextServerlessLoader: loader.Loader = function() {
)
const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, '/')

const escapedBuildId = buildId.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&')
const escapedBuildId = escapeRegexp(buildId)
const pageIsDynamicRoute = isDynamicRoute(page)

const dynamicRouteImports = pageIsDynamicRoute
Expand Down
2 changes: 1 addition & 1 deletion packages/next/next-server/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ParsedUrlQuery } from 'querystring'
import { ComponentType } from 'react'
import { format, URLFormatOptions, UrlObject } from 'url'

import { ManifestItem } from '../server/render'
import { ManifestItem } from '../server/load-components'
import { NextRouter } from './router/router'

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/next/next-server/server/api-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Stream } from 'stream'
import getRawBody from 'raw-body'
import { parse } from 'content-type'
import { Params } from './router'
import { PageConfig } from '../../types'
import { PageConfig } from 'next/types'
import { interopDefault } from './load-components'
import { isResSent } from '../lib/utils'

Expand Down
48 changes: 32 additions & 16 deletions packages/next/next-server/server/load-components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,44 @@ import {
SERVER_DIRECTORY,
} from '../lib/constants'
import { join } from 'path'
import { PageConfig } from '../../types'
import { requirePage } from './require'
import { ParsedUrlQuery } from 'querystring'
import { BuildManifest } from './get-page-files'
import { AppType, DocumentType } from '../lib/utils'
import { PageConfig, NextPageContext } from 'next/types'

export function interopDefault(mod: any) {
return mod.default || mod
}

export type ManifestItem = {
id: number | string
name: string
file: string
publicPath: string
}

type ReactLoadableManifest = { [moduleId: string]: ManifestItem[] }

type Unstable_getStaticProps = (params: {
params: ParsedUrlQuery | undefined
}) => Promise<{
props: { [key: string]: any }
revalidate?: number | boolean
}>

type Unstable_getStaticPaths = () => Promise<Array<string | ParsedUrlQuery>>

export type LoadComponentsReturnType = {
Component: any
pageConfig: PageConfig
unstable_getStaticProps?: (params: {
params: any
}) => {
props: any
revalidate?: number | boolean
}
unstable_getStaticPaths?: () => void
buildManifest?: any
reactLoadableManifest?: any
Document?: any
DocumentMiddleware?: any
App?: any
Component: React.ComponentType
pageConfig?: PageConfig
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
Document: DocumentType
DocumentMiddleware?: (ctx: NextPageContext) => void
App: AppType
unstable_getStaticProps?: Unstable_getStaticProps
unstable_getStaticPaths?: Unstable_getStaticPaths
}

export async function loadComponents(
Expand All @@ -42,7 +58,7 @@ export async function loadComponents(
pageConfig: Component.config || {},
unstable_getStaticProps: Component.unstable_getStaticProps,
unstable_getStaticPaths: Component.unstable_getStaticPaths,
}
} as LoadComponentsReturnType
}
const documentPath = join(
distDir,
Expand Down
10 changes: 7 additions & 3 deletions packages/next/next-server/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -863,15 +863,15 @@ export default class Server {
// check request state
const isLikeServerless =
typeof result.Component === 'object' &&
typeof result.Component.renderReqToHTML === 'function'
typeof (result.Component as any).renderReqToHTML === 'function'
const isSSG = !!result.unstable_getStaticProps

// non-spr requests should render like normal
if (!isSSG) {
// handle serverless
if (isLikeServerless) {
this.prepareServerlessUrl(req, query)
return result.Component.renderReqToHTML(req, res)
return (result.Component as any).renderReqToHTML(req, res)
}

return renderToHTML(req, res, pathname, query, {
Expand Down Expand Up @@ -929,7 +929,11 @@ export default class Server {
let renderResult
// handle serverless
if (isLikeServerless) {
renderResult = await result.Component.renderReqToHTML(req, res, true)
renderResult = await (result.Component as any).renderReqToHTML(
req,
res,
true
)

html = renderResult.html
pageData = renderResult.renderOpts.pageData
Expand Down
34 changes: 4 additions & 30 deletions packages/next/next-server/server/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,19 @@ import {
NextComponentType,
DocumentType,
AppType,
NextPageContext,
} from '../lib/utils'
import Head, { defaultHead } from '../lib/head'
// @ts-ignore types will be added later as it's an internal module
import Loadable from '../lib/loadable'
import { LoadableContext } from '../lib/loadable-context'
import { RouterContext } from '../lib/router-context'
import { getPageFiles, BuildManifest } from './get-page-files'
import { getPageFiles } from './get-page-files'
import { AmpStateContext } from '../lib/amp-context'
import optimizeAmp from './optimize-amp'
import { isInAmpMode } from '../lib/amp'
// Uses a module path because of the compiled output directory location
import { PageConfig } from 'next/types'
import { isDynamicRoute } from '../lib/router/utils/is-dynamic'
import { SSG_GET_INITIAL_PROPS_CONFLICT } from '../../lib/constants'
import { AMP_RENDER_TARGET } from '../lib/constants'

export type ManifestItem = {
id: number | string
name: string
file: string
publicPath: string
}

type ReactLoadableManifest = { [moduleId: string]: ManifestItem[] }
import { LoadComponentsReturnType, ManifestItem } from './load-components'

function noRouter() {
const message =
Expand Down Expand Up @@ -122,8 +110,7 @@ function render(
return { html, head }
}

type RenderOpts = {
documentMiddlewareEnabled: boolean
type RenderOpts = LoadComponentsReturnType & {
staticMarkup: boolean
buildId: string
canonicalBase: string
Expand All @@ -139,22 +126,9 @@ type RenderOpts = {
ampPath?: string
inAmpMode?: boolean
hybridAmp?: boolean
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
pageConfig: PageConfig
Component: React.ComponentType
Document: DocumentType
DocumentMiddleware: (ctx: NextPageContext) => void
App: AppType
ErrorDebug?: React.ComponentType<{ error: Error }>
ampValidator?: (html: string, pathname: string) => Promise<void>
unstable_getStaticProps?: (params: {
params: any | undefined
}) => {
props: any
revalidate?: number | boolean
}
unstable_getStaticPaths?: () => void
documentMiddlewareEnabled?: boolean
}

function renderDocument(
Expand Down
1 change: 1 addition & 0 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"css-loader": "3.3.0",
"cssnano-simple": "1.0.0",
"devalue": "2.0.1",
"escape-string-regexp": "2.0.0",
"etag": "1.8.1",
"file-loader": "4.2.0",
"find-up": "4.0.0",
Expand Down
3 changes: 1 addition & 2 deletions test/integration/custom-routes/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import escapeRegex from 'escape-string-regexp'
import {
launchApp,
killApp,
Expand All @@ -29,8 +30,6 @@ let stdout = ''
let appPort
let app

const escapeRegex = str => str.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&')

const runTests = (isDev = false) => {
it('should handle one-to-one rewrite successfully', async () => {
const html = await renderViaHTTP(appPort, '/first')
Expand Down
5 changes: 3 additions & 2 deletions test/integration/prerender/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
/* global jasmine */
import fs from 'fs-extra'
import { join } from 'path'
import webdriver from 'next-webdriver'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import escapeRegex from 'escape-string-regexp'
import {
renderViaHTTP,
fetchViaHTTP,
Expand Down Expand Up @@ -420,7 +421,7 @@ const runTests = (dev = false) => {
const manifest = JSON.parse(
await fs.readFile(join(appDir, '.next/prerender-manifest.json'), 'utf8')
)
const escapedBuildId = buildId.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&')
const escapedBuildId = escapeRegex(buildId)

Object.keys(manifest.dynamicRoutes).forEach(key => {
const item = manifest.dynamicRoutes[key]
Expand Down

0 comments on commit f4ab825

Please sign in to comment.