Unverified Commit b31c2967 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Experimental: Serverless Trace target (#8246)

* Experimental: Serverless Trace target
The Serverless Trace target produces Serverless-handler wrapped entrypoints, but does not bundle all of `node_modules`.

This behavior increases bundling performance to be more akin to `target: 'server'`.

This mode is expected to be used with smart platforms (like [ZEIT Now](https://zeit.co/now) that can trace a program to its minimum dependencies.

* Use more generic variables

* Add asset relocator for production mode of serverless trace

* Verify Firebase compatiblity

* Revert "Add asset relocator for production mode of serverless trace"

This reverts commit 8404f1dcf28b60edab41a56c94b38dcd3fddec20.

* Add serverless trace tests

* Add _isLikeServerless helper

* Make constants

* Fix export

* Update packages/next-server/server/config.ts
Co-Authored-By: 's avatarJJ Kasper <jj@jjsweb.site>

* Use a global helper for is like serverless

* Update import for isTargetLikeServerless

* Update packages/next/build/index.ts
Co-Authored-By: 's avatarJJ Kasper <jj@jjsweb.site>
parent f40a9015
...@@ -81,6 +81,7 @@ ...@@ -81,6 +81,7 @@
"execa": "2.0.3", "execa": "2.0.3",
"express": "4.17.0", "express": "4.17.0",
"faunadb": "2.6.1", "faunadb": "2.6.1",
"firebase": "6.3.4",
"fs-extra": "7.0.1", "fs-extra": "7.0.1",
"get-port": "5.0.0", "get-port": "5.0.0",
"isomorphic-unfetch": "3.0.0", "isomorphic-unfetch": "3.0.0",
......
import os from 'os'
import findUp from 'find-up' import findUp from 'find-up'
import os from 'os'
import { CONFIG_FILE } from '../lib/constants' import { CONFIG_FILE } from '../lib/constants'
import { execOnce } from '../lib/utils' import { execOnce } from '../lib/utils'
const targets = ['server', 'serverless'] const targets = ['server', 'serverless', 'experimental-serverless-trace']
const defaultConfig: { [key: string]: any } = { const defaultConfig: { [key: string]: any } = {
env: [], env: [],
...@@ -120,10 +121,12 @@ export default function loadConfig( ...@@ -120,10 +121,12 @@ export default function loadConfig(
} }
if ( if (
userConfig.target === 'serverless' && userConfig.target &&
userConfig.target !== 'server' &&
userConfig.publicRuntimeConfig && userConfig.publicRuntimeConfig &&
Object.keys(userConfig.publicRuntimeConfig).length !== 0 Object.keys(userConfig.publicRuntimeConfig).length !== 0
) { ) {
// TODO: change error message tone to "Only compatible with [fat] server mode"
throw new Error( throw new Error(
'Cannot use publicRuntimeConfig with target=serverless https://err.sh/zeit/next.js/serverless-publicRuntimeConfig' 'Cannot use publicRuntimeConfig with target=serverless https://err.sh/zeit/next.js/serverless-publicRuntimeConfig'
) )
...@@ -134,3 +137,9 @@ export default function loadConfig( ...@@ -134,3 +137,9 @@ export default function loadConfig(
return defaultConfig return defaultConfig
} }
export function isTargetLikeServerless(target: string) {
const isServerless = target === 'serverless'
const isServerlessTrace = target === 'experimental-serverless-trace'
return isServerless || isServerlessTrace
}
import compression from 'compression'
import fs from 'fs' import fs from 'fs'
import { IncomingMessage, ServerResponse } from 'http' import { IncomingMessage, ServerResponse } from 'http'
import { join, resolve, sep } from 'path' import { join, resolve, sep } from 'path'
import { parse as parseQs, ParsedUrlQuery } from 'querystring' import { parse as parseQs, ParsedUrlQuery } from 'querystring'
import { parse as parseUrl, UrlWithParsedQuery } from 'url' import { parse as parseUrl, UrlWithParsedQuery } from 'url'
import compression from 'compression'
import { import {
BUILD_ID_FILE, BUILD_ID_FILE,
BUILD_MANIFEST,
CLIENT_PUBLIC_FILES_PATH, CLIENT_PUBLIC_FILES_PATH,
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
CLIENT_STATIC_FILES_RUNTIME, CLIENT_STATIC_FILES_RUNTIME,
...@@ -25,12 +24,12 @@ import { ...@@ -25,12 +24,12 @@ import {
import * as envConfig from '../lib/runtime-config' import * as envConfig from '../lib/runtime-config'
import { NextApiRequest, NextApiResponse } from '../lib/utils' import { NextApiRequest, NextApiResponse } from '../lib/utils'
import { apiResolver } from './api-utils' import { apiResolver } from './api-utils'
import loadConfig from './config' import loadConfig, { isTargetLikeServerless } from './config'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync' import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { loadComponents, LoadComponentsReturnType } from './load-components' import { loadComponents, LoadComponentsReturnType } from './load-components'
import { renderToHTML } from './render' import { renderToHTML } from './render'
import { getPagePath } from './require' import { getPagePath } from './require'
import Router, { route, Route, RouteMatch, Params } from './router' import Router, { Params, route, Route, RouteMatch } from './router'
import { sendHTML } from './send-html' import { sendHTML } from './send-html'
import { serveStatic } from './serve-static' import { serveStatic } from './serve-static'
import { isBlockedPage, isInternalUrl } from './utils' import { isBlockedPage, isInternalUrl } from './utils'
...@@ -98,7 +97,9 @@ export default class Server { ...@@ -98,7 +97,9 @@ export default class Server {
this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH) this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
this.pagesManifest = join( this.pagesManifest = join(
this.distDir, this.distDir,
this.nextConfig.target || 'server', this.nextConfig.target === 'server'
? SERVER_DIRECTORY
: SERVERLESS_DIRECTORY,
PAGES_MANIFEST PAGES_MANIFEST
) )
...@@ -131,7 +132,7 @@ export default class Server { ...@@ -131,7 +132,7 @@ export default class Server {
this.renderOpts.runtimeConfig = publicRuntimeConfig this.renderOpts.runtimeConfig = publicRuntimeConfig
} }
if (compress && this.nextConfig.target !== 'serverless') { if (compress && this.nextConfig.target === 'server') {
this.compression = compression() as Middleware this.compression = compression() as Middleware
} }
...@@ -319,7 +320,7 @@ export default class Server { ...@@ -319,7 +320,7 @@ export default class Server {
return this.render404(req, res) return this.render404(req, res)
} }
if (!this.renderOpts.dev && this.nextConfig.target === 'serverless') { if (!this.renderOpts.dev && this._isLikeServerless) {
const mod = require(resolverFunction) const mod = require(resolverFunction)
if (typeof mod.default === 'function') { if (typeof mod.default === 'function') {
return mod.default(req, res) return mod.default(req, res)
...@@ -342,7 +343,7 @@ export default class Server { ...@@ -342,7 +343,7 @@ export default class Server {
return getPagePath( return getPagePath(
pathname, pathname,
this.distDir, this.distDir,
this.nextConfig.target === 'serverless', this._isLikeServerless,
this.renderOpts.dev this.renderOpts.dev
) )
} }
...@@ -352,9 +353,7 @@ export default class Server { ...@@ -352,9 +353,7 @@ export default class Server {
const publicFiles = recursiveReadDirSync(this.publicDir) const publicFiles = recursiveReadDirSync(this.publicDir)
const serverBuildPath = join( const serverBuildPath = join(
this.distDir, this.distDir,
this.nextConfig.target === 'serverless' this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
? SERVERLESS_DIRECTORY
: SERVER_DIRECTORY
) )
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST)) const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
...@@ -458,8 +457,7 @@ export default class Server { ...@@ -458,8 +457,7 @@ export default class Server {
pathname: string, pathname: string,
query: ParsedUrlQuery = {} query: ParsedUrlQuery = {}
) { ) {
const serverless = const serverless = !this.renderOpts.dev && this._isLikeServerless
!this.renderOpts.dev && this.nextConfig.target === 'serverless'
// try serving a static AMP version first // try serving a static AMP version first
if (query.amp) { if (query.amp) {
try { try {
...@@ -708,4 +706,8 @@ export default class Server { ...@@ -708,4 +706,8 @@ export default class Server {
throw err throw err
} }
} }
private get _isLikeServerless(): boolean {
return isTargetLikeServerless(this.nextConfig.target)
}
} }
import { isTargetLikeServerless } from 'next-server/dist/server/config'
import { join } from 'path' import { join } from 'path'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { PAGES_DIR_ALIAS, DOT_NEXT_ALIAS, API_ROUTE } from '../lib/constants'
import { API_ROUTE, DOT_NEXT_ALIAS, PAGES_DIR_ALIAS } from '../lib/constants'
import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader' import { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
type PagesMapping = { type PagesMapping = {
...@@ -45,7 +47,7 @@ type Entrypoints = { ...@@ -45,7 +47,7 @@ type Entrypoints = {
export function createEntrypoints( export function createEntrypoints(
pages: PagesMapping, pages: PagesMapping,
target: 'server' | 'serverless', target: 'server' | 'serverless' | 'experimental-serverless-trace',
buildId: string, buildId: string,
dynamicBuildId: boolean, dynamicBuildId: boolean,
config: any config: any
...@@ -72,7 +74,9 @@ export function createEntrypoints( ...@@ -72,7 +74,9 @@ export function createEntrypoints(
const bundlePath = join('static', buildId, 'pages', bundleFile) const bundlePath = join('static', buildId, 'pages', bundleFile)
if (isApiRoute && target === 'serverless') { const isLikeServerless = isTargetLikeServerless(target)
if (isApiRoute && isLikeServerless) {
const serverlessLoaderOptions: ServerlessLoaderQuery = { const serverlessLoaderOptions: ServerlessLoaderQuery = {
page, page,
absolutePagePath, absolutePagePath,
...@@ -83,11 +87,7 @@ export function createEntrypoints( ...@@ -83,11 +87,7 @@ export function createEntrypoints(
)}!` )}!`
} else if (isApiRoute || target === 'server') { } else if (isApiRoute || target === 'server') {
server[bundlePath] = [absolutePagePath] server[bundlePath] = [absolutePagePath]
} else if ( } else if (isLikeServerless && page !== '/_app' && page !== '/_document') {
target === 'serverless' &&
page !== '/_app' &&
page !== '/_document'
) {
const serverlessLoaderOptions: ServerlessLoaderQuery = { const serverlessLoaderOptions: ServerlessLoaderQuery = {
page, page,
absolutePagePath, absolutePagePath,
......
import { Sema } from 'async-sema'
import chalk from 'chalk' import chalk from 'chalk'
import fs from 'fs'
import mkdirpOrig from 'mkdirp'
import { import {
SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
PAGES_MANIFEST,
CHUNK_GRAPH_MANIFEST, CHUNK_GRAPH_MANIFEST,
PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
} from 'next-server/constants' } from 'next-server/constants'
import loadConfig from 'next-server/next-config' import loadConfig, {
isTargetLikeServerless,
} from 'next-server/dist/server/config'
import nanoid from 'next/dist/compiled/nanoid/index.js' import nanoid from 'next/dist/compiled/nanoid/index.js'
import path from 'path' import path from 'path'
import fs from 'fs'
import { promisify } from 'util' import { promisify } from 'util'
import workerFarm from 'worker-farm'
import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages'
import { recursiveDelete } from '../lib/recursive-delete' import { recursiveDelete } from '../lib/recursive-delete'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup' import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup'
import { CompilerResult, runCompiler } from './compiler' import { CompilerResult, runCompiler } from './compiler'
import { createEntrypoints, createPagesMapping } from './entries' import { createEntrypoints, createPagesMapping } from './entries'
...@@ -25,9 +32,9 @@ import { ...@@ -25,9 +32,9 @@ import {
getFileForPage, getFileForPage,
getPageSizeInKb, getPageSizeInKb,
getSpecifiedPages, getSpecifiedPages,
printTreeView,
PageInfo,
hasCustomAppGetInitialProps, hasCustomAppGetInitialProps,
PageInfo,
printTreeView,
} from './utils' } from './utils'
import getBaseWebpackConfig from './webpack-config' import getBaseWebpackConfig from './webpack-config'
import { import {
...@@ -35,10 +42,6 @@ import { ...@@ -35,10 +42,6 @@ import {
getPageChunks, getPageChunks,
} from './webpack/plugins/chunk-graph-plugin' } from './webpack/plugins/chunk-graph-plugin'
import { writeBuildId } from './write-build-id' import { writeBuildId } from './write-build-id'
import { recursiveReadDir } from '../lib/recursive-readdir'
import mkdirpOrig from 'mkdirp'
import workerFarm from 'worker-farm'
import { Sema } from 'async-sema'
const fsUnlink = promisify(fs.unlink) const fsUnlink = promisify(fs.unlink)
const fsRmdir = promisify(fs.rmdir) const fsRmdir = promisify(fs.rmdir)
...@@ -75,11 +78,13 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -75,11 +78,13 @@ export default async function build(dir: string, conf = null): Promise<void> {
isFlyingShuttle || process.env.__NEXT_BUILDER_EXPERIMENTAL_PAGE isFlyingShuttle || process.env.__NEXT_BUILDER_EXPERIMENTAL_PAGE
) )
const isLikeServerless = isTargetLikeServerless(target)
if (selectivePageBuilding && target !== 'serverless') { if (selectivePageBuilding && target !== 'serverless') {
throw new Error( throw new Error(
`Cannot use ${ `Cannot use ${
isFlyingShuttle ? 'flying shuttle' : '`now dev`' isFlyingShuttle ? 'flying shuttle' : '`now dev`'
} without the serverless target.` } without the \`serverless\` target.`
) )
} }
...@@ -199,7 +204,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -199,7 +204,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
]) ])
let result: CompilerResult = { warnings: [], errors: [] } let result: CompilerResult = { warnings: [], errors: [] }
if (target === 'serverless') { // TODO: why do we need this?? https://github.com/zeit/next.js/issues/8253
if (isLikeServerless) {
const clientResult = await runCompiler(configs[0]) const clientResult = await runCompiler(configs[0])
// Fail build if clientResult contains errors // Fail build if clientResult contains errors
if (clientResult.errors.length > 0) { if (clientResult.errors.length > 0) {
...@@ -273,7 +279,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -273,7 +279,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
const pageKeys = Object.keys(mappedPages) const pageKeys = Object.keys(mappedPages)
const manifestPath = path.join( const manifestPath = path.join(
distDir, distDir,
target === 'serverless' ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY, isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
PAGES_MANIFEST PAGES_MANIFEST
) )
...@@ -303,12 +309,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -303,12 +309,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
const actualPage = page === '/' ? '/index' : page const actualPage = page === '/' ? '/index' : page
const size = await getPageSizeInKb(actualPage, distPath, buildId) const size = await getPageSizeInKb(actualPage, distPath, buildId)
const bundleRelative = path.join( const bundleRelative = path.join(
target === 'serverless' ? 'pages' : `static/${buildId}/pages`, isLikeServerless ? 'pages' : `static/${buildId}/pages`,
actualPage + '.js' actualPage + '.js'
) )
const serverBundle = path.join( const serverBundle = path.join(
distPath, distPath,
target === 'serverless' ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY, isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
bundleRelative bundleRelative
) )
...@@ -324,7 +330,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -324,7 +330,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (nonReservedPage && customAppGetInitialProps === undefined) { if (nonReservedPage && customAppGetInitialProps === undefined) {
customAppGetInitialProps = hasCustomAppGetInitialProps( customAppGetInitialProps = hasCustomAppGetInitialProps(
target === 'serverless' isLikeServerless
? serverBundle ? serverBundle
: path.join( : path.join(
distPath, distPath,
...@@ -437,7 +443,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -437,7 +443,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
for (const file of toMove) { for (const file of toMove) {
const orig = path.join(exportOptions.outdir, file) const orig = path.join(exportOptions.outdir, file)
const dest = path.join(serverDir, file) const dest = path.join(serverDir, file)
const relativeDest = (target === 'serverless' const relativeDest = (isLikeServerless
? path.join('pages', file) ? path.join('pages', file)
: path.join('static', buildId, 'pages', file) : path.join('static', buildId, 'pages', file)
).replace(/\\/g, '/') ).replace(/\\/g, '/')
...@@ -465,9 +471,5 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -465,9 +471,5 @@ export default async function build(dir: string, conf = null): Promise<void> {
await flyingShuttle.save(allStaticPages, pageInfos) await flyingShuttle.save(allStaticPages, pageInfos)
} }
printTreeView( printTreeView(Object.keys(allMappedPages), allPageInfos, isLikeServerless)
Object.keys(allMappedPages),
allPageInfos,
target === 'serverless'
)
} }
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin' import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import fs from 'fs'
import { import {
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK, CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
} from 'next-server/constants' } from 'next-server/constants'
import resolve from 'next/dist/compiled/resolve/index.js' import resolve from 'next/dist/compiled/resolve/index.js'
import path from 'path' import path from 'path'
...@@ -25,6 +25,7 @@ import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin' ...@@ -25,6 +25,7 @@ import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
import { importAutoDllPlugin } from './webpack/plugins/dll-import' import { importAutoDllPlugin } from './webpack/plugins/dll-import'
import { HashedChunkIdsPlugin } from './webpack/plugins/hashed-chunk-ids-plugin' import { HashedChunkIdsPlugin } from './webpack/plugins/hashed-chunk-ids-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin' import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import' import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import'
import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache' import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin' import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
...@@ -32,7 +33,6 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin' ...@@ -32,7 +33,6 @@ import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { ServerlessPlugin } from './webpack/plugins/serverless-plugin' import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin' import { SharedRuntimePlugin } from './webpack/plugins/shared-runtime-plugin'
import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index' import { TerserPlugin } from './webpack/plugins/terser-webpack-plugin/src/index'
import NextEsmPlugin from './webpack/plugins/next-esm-plugin'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
...@@ -79,7 +79,12 @@ export default async function getBaseWebpackConfig( ...@@ -79,7 +79,12 @@ export default async function getBaseWebpackConfig(
.split(process.platform === 'win32' ? ';' : ':') .split(process.platform === 'win32' ? ';' : ':')
.filter(p => !!p) .filter(p => !!p)
const outputDir = target === 'serverless' ? 'serverless' : SERVER_DIRECTORY const isServerless = target === 'serverless'
const isServerlessTrace = target === 'experimental-serverless-trace'
// Intentionally not using isTargetLikeServerless helper
const isLikeServerless = isServerless || isServerlessTrace
const outputDir = isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
const outputPath = path.join(distDir, isServer ? outputDir : '') const outputPath = path.join(distDir, isServer ? outputDir : '')
const totalPages = Object.keys(entrypoints).length const totalPages = Object.keys(entrypoints).length
const clientEntries = !isServer const clientEntries = !isServer
...@@ -238,7 +243,7 @@ export default async function getBaseWebpackConfig( ...@@ -238,7 +243,7 @@ export default async function getBaseWebpackConfig(
target: isServer ? 'node' : 'web', target: isServer ? 'node' : 'web',
externals: !isServer externals: !isServer
? undefined ? undefined
: target !== 'serverless' : !isServerless
? [ ? [
(context, request, callback) => { (context, request, callback) => {
const notExternalModules = [ const notExternalModules = [
...@@ -293,8 +298,8 @@ export default async function getBaseWebpackConfig( ...@@ -293,8 +298,8 @@ export default async function getBaseWebpackConfig(
}, },
] ]
: [ : [
// When the serverless target is used all node_modules will be compiled into the output bundles // When the 'serverless' target is used all node_modules will be compiled into the output bundles
// So that the serverless bundles have 0 runtime dependencies // So that the 'serverless' bundles have 0 runtime dependencies
'amp-toolbox-optimizer', // except this one 'amp-toolbox-optimizer', // except this one
(context, request, callback) => { (context, request, callback) => {
if ( if (
...@@ -561,11 +566,14 @@ export default async function getBaseWebpackConfig( ...@@ -561,11 +566,14 @@ export default async function getBaseWebpackConfig(
) )
}, },
}), }),
target === 'serverless' && isLikeServerless &&
(isServer || selectivePageBuilding) && new ServerlessPlugin(buildId, {
new ServerlessPlugin(buildId, { isServer }), isServer,
isServer && new PagesManifestPlugin(target === 'serverless'), isFlyingShuttle: selectivePageBuilding,
target !== 'serverless' && isTrace: isServerlessTrace,
}),
isServer && new PagesManifestPlugin(isLikeServerless),
target === 'server' &&
isServer && isServer &&
new NextJsSSRModuleCachePlugin({ outputPath }), new NextJsSSRModuleCachePlugin({ outputPath }),
isServer && new NextJsSsrImportPlugin(), isServer && new NextJsSsrImportPlugin(),
......
...@@ -54,18 +54,47 @@ function interceptFileWrites( ...@@ -54,18 +54,47 @@ function interceptFileWrites(
export class ServerlessPlugin { export class ServerlessPlugin {
private buildId: string private buildId: string
private isServer: boolean private isServer: boolean
private isTrace: boolean
private isFlyingShuttle: boolean
constructor(buildId: string, { isServer = false } = {}) { constructor(
buildId: string,
{
isServer,
isTrace,
isFlyingShuttle,
}: { isServer: boolean; isTrace: boolean; isFlyingShuttle: boolean }
) {
this.buildId = buildId this.buildId = buildId
this.isServer = isServer this.isServer = isServer
this.isTrace = isTrace
this.isFlyingShuttle = isFlyingShuttle
} }
apply(compiler: Compiler) { apply(compiler: Compiler) {
if (this.isServer) { if (!this.isServer) {
if (this.isFlyingShuttle) {
compiler.hooks.emit.tap('ServerlessPlugin', compilation => {
const assetNames = Object.keys(compilation.assets).filter(f =>
f.includes(this.buildId)
)
for (const name of assetNames) {
compilation.assets[
name
.replace(new RegExp(`${this.buildId}[\\/\\\\]`), 'client/')
.replace(/[.]js$/, `.${this.buildId}.js`)
] = compilation.assets[name]
}
})
}
return
}
interceptFileWrites(compiler, content => interceptFileWrites(compiler, content =>
replaceInBuffer(content, NEXT_REPLACE_BUILD_ID, this.buildId) replaceInBuffer(content, NEXT_REPLACE_BUILD_ID, this.buildId)
) )
if (!this.isTrace) {
compiler.hooks.compilation.tap('ServerlessPlugin', compilation => { compiler.hooks.compilation.tap('ServerlessPlugin', compilation => {
compilation.hooks.optimizeChunksBasic.tap( compilation.hooks.optimizeChunksBasic.tap(
'ServerlessPlugin', 'ServerlessPlugin',
...@@ -86,19 +115,6 @@ export class ServerlessPlugin { ...@@ -86,19 +115,6 @@ export class ServerlessPlugin {
} }
) )
}) })
} else {
compiler.hooks.emit.tap('ServerlessPlugin', compilation => {
const assetNames = Object.keys(compilation.assets).filter(f =>
f.includes(this.buildId)
)
for (const name of assetNames) {
compilation.assets[
name
.replace(new RegExp(`${this.buildId}[\\/\\\\]`), 'client/')
.replace(/[.]js$/, `.${this.buildId}.js`)
] = compilation.assets[name]
}
})
} }
} }
} }
...@@ -4,7 +4,9 @@ import { recursiveCopy } from '../lib/recursive-copy' ...@@ -4,7 +4,9 @@ import { recursiveCopy } from '../lib/recursive-copy'
import mkdirpModule from 'mkdirp' import mkdirpModule from 'mkdirp'
import { resolve, join } from 'path' import { resolve, join } from 'path'
import { existsSync, readFileSync } from 'fs' import { existsSync, readFileSync } from 'fs'
import loadConfig from 'next-server/next-config' import loadConfig, {
isTargetLikeServerless
} from 'next-server/dist/server/config'
import { import {
PHASE_EXPORT, PHASE_EXPORT,
SERVER_DIRECTORY, SERVER_DIRECTORY,
...@@ -183,7 +185,7 @@ export default async function (dir, options, configuration) { ...@@ -183,7 +185,7 @@ export default async function (dir, options, configuration) {
serverRuntimeConfig, serverRuntimeConfig,
concurrency, concurrency,
subFolders, subFolders,
serverless: nextConfig.target === 'serverless' serverless: isTargetLikeServerless(nextConfig.target)
}) })
worker.on('message', ({ type, payload }) => { worker.on('message', ({ type, payload }) => {
if (type === 'progress' && progress) { if (type === 'progress' && progress) {
......
module.exports = {
target: 'experimental-serverless-trace',
onDemandEntries: {
maxInactiveAge: 1000 * 60 * 60
}
}
import firebase from 'firebase/app'
import 'firebase/firestore'
if (!firebase.apps.length) {
firebase.initializeApp({ projectId: 'noop' })
}
const store = firebase.firestore()
const Comp = ({ results }) => {
return <div>Hello Firebase: {results}</div>
}
Comp.getInitialProps = async () => {
const query = await store.collection('users').get()
return { results: query.size }
}
export default Comp
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import {
killApp,
findPort,
nextBuild,
nextStart,
renderViaHTTP
} from 'next-test-utils'
const appDir = join(__dirname, '../')
let appPort
let app
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
describe('External Assets', () => {
beforeAll(async () => {
await nextBuild(appDir, [])
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
it('should support Firebase', async () => {
const html = await renderViaHTTP(appPort, '/about/history')
expect(html).toMatch(/Hello Firebase: <!-- -->0/)
})
})
module.exports = {
target: 'experimental-serverless-trace',
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
},
experimental: {
publicDirectory: true
},
// make sure error isn't thrown from empty publicRuntimeConfig
publicRuntimeConfig: {}
}
export default () => <div>test</div>
export default (req, res) => {
res.send('hello world')
}
export default (req, res) => {
res.json({ post: req.query.id })
}
import dynamic from 'next/dynamic'
const Hello = dynamic(() => import('../components/hello'))
export default () => (
<div>
<Hello />
</div>
)
import dynamic from 'next/dynamic'
const Hello = dynamic(() => import('../components/hello'))
export default () => (
<div>
<Hello />
</div>
)
import fetch from 'isomorphic-unfetch'
import React from 'react'
export default class extends React.Component {
static async getInitialProps () {
try {
const res = await fetch('')
const text = await res.text()
console.log(text)
return { text }
} catch (err) {
if (err.message.includes('is not a function')) {
return { failed: true, error: err.toString() }
}
return { error: err.toString() }
}
}
render () {
const { failed, error, text } = this.props
return (
<div className='fetch-page'>
{failed ? 'failed' : ''}
{error}
<div id='text'>{text}</div>
</div>
)
}
}
import Link from 'next/link'
export default () => {
return (
<div>
Hello World
<Link href='/fetch'>
<a id='fetchlink'>fetch page</a>
</Link>
</div>
)
}
export default () => `Hi Im an AMP page!`
export const config = { amp: 'hybrid' }
/* eslint-env jest */
/* global jasmine */
import webdriver from 'next-webdriver'
import { join } from 'path'
import { existsSync } from 'fs'
import {
killApp,
findPort,
nextBuild,
nextStart,
fetchViaHTTP,
renderViaHTTP
} from 'next-test-utils'
import fetch from 'node-fetch'
const appDir = join(__dirname, '../')
const serverlessDir = join(appDir, '.next/serverless/pages')
let appPort
let app
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
describe('Serverless', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
it('should render the page', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Hello World/)
})
it('should serve file from public folder', async () => {
const content = await renderViaHTTP(appPort, '/hello.txt')
expect(content.trim()).toBe('hello world')
})
it('should render the page with dynamic import', async () => {
const html = await renderViaHTTP(appPort, '/dynamic')
expect(html).toMatch(/Hello!/)
})
it('should render the page with same dynamic import', async () => {
const html = await renderViaHTTP(appPort, '/dynamic-two')
expect(html).toMatch(/Hello!/)
})
it('should render 404', async () => {
const html = await renderViaHTTP(appPort, '/404')
expect(html).toMatch(/This page could not be found/)
})
it('should render an AMP page', async () => {
const html = await renderViaHTTP(appPort, '/some-amp?amp=1')
expect(html).toMatch(/Hi Im an AMP page/)
expect(html).toMatch(/ampproject\.org/)
})
it('should have correct amphtml rel link', async () => {
const html = await renderViaHTTP(appPort, '/some-amp')
expect(html).toMatch(/Hi Im an AMP page/)
expect(html).toMatch(/rel="amphtml" href="\/some-amp\?amp=1"/)
})
it('should have correct canonical link', async () => {
const html = await renderViaHTTP(appPort, '/some-amp?amp=1')
expect(html).toMatch(/rel="canonical" href="\/some-amp"/)
})
it('should render correctly when importing isomorphic-unfetch', async () => {
const url = `http://localhost:${appPort}/fetch`
const res = await fetch(url)
expect(res.status).toBe(200)
const text = await res.text()
expect(text.includes('failed')).toBe(false)
})
it('should render correctly when importing isomorphic-unfetch on the client side', async () => {
const browser = await webdriver(appPort, '/')
try {
const text = await browser
.elementByCss('a')
.click()
.waitForElementByCss('.fetch-page')
.elementByCss('#text')
.text()
expect(text).toMatch(/fetch page/)
} finally {
await browser.close()
}
})
it('should not output _app.js and _document.js to serverless build', () => {
expect(existsSync(join(serverlessDir, '_app.js'))).toBeFalsy()
expect(existsSync(join(serverlessDir, '_document.js'))).toBeFalsy()
})
it('should replace static pages with HTML files', async () => {
const staticFiles = ['abc', 'dynamic', 'dynamic-two', 'some-amp']
for (const file of staticFiles) {
expect(existsSync(join(serverlessDir, file + '.html'))).toBe(true)
expect(existsSync(join(serverlessDir, file + '.js'))).toBe(false)
}
})
it('should not replace non-static pages with HTML files', async () => {
const nonStaticFiles = ['fetch', '_error']
for (const file of nonStaticFiles) {
expect(existsSync(join(serverlessDir, file + '.js'))).toBe(true)
expect(existsSync(join(serverlessDir, file + '.html'))).toBe(false)
}
})
it('should reply on API request successfully', async () => {
const content = await renderViaHTTP(appPort, '/api/hello')
expect(content).toMatch(/hello world/)
})
it('should reply on dynamic API request successfully', async () => {
const result = await renderViaHTTP(appPort, '/api/posts/post-1')
const { post } = JSON.parse(result)
expect(post).toBe('post-1')
})
it('should 404 on API request with trailing slash', async () => {
const res = await fetchViaHTTP(appPort, '/api/hello/')
expect(res.status).toBe(404)
})
describe('With basic usage', () => {
it('should allow etag header support', async () => {
const url = `http://localhost:${appPort}/`
const etag = (await fetch(url)).headers.get('ETag')
const headers = { 'If-None-Match': etag }
const res2 = await fetch(url, { headers })
expect(res2.status).toBe(304)
})
it('should set Content-Length header', async () => {
const url = `http://localhost:${appPort}`
const res = await fetch(url)
expect(res.headers.get('Content-Length')).toBeDefined()
})
})
})
This diff is collapsed.
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