Commit fcf1167c authored by Connor Davis's avatar Connor Davis Committed by Tim Neutkens

Upgrade standard and fix files (#6358)

Upgrades `standard` to major version 12
parent bf69357f
...@@ -69,7 +69,7 @@ ...@@ -69,7 +69,7 @@
"chromedriver": "2.42.0", "chromedriver": "2.42.0",
"clone": "2.1.1", "clone": "2.1.1",
"coveralls": "3.0.2", "coveralls": "3.0.2",
"eslint": "5.13.0", "eslint": "5.4.0",
"eslint-plugin-typescript": "0.14.0", "eslint-plugin-typescript": "0.14.0",
"express": "4.16.3", "express": "4.16.3",
"fkill": "5.1.0", "fkill": "5.1.0",
...@@ -90,7 +90,7 @@ ...@@ -90,7 +90,7 @@
"release": "5.0.3", "release": "5.0.3",
"request-promise-core": "1.1.1", "request-promise-core": "1.1.1",
"rimraf": "2.6.2", "rimraf": "2.6.2",
"standard": "11.0.1", "standard": "12.0.1",
"taskr": "1.1.0", "taskr": "1.1.0",
"tslint": "5.12.0", "tslint": "5.12.0",
"typescript": "3.1.1", "typescript": "3.1.1",
......
...@@ -25,7 +25,7 @@ export default function dynamic (dynamicOptions, options) { ...@@ -25,7 +25,7 @@ export default function dynamic (dynamicOptions, options) {
let loadableFn = Loadable let loadableFn = Loadable
let loadableOptions = { let loadableOptions = {
// A loading component is not required, so we default it // A loading component is not required, so we default it
loading: ({error, isLoading}) => { loading: ({ error, isLoading }) => {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
if (isLoading) { if (isLoading) {
return <DefaultLoading /> return <DefaultLoading />
...@@ -50,11 +50,11 @@ export default function dynamic (dynamicOptions, options) { ...@@ -50,11 +50,11 @@ export default function dynamic (dynamicOptions, options) {
loadableOptions.loader = dynamicOptions loadableOptions.loader = dynamicOptions
// Support for having first argument being options, eg: dynamic({loader: import('../hello-world')}) // Support for having first argument being options, eg: dynamic({loader: import('../hello-world')})
} else if (typeof dynamicOptions === 'object') { } else if (typeof dynamicOptions === 'object') {
loadableOptions = {...loadableOptions, ...dynamicOptions} loadableOptions = { ...loadableOptions, ...dynamicOptions }
} }
// Support for passing options, eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>}) // Support for passing options, eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>})
loadableOptions = {...loadableOptions, ...options} loadableOptions = { ...loadableOptions, ...options }
// Support for `render` when using a mapping, eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) // Support for `render` when using a mapping, eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } })
if (dynamicOptions.render) { if (dynamicOptions.render) {
...@@ -78,7 +78,7 @@ export default function dynamic (dynamicOptions, options) { ...@@ -78,7 +78,7 @@ export default function dynamic (dynamicOptions, options) {
// coming from build/babel/plugins/react-loadable-plugin.js // coming from build/babel/plugins/react-loadable-plugin.js
if (loadableOptions.loadableGenerated) { if (loadableOptions.loadableGenerated) {
loadableOptions = {...loadableOptions, ...loadableOptions.loadableGenerated} loadableOptions = { ...loadableOptions, ...loadableOptions.loadableGenerated }
delete loadableOptions.loadableGenerated delete loadableOptions.loadableGenerated
} }
......
...@@ -412,9 +412,9 @@ export default class Router { ...@@ -412,9 +412,9 @@ export default class Router {
let cancelled = false let cancelled = false
const cancel = () => { cancelled = true } const cancel = () => { cancelled = true }
this.componentLoadCancel = cancel this.componentLoadCancel = cancel
const {Component: App} = this.components['/_app'] const { Component: App } = this.components['/_app']
const props = await loadGetInitialProps(App, {Component, router: this, ctx}) const props = await loadGetInitialProps(App, { Component, router: this, ctx })
if (cancel === this.componentLoadCancel) { if (cancel === this.componentLoadCancel) {
this.componentLoadCancel = null this.componentLoadCancel = null
...@@ -442,8 +442,8 @@ export default class Router { ...@@ -442,8 +442,8 @@ export default class Router {
} }
notify (data) { notify (data) {
const {Component: App} = this.components['/_app'] const { Component: App } = this.components['/_app']
this.subscriptions.forEach((fn) => fn({...data, App})) this.subscriptions.forEach((fn) => fn({ ...data, App }))
} }
subscribe (fn) { subscribe (fn) {
......
import findUp from 'find-up' import findUp from 'find-up'
import {CONFIG_FILE} from 'next-server/constants' import { CONFIG_FILE } from 'next-server/constants'
const targets = ['server', 'serverless'] const targets = ['server', 'serverless']
...@@ -27,7 +27,7 @@ const defaultConfig = { ...@@ -27,7 +27,7 @@ const defaultConfig = {
function normalizeConfig (phase, config) { function normalizeConfig (phase, config) {
if (typeof config === 'function') { if (typeof config === 'function') {
return config(phase, {defaultConfig}) return config(phase, { defaultConfig })
} }
return config return config
...@@ -35,7 +35,7 @@ function normalizeConfig (phase, config) { ...@@ -35,7 +35,7 @@ function normalizeConfig (phase, config) {
export default function loadConfig (phase, dir, customConfig) { export default function loadConfig (phase, dir, customConfig) {
if (customConfig) { if (customConfig) {
return {...defaultConfig, configOrigin: 'server', ...customConfig} return { ...defaultConfig, configOrigin: 'server', ...customConfig }
} }
const path = findUp.sync(CONFIG_FILE, { const path = findUp.sync(CONFIG_FILE, {
cwd: dir cwd: dir
...@@ -60,7 +60,7 @@ export default function loadConfig (phase, dir, customConfig) { ...@@ -60,7 +60,7 @@ export default function loadConfig (phase, dir, customConfig) {
...userConfig.onDemandEntries ...userConfig.onDemandEntries
} }
} }
return {...defaultConfig, configOrigin: CONFIG_FILE, ...userConfig} return { ...defaultConfig, configOrigin: CONFIG_FILE, ...userConfig }
} }
return defaultConfig return defaultConfig
......
const notifier = require('node-notifier') const notifier = require('node-notifier')
export async function lib (task, opts) { export async function lib (task, opts) {
await task.source(opts.src || 'lib/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).target('dist/lib') await task.source(opts.src || 'lib/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/lib')
notify('Compiled lib files') notify('Compiled lib files')
} }
export async function server (task, opts) { export async function server (task, opts) {
await task.source(opts.src || 'server/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).target('dist/server') await task.source(opts.src || 'server/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/server')
notify('Compiled server files') notify('Compiled server files')
} }
......
...@@ -10,11 +10,11 @@ import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin' ...@@ -10,11 +10,11 @@ import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin' import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin' import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import {SERVER_DIRECTORY, REACT_LOADABLE_MANIFEST, CLIENT_STATIC_FILES_RUNTIME_WEBPACK, CLIENT_STATIC_FILES_RUNTIME_MAIN} from 'next-server/constants' import { SERVER_DIRECTORY, REACT_LOADABLE_MANIFEST, CLIENT_STATIC_FILES_RUNTIME_WEBPACK, CLIENT_STATIC_FILES_RUNTIME_MAIN } from 'next-server/constants'
import {NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT_NODE_MODULES, NEXT_PROJECT_ROOT_DIST_CLIENT, PAGES_DIR_ALIAS, DOT_NEXT_ALIAS} from '../lib/constants' import { NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT_NODE_MODULES, NEXT_PROJECT_ROOT_DIST_CLIENT, PAGES_DIR_ALIAS, DOT_NEXT_ALIAS } from '../lib/constants'
import AutoDllPlugin from 'autodll-webpack-plugin' import AutoDllPlugin from 'autodll-webpack-plugin'
import TerserPlugin from './webpack/plugins/terser-webpack-plugin/src/cjs.js' import TerserPlugin from './webpack/plugins/terser-webpack-plugin/src/cjs.js'
import {ServerlessPlugin} from './webpack/plugins/serverless-plugin' import { ServerlessPlugin } from './webpack/plugins/serverless-plugin'
// The externals config makes sure that // The externals config makes sure that
// on the server side when modules are // on the server side when modules are
...@@ -83,7 +83,7 @@ function optimizationConfig ({ dev, isServer, totalPages, target }) { ...@@ -83,7 +83,7 @@ function optimizationConfig ({ dev, isServer, totalPages, target }) {
return { return {
splitChunks: false, splitChunks: false,
minimizer: [ minimizer: [
new TerserPlugin({...terserPluginConfig, new TerserPlugin({ ...terserPluginConfig,
terserOptions: { terserOptions: {
compress: false, compress: false,
mangle: false, mangle: false,
...@@ -121,7 +121,7 @@ function optimizationConfig ({ dev, isServer, totalPages, target }) { ...@@ -121,7 +121,7 @@ function optimizationConfig ({ dev, isServer, totalPages, target }) {
// Terser is a better uglifier // Terser is a better uglifier
config.minimizer = [ config.minimizer = [
new TerserPlugin({...terserPluginConfig, new TerserPlugin({ ...terserPluginConfig,
terserOptions: { terserOptions: {
safari10: true safari10: true
} }
...@@ -146,11 +146,11 @@ function optimizationConfig ({ dev, isServer, totalPages, target }) { ...@@ -146,11 +146,11 @@ function optimizationConfig ({ dev, isServer, totalPages, target }) {
return config return config
} }
export default async function getBaseWebpackConfig (dir, {dev = false, isServer = false, buildId, config, target = 'server', entrypoints}) { export default async function getBaseWebpackConfig (dir, { dev = false, isServer = false, buildId, config, target = 'server', entrypoints }) {
const defaultLoaders = { const defaultLoaders = {
babel: { babel: {
loader: 'next-babel-loader', loader: 'next-babel-loader',
options: {dev, isServer, cwd: dir} options: { dev, isServer, cwd: dir }
}, },
// Backwards compat // Backwards compat
hotSelfAccept: { hotSelfAccept: {
...@@ -198,7 +198,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer ...@@ -198,7 +198,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
name: isServer ? 'server' : 'client', name: isServer ? 'server' : 'client',
target: isServer ? 'node' : 'web', target: isServer ? 'node' : 'web',
externals: externalsConfig(isServer, target), externals: externalsConfig(isServer, target),
optimization: optimizationConfig({dir, dev, isServer, totalPages, target}), optimization: optimizationConfig({ dir, dev, isServer, totalPages, target }),
recordsPath: path.join(outputPath, 'records.json'), recordsPath: path.join(outputPath, 'records.json'),
context: dir, context: dir,
// Kept as function to be backwards compatible // Kept as function to be backwards compatible
...@@ -210,7 +210,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer ...@@ -210,7 +210,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
}, },
output: { output: {
path: outputPath, path: outputPath,
filename: ({chunk}) => { filename: ({ chunk }) => {
// Use `[name]-[contenthash].js` in production // Use `[name]-[contenthash].js` in production
if (!dev && (chunk.name === CLIENT_STATIC_FILES_RUNTIME_MAIN || chunk.name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK)) { if (!dev && (chunk.name === CLIENT_STATIC_FILES_RUNTIME_MAIN || chunk.name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK)) {
return chunk.name.replace(/\.js$/, '-[contenthash].js') return chunk.name.replace(/\.js$/, '-[contenthash].js')
...@@ -306,7 +306,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer ...@@ -306,7 +306,7 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
target !== 'serverless' && isServer && new PagesManifestPlugin(), target !== 'serverless' && isServer && new PagesManifestPlugin(),
!isServer && new BuildManifestPlugin(), !isServer && new BuildManifestPlugin(),
isServer && new NextJsSsrImportPlugin(), isServer && new NextJsSsrImportPlugin(),
target !== 'serverless' && isServer && new NextJsSSRModuleCachePlugin({outputPath}), target !== 'serverless' && isServer && new NextJsSSRModuleCachePlugin({ outputPath }),
!dev && new webpack.IgnorePlugin({ !dev && new webpack.IgnorePlugin({
checkResource: (resource) => { checkResource: (resource) => {
return /react-is/.test(resource) return /react-is/.test(resource)
...@@ -319,13 +319,13 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer ...@@ -319,13 +319,13 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
} }
if (typeof config.webpack === 'function') { if (typeof config.webpack === 'function') {
webpackConfig = config.webpack(webpackConfig, {dir, dev, isServer, buildId, config, defaultLoaders, totalPages}) webpackConfig = config.webpack(webpackConfig, { dir, dev, isServer, buildId, config, defaultLoaders, totalPages })
} }
// Backwards compat for `main.js` entry key // Backwards compat for `main.js` entry key
const originalEntry = webpackConfig.entry const originalEntry = webpackConfig.entry
webpackConfig.entry = async () => { webpackConfig.entry = async () => {
const entry = {...await originalEntry()} const entry = { ...await originalEntry() }
// Server compilation doesn't have main.js // Server compilation doesn't have main.js
if (typeof entry['main.js'] !== 'undefined') { if (typeof entry['main.js'] !== 'undefined') {
......
...@@ -22,7 +22,7 @@ module.exports = function (content, sourceMap) { ...@@ -22,7 +22,7 @@ module.exports = function (content, sourceMap) {
const regExp = query.regExp const regExp = query.regExp
const opts = { context, content, regExp } const opts = { context, content, regExp }
const interpolateName = query.interpolateName || ((name) => name) const interpolateName = query.interpolateName || ((name) => name)
const interpolatedName = interpolateName(loaderUtils.interpolateName(this, name, opts), {name, opts}) const interpolatedName = interpolateName(loaderUtils.interpolateName(this, name, opts), { name, opts })
const emit = (code, map) => { const emit = (code, map) => {
this.emitFile(interpolatedName, code, map) this.emitFile(interpolatedName, code, map)
callback(null, code, map) callback(null, code, map)
......
import babelLoader from 'babel-loader' import babelLoader from 'babel-loader'
module.exports = babelLoader.custom(babel => { module.exports = babelLoader.custom(babel => {
const presetItem = babel.createConfigItem(require('../../babel/preset'), {type: 'preset'}) const presetItem = babel.createConfigItem(require('../../babel/preset'), { type: 'preset' })
const applyCommonJs = babel.createConfigItem(require('../../babel/plugins/commonjs'), {type: 'plugin'}) const applyCommonJs = babel.createConfigItem(require('../../babel/plugins/commonjs'), { type: 'plugin' })
const commonJsItem = babel.createConfigItem(require('@babel/plugin-transform-modules-commonjs'), {type: 'plugin'}) const commonJsItem = babel.createConfigItem(require('@babel/plugin-transform-modules-commonjs'), { type: 'plugin' })
const configs = new Set() const configs = new Set()
...@@ -22,7 +22,7 @@ module.exports = babelLoader.custom(babel => { ...@@ -22,7 +22,7 @@ module.exports = babelLoader.custom(babel => {
return { loader, custom } return { loader, custom }
}, },
config (cfg, {source, customOptions: {isServer, dev}}) { config (cfg, { source, customOptions: { isServer, dev } }) {
const options = Object.assign({}, cfg.options) const options = Object.assign({}, cfg.options)
if (cfg.hasFilesystemConfig()) { if (cfg.hasFilesystemConfig()) {
for (const file of [cfg.babelrc, cfg.config]) { for (const file of [cfg.babelrc, cfg.config]) {
......
import { RawSource } from 'webpack-sources' import { RawSource } from 'webpack-sources'
import {BUILD_MANIFEST, ROUTE_NAME_REGEX, IS_BUNDLED_PAGE_REGEX, CLIENT_STATIC_FILES_RUNTIME_MAIN} from 'next-server/constants' import { BUILD_MANIFEST, ROUTE_NAME_REGEX, IS_BUNDLED_PAGE_REGEX, CLIENT_STATIC_FILES_RUNTIME_MAIN } from 'next-server/constants'
// This plugin creates a build-manifest.json for all assets that are being output // This plugin creates a build-manifest.json for all assets that are being output
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production // It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin { export default class BuildManifestPlugin {
apply (compiler) { apply (compiler) {
compiler.hooks.emit.tapAsync('NextJsBuildManifest', (compilation, callback) => { compiler.hooks.emit.tapAsync('NextJsBuildManifest', (compilation, callback) => {
const {chunks} = compilation const { chunks } = compilation
const assetMap = {devFiles: [], pages: {}} const assetMap = { devFiles: [], pages: {} }
const mainJsChunk = chunks.find((c) => c.name === CLIENT_STATIC_FILES_RUNTIME_MAIN) const mainJsChunk = chunks.find((c) => c.name === CLIENT_STATIC_FILES_RUNTIME_MAIN)
const mainJsFiles = mainJsChunk && mainJsChunk.files.length > 0 ? mainJsChunk.files.filter((file) => /\.js$/.test(file)) : [] const mainJsFiles = mainJsChunk && mainJsChunk.files.length > 0 ? mainJsChunk.files.filter((file) => /\.js$/.test(file)) : []
......
import webpack from 'webpack' import webpack from 'webpack'
import { RawSource } from 'webpack-sources' import { RawSource } from 'webpack-sources'
import { join, relative, dirname } from 'path' import { join, relative, dirname } from 'path'
import {IS_BUNDLED_PAGE_REGEX} from 'next-server/constants' import { IS_BUNDLED_PAGE_REGEX } from 'next-server/constants'
const SSR_MODULE_CACHE_FILENAME = 'ssr-module-cache.js' const SSR_MODULE_CACHE_FILENAME = 'ssr-module-cache.js'
...@@ -20,7 +20,7 @@ export default class NextJsSsrImportPlugin { ...@@ -20,7 +20,7 @@ export default class NextJsSsrImportPlugin {
this.options = options this.options = options
} }
apply (compiler) { apply (compiler) {
const {outputPath} = this.options const { outputPath } = this.options
compiler.hooks.emit.tapAsync('NextJsSSRModuleCache', (compilation, callback) => { compiler.hooks.emit.tapAsync('NextJsSSRModuleCache', (compilation, callback) => {
compilation.assets[SSR_MODULE_CACHE_FILENAME] = new RawSource(` compilation.assets[SSR_MODULE_CACHE_FILENAME] = new RawSource(`
/* This cache is used by webpack for instantiated modules */ /* This cache is used by webpack for instantiated modules */
......
import { RawSource } from 'webpack-sources' import { RawSource } from 'webpack-sources'
import {PAGES_MANIFEST, ROUTE_NAME_REGEX} from 'next-server/constants' import { PAGES_MANIFEST, ROUTE_NAME_REGEX } from 'next-server/constants'
// This plugin creates a pages-manifest.json from page entrypoints. // This plugin creates a pages-manifest.json from page entrypoints.
// This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR // This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR
...@@ -7,7 +7,7 @@ import {PAGES_MANIFEST, ROUTE_NAME_REGEX} from 'next-server/constants' ...@@ -7,7 +7,7 @@ import {PAGES_MANIFEST, ROUTE_NAME_REGEX} from 'next-server/constants'
export default class PagesManifestPlugin { export default class PagesManifestPlugin {
apply (compiler) { apply (compiler) {
compiler.hooks.emit.tap('NextJsPagesManifest', (compilation) => { compiler.hooks.emit.tap('NextJsPagesManifest', (compilation) => {
const {entries} = compilation const { entries } = compilation
const pages = {} const pages = {}
for (const entry of entries) { for (const entry of entries) {
...@@ -22,7 +22,7 @@ export default class PagesManifestPlugin { ...@@ -22,7 +22,7 @@ export default class PagesManifestPlugin {
continue continue
} }
const {name} = entry const { name } = entry
// Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency. // Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency.
pages[`/${pagePath.replace(/\\/g, '/')}`] = name.replace(/\\/g, '/') pages[`/${pagePath.replace(/\\/g, '/')}`] = name.replace(/\\/g, '/')
} }
......
...@@ -26,11 +26,11 @@ SOFTWARE. ...@@ -26,11 +26,11 @@ SOFTWARE.
// It's been edited to rely on webpack-hot-middleware and to be more compatible with SSR / Next.js // It's been edited to rely on webpack-hot-middleware and to be more compatible with SSR / Next.js
'use strict' 'use strict'
import {getEventSourceWrapper} from './eventsource' import { getEventSourceWrapper } from './eventsource'
import formatWebpackMessages from './format-webpack-messages' import formatWebpackMessages from './format-webpack-messages'
import * as ErrorOverlay from 'react-error-overlay' import * as ErrorOverlay from 'react-error-overlay'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
import {rewriteStacktrace} from '../source-map-support' import { rewriteStacktrace } from '../source-map-support'
import fetch from 'unfetch' import fetch from 'unfetch'
// This alternative WebpackDevServer combines the functionality of: // This alternative WebpackDevServer combines the functionality of:
......
...@@ -2,12 +2,12 @@ import React from 'react' ...@@ -2,12 +2,12 @@ import React from 'react'
class ErrorBoundary extends React.Component { class ErrorBoundary extends React.Component {
componentDidCatch (error, info) { componentDidCatch (error, info) {
const {onError} = this.props const { onError } = this.props
// onError is required // onError is required
onError(error, info) onError(error, info)
} }
render () { render () {
const {children} = this.props const { children } = this.props
return React.Children.only(children) return React.Children.only(children)
} }
} }
......
...@@ -3,7 +3,7 @@ import ReactDOM from 'react-dom' ...@@ -3,7 +3,7 @@ import ReactDOM from 'react-dom'
import HeadManager from './head-manager' import HeadManager from './head-manager'
import { createRouter } from 'next/router' import { createRouter } from 'next/router'
import mitt from 'next-server/dist/lib/mitt' import mitt from 'next-server/dist/lib/mitt'
import {loadGetInitialProps, getURL} from 'next-server/dist/lib/utils' import { loadGetInitialProps, getURL } from 'next-server/dist/lib/utils'
import PageLoader from './page-loader' import PageLoader from './page-loader'
import * as envConfig from 'next-server/config' import * as envConfig from 'next-server/config'
import ErrorBoundary from './error-boundary' import ErrorBoundary from './error-boundary'
...@@ -119,7 +119,7 @@ export async function render (props) { ...@@ -119,7 +119,7 @@ export async function render (props) {
try { try {
await doRender(props) await doRender(props)
} catch (err) { } catch (err) {
await renderError({...props, err}) await renderError({ ...props, err })
} }
} }
...@@ -127,7 +127,7 @@ export async function render (props) { ...@@ -127,7 +127,7 @@ export async function render (props) {
// 404 and 500 errors are special kind of errors // 404 and 500 errors are special kind of errors
// and they are still handle via the main render method. // and they are still handle via the main render method.
export async function renderError (props) { export async function renderError (props) {
const {App, err} = props const { App, err } = props
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
throw webpackHMR.prepareError(err) throw webpackHMR.prepareError(err)
...@@ -143,9 +143,9 @@ export async function renderError (props) { ...@@ -143,9 +143,9 @@ export async function renderError (props) {
// Otherwise, we need to call `getInitialProps` on `App` before mounting. // Otherwise, we need to call `getInitialProps` on `App` before mounting.
const initProps = props.props const initProps = props.props
? props.props ? props.props
: await loadGetInitialProps(App, {Component: ErrorComponent, router, ctx: {err, pathname: page, query, asPath}}) : await loadGetInitialProps(App, { Component: ErrorComponent, router, ctx: { err, pathname: page, query, asPath } })
await doRender({...props, err, Component: ErrorComponent, props: initProps}) await doRender({ ...props, err, Component: ErrorComponent, props: initProps })
} }
let isInitialRender = true let isInitialRender = true
...@@ -166,7 +166,7 @@ async function doRender ({ App, Component, props, err, emitter: emitterProp = em ...@@ -166,7 +166,7 @@ async function doRender ({ App, Component, props, err, emitter: emitterProp = em
Component !== ErrorComponent && Component !== ErrorComponent &&
lastAppProps.Component === ErrorComponent) { lastAppProps.Component === ErrorComponent) {
const { pathname, query, asPath } = router const { pathname, query, asPath } = router
props = await loadGetInitialProps(App, {Component, router, ctx: {err, pathname, query, asPath}}) props = await loadGetInitialProps(App, { Component, router, ctx: { err, pathname, query, asPath } })
} }
Component = Component || lastAppProps.Component Component = Component || lastAppProps.Component
...@@ -189,7 +189,7 @@ async function doRender ({ App, Component, props, err, emitter: emitterProp = em ...@@ -189,7 +189,7 @@ async function doRender ({ App, Component, props, err, emitter: emitterProp = em
// In production we catch runtime errors using componentDidCatch which will trigger renderError. // In production we catch runtime errors using componentDidCatch which will trigger renderError.
const onError = async (error) => { const onError = async (error) => {
try { try {
await renderError({App, err: error}) await renderError({ App, err: error })
} catch (err) { } catch (err) {
console.error('Error while rendering error page: ', err) console.error('Error while rendering error page: ', err)
} }
......
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
import { resolve, format, parse } from 'url' import { resolve, format, parse } from 'url'
import React, { Component, Children } from 'react' import React, { Component, Children } from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import Router, {Router as _Router} from 'next/router' import Router, { Router as _Router } from 'next/router'
import {execOnce, getLocationOrigin} from 'next-server/dist/lib/utils' import { execOnce, getLocationOrigin } from 'next-server/dist/lib/utils'
function isLocal (href) { function isLocal (href) {
const url = parse(href, false, true) const url = parse(href, false, true)
...@@ -102,7 +102,7 @@ class Link extends Component { ...@@ -102,7 +102,7 @@ class Link extends Component {
// Prefetch the JSON page if asked (only in the client) // Prefetch the JSON page if asked (only in the client)
const { pathname } = window.location const { pathname } = window.location
const {href: parsedHref} = this.formatUrls(this.props.href, this.props.as) const { href: parsedHref } = this.formatUrls(this.props.href, this.props.as)
const href = resolve(pathname, parsedHref) const href = resolve(pathname, parsedHref)
Router.prefetch(href) Router.prefetch(href)
} }
......
...@@ -15,12 +15,12 @@ const { ...@@ -15,12 +15,12 @@ const {
} = window } = window
const prefix = assetPrefix || '' const prefix = assetPrefix || ''
const webpackHMR = initWebpackHMR({assetPrefix: prefix}) const webpackHMR = initWebpackHMR({ assetPrefix: prefix })
window.next = next window.next = next
initNext({ webpackHMR }) initNext({ webpackHMR })
.then((emitter) => { .then((emitter) => {
initOnDemandEntries({assetPrefix: prefix}) initOnDemandEntries({ assetPrefix: prefix })
let lastScroll let lastScroll
......
...@@ -99,7 +99,7 @@ export function makePublicRouterInstance (router) { ...@@ -99,7 +99,7 @@ export function makePublicRouterInstance (router) {
for (const property of urlPropertyFields) { for (const property of urlPropertyFields) {
if (typeof router[property] === 'object') { if (typeof router[property] === 'object') {
instance[property] = {...router[property]} // makes sure query is not stateful instance[property] = { ...router[property] } // makes sure query is not stateful
continue continue
} }
......
import 'event-source-polyfill' import 'event-source-polyfill'
import connect from './dev-error-overlay/hot-dev-client' import connect from './dev-error-overlay/hot-dev-client'
export default ({assetPrefix}) => { export default ({ assetPrefix }) => {
const options = { const options = {
path: `${assetPrefix}/_next/webpack-hmr` path: `${assetPrefix}/_next/webpack-hmr`
} }
......
...@@ -91,7 +91,7 @@ export default async function (dir, options, configuration) { ...@@ -91,7 +91,7 @@ export default async function (dir, options, configuration) {
hotReloader: null hotReloader: null
} }
const {serverRuntimeConfig, publicRuntimeConfig} = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
if (publicRuntimeConfig) { if (publicRuntimeConfig) {
renderOpts.runtimeConfig = publicRuntimeConfig renderOpts.runtimeConfig = publicRuntimeConfig
...@@ -103,7 +103,7 @@ export default async function (dir, options, configuration) { ...@@ -103,7 +103,7 @@ export default async function (dir, options, configuration) {
} }
log(` launching ${threads} threads with concurrency of ${concurrency} per thread`) log(` launching ${threads} threads with concurrency of ${concurrency} per thread`)
const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {dev: false, dir, outDir, distDir, buildId}) const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, { dev: false, dir, outDir, distDir, buildId })
const exportPaths = Object.keys(exportPathMap) const exportPaths = Object.keys(exportPathMap)
const progress = !options.silent && createProgress(exportPaths.length) const progress = !options.silent && createProgress(exportPaths.length)
......
...@@ -7,7 +7,7 @@ const mkdirp = require('mkdirp-then') ...@@ -7,7 +7,7 @@ const mkdirp = require('mkdirp-then')
const { renderToHTML } = require('next-server/dist/server/render') const { renderToHTML } = require('next-server/dist/server/render')
const { writeFile } = require('fs') const { writeFile } = require('fs')
const Sema = require('async-sema') const Sema = require('async-sema')
const {loadComponents} = require('next-server/dist/server/load-components') const { loadComponents } = require('next-server/dist/server/load-components')
const envConfig = require('next-server/config') const envConfig = require('next-server/config')
process.on( process.on(
...@@ -47,7 +47,7 @@ process.on( ...@@ -47,7 +47,7 @@ process.on(
await mkdirp(baseDir) await mkdirp(baseDir)
const components = await loadComponents(distDir, buildId, page) const components = await loadComponents(distDir, buildId, page)
const html = await renderToHTML(req, res, page, query, {...components, ...renderOpts}) const html = await renderToHTML(req, res, page, query, { ...components, ...renderOpts })
await new Promise((resolve, reject) => await new Promise((resolve, reject) =>
writeFile( writeFile(
htmlFilepath, htmlFilepath,
......
import {join} from 'path' import { join } from 'path'
export const NEXT_PROJECT_ROOT = join(__dirname, '..', '..') export const NEXT_PROJECT_ROOT = join(__dirname, '..', '..')
export const NEXT_PROJECT_ROOT_DIST = join(NEXT_PROJECT_ROOT, 'dist') export const NEXT_PROJECT_ROOT_DIST = join(NEXT_PROJECT_ROOT, 'dist')
export const NEXT_PROJECT_ROOT_NODE_MODULES = join(NEXT_PROJECT_ROOT, 'node_modules') export const NEXT_PROJECT_ROOT_NODE_MODULES = join(NEXT_PROJECT_ROOT, 'node_modules')
......
...@@ -10,7 +10,7 @@ export default class App extends Component { ...@@ -10,7 +10,7 @@ export default class App extends Component {
static async getInitialProps ({ Component, router, ctx }) { static async getInitialProps ({ Component, router, ctx }) {
const pageProps = await loadGetInitialProps(Component, ctx) const pageProps = await loadGetInitialProps(Component, ctx)
return {pageProps} return { pageProps }
} }
getChildContext () { getChildContext () {
...@@ -26,7 +26,7 @@ export default class App extends Component { ...@@ -26,7 +26,7 @@ export default class App extends Component {
} }
render () { render () {
const {router, Component, pageProps} = this.props const { router, Component, pageProps } = this.props
const url = createUrl(router) const url = createUrl(router)
return ( return (
<Container> <Container>
...@@ -71,7 +71,7 @@ const warnUrl = execOnce(() => { ...@@ -71,7 +71,7 @@ const warnUrl = execOnce(() => {
export function createUrl (router) { export function createUrl (router) {
// This is to make sure we don't references the router object at call time // This is to make sure we don't references the router object at call time
const {pathname, asPath, query} = router const { pathname, asPath, query } = router
return { return {
get query () { get query () {
warnUrl() warnUrl()
......
...@@ -4,7 +4,7 @@ import Head from 'next-server/head' ...@@ -4,7 +4,7 @@ import Head from 'next-server/head'
// This component is rendered through dev-error-overlay on the client side. // This component is rendered through dev-error-overlay on the client side.
// On the server side it's rendered directly // On the server side it's rendered directly
export default function ErrorDebug ({error, info}) { export default function ErrorDebug ({ error, info }) {
const { name, message } = error const { name, message } = error
return ( return (
<div style={styles.errorDebug}> <div style={styles.errorDebug}>
......
...@@ -3,15 +3,15 @@ import WebpackDevMiddleware from 'webpack-dev-middleware' ...@@ -3,15 +3,15 @@ import WebpackDevMiddleware from 'webpack-dev-middleware'
import WebpackHotMiddleware from 'webpack-hot-middleware' import WebpackHotMiddleware from 'webpack-hot-middleware'
import errorOverlayMiddleware from './lib/error-overlay-middleware' import errorOverlayMiddleware from './lib/error-overlay-middleware'
import del from 'del' import del from 'del'
import onDemandEntryHandler, {normalizePage} from './on-demand-entry-handler' import onDemandEntryHandler, { normalizePage } from './on-demand-entry-handler'
import webpack from 'webpack' import webpack from 'webpack'
import getBaseWebpackConfig from '../build/webpack-config' import getBaseWebpackConfig from '../build/webpack-config'
import {IS_BUNDLED_PAGE_REGEX, ROUTE_NAME_REGEX, BLOCKED_PAGES} from 'next-server/constants' import { IS_BUNDLED_PAGE_REGEX, ROUTE_NAME_REGEX, BLOCKED_PAGES } from 'next-server/constants'
import {route} from 'next-server/dist/server/router' import { route } from 'next-server/dist/server/router'
import globModule from 'glob' import globModule from 'glob'
import {promisify} from 'util' import { promisify } from 'util'
import {createPagesMapping, createEntrypoints} from '../build/entries' import { createPagesMapping, createEntrypoints } from '../build/entries'
import {watchCompiler} from '../build/output' import { watchCompiler } from '../build/output'
const glob = promisify(globModule) const glob = promisify(globModule)
...@@ -62,11 +62,11 @@ function findEntryModule (issuer) { ...@@ -62,11 +62,11 @@ function findEntryModule (issuer) {
return issuer return issuer
} }
function erroredPages (compilation, options = {enhanceName: (name) => name}) { function erroredPages (compilation, options = { enhanceName: (name) => name }) {
const failedPages = {} const failedPages = {}
for (const error of compilation.errors) { for (const error of compilation.errors) {
const entryModule = findEntryModule(error.origin) const entryModule = findEntryModule(error.origin)
const {name} = entryModule const { name } = entryModule
if (!name) { if (!name) {
continue continue
} }
...@@ -117,7 +117,7 @@ export default class HotReloader { ...@@ -117,7 +117,7 @@ export default class HotReloader {
// by adding the page to on-demand-entries, waiting till it's done // by adding the page to on-demand-entries, waiting till it's done
// and then the bundle will be served like usual by the actual route in server/index.js // and then the bundle will be served like usual by the actual route in server/index.js
const handlePageBundleRequest = async (res, parsedUrl) => { const handlePageBundleRequest = async (res, parsedUrl) => {
const {pathname} = parsedUrl const { pathname } = parsedUrl
const params = matchNextPageBundleRequest(pathname) const params = matchNextPageBundleRequest(pathname)
if (!params) { if (!params) {
return {} return {}
...@@ -133,20 +133,20 @@ export default class HotReloader { ...@@ -133,20 +133,20 @@ export default class HotReloader {
await this.ensurePage(page) await this.ensurePage(page)
} catch (error) { } catch (error) {
await renderScriptError(res, error) await renderScriptError(res, error)
return {finished: true} return { finished: true }
} }
const errors = await this.getCompilationErrors(page) const errors = await this.getCompilationErrors(page)
if (errors.length > 0) { if (errors.length > 0) {
await renderScriptError(res, errors[0]) await renderScriptError(res, errors[0])
return {finished: true} return { finished: true }
} }
} }
return {} return {}
} }
const {finished} = await handlePageBundleRequest(res, parsedUrl) const { finished } = await handlePageBundleRequest(res, parsedUrl)
for (const fn of this.middlewares) { for (const fn of this.middlewares) {
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
...@@ -157,7 +157,7 @@ export default class HotReloader { ...@@ -157,7 +157,7 @@ export default class HotReloader {
}) })
} }
return {finished} return { finished }
} }
async clean () { async clean () {
...@@ -165,7 +165,7 @@ export default class HotReloader { ...@@ -165,7 +165,7 @@ export default class HotReloader {
} }
async getWebpackConfig () { async getWebpackConfig () {
const pagePaths = await glob(`+(_app|_document).+(${this.config.pageExtensions.join('|')})`, {cwd: join(this.dir, 'pages')}) const pagePaths = await glob(`+(_app|_document).+(${this.config.pageExtensions.join('|')})`, { cwd: join(this.dir, 'pages') })
const pages = createPagesMapping(pagePaths, this.config.pageExtensions) const pages = createPagesMapping(pagePaths, this.config.pageExtensions)
const entrypoints = createEntrypoints(pages, 'server', this.buildId, this.config) const entrypoints = createEntrypoints(pages, 'server', this.buildId, this.config)
return Promise.all([ return Promise.all([
...@@ -240,7 +240,7 @@ export default class HotReloader { ...@@ -240,7 +240,7 @@ export default class HotReloader {
return return
} }
const {compilation} = stats const { compilation } = stats
// We only watch `_document` for changes on the server compilation // We only watch `_document` for changes on the server compilation
// the rest of the files will be triggered by the client compilation // the rest of the files will be triggered by the client compilation
...@@ -359,7 +359,7 @@ export default class HotReloader { ...@@ -359,7 +359,7 @@ export default class HotReloader {
await this.onDemandEntries.waitUntilReloaded() await this.onDemandEntries.waitUntilReloaded()
if (this.stats.hasErrors()) { if (this.stats.hasErrors()) {
const {compilation} = this.stats const { compilation } = this.stats
const failedPages = erroredPages(compilation, { const failedPages = erroredPages(compilation, {
enhanceName (name) { enhanceName (name) {
return '/' + ROUTE_NAME_REGEX.exec(name)[1] return '/' + ROUTE_NAME_REGEX.exec(name)[1]
......
import Server from 'next-server/dist/server/next-server' import Server from 'next-server/dist/server/next-server'
import { join } from 'path' import { join } from 'path'
import HotReloader from './hot-reloader' import HotReloader from './hot-reloader'
import {route} from 'next-server/dist/server/router' import { route } from 'next-server/dist/server/router'
import {PHASE_DEVELOPMENT_SERVER} from 'next-server/constants' import { PHASE_DEVELOPMENT_SERVER } from 'next-server/constants'
import ErrorDebug from './error-debug' import ErrorDebug from './error-debug'
export default class DevServer extends Server { export default class DevServer extends Server {
...@@ -28,9 +28,9 @@ export default class DevServer extends Server { ...@@ -28,9 +28,9 @@ export default class DevServer extends Server {
// So that the user doesn't have to define a custom server reading the exportPathMap // So that the user doesn't have to define a custom server reading the exportPathMap
if (this.nextConfig.exportPathMap) { if (this.nextConfig.exportPathMap) {
console.log('Defining routes from exportPathMap') console.log('Defining routes from exportPathMap')
const exportPathMap = await this.nextConfig.exportPathMap({}, {dev: true, dir: this.dir, outDir: null, distDir: this.distDir, buildId: this.buildId}) // In development we can't give a default path mapping const exportPathMap = await this.nextConfig.exportPathMap({}, { dev: true, dir: this.dir, outDir: null, distDir: this.distDir, buildId: this.buildId }) // In development we can't give a default path mapping
for (const path in exportPathMap) { for (const path in exportPathMap) {
const {page, query = {}} = exportPathMap[path] const { page, query = {} } = exportPathMap[path]
// We use unshift so that we're sure the routes is defined before Next's default routes // We use unshift so that we're sure the routes is defined before Next's default routes
this.router.add({ this.router.add({
...@@ -42,7 +42,7 @@ export default class DevServer extends Server { ...@@ -42,7 +42,7 @@ export default class DevServer extends Server {
.filter(key => query[key] === undefined) .filter(key => query[key] === undefined)
.forEach(key => console.warn(`Url defines a query parameter '${key}' that is missing in exportPathMap`)) .forEach(key => console.warn(`Url defines a query parameter '${key}' that is missing in exportPathMap`))
const mergedQuery = {...urlQuery, ...query} const mergedQuery = { ...urlQuery, ...query }
await this.render(req, res, page, mergedQuery, parsedUrl) await this.render(req, res, page, mergedQuery, parsedUrl)
} }
...@@ -67,7 +67,7 @@ export default class DevServer extends Server { ...@@ -67,7 +67,7 @@ export default class DevServer extends Server {
async run (req, res, parsedUrl) { async run (req, res, parsedUrl) {
await this.devReady await this.devReady
const {finished} = await this.hotReloader.run(req, res, parsedUrl) const { finished } = await this.hotReloader.run(req, res, parsedUrl)
if (finished) { if (finished) {
return return
} }
......
import DynamicEntryPlugin from 'webpack/lib/DynamicEntryPlugin' import DynamicEntryPlugin from 'webpack/lib/DynamicEntryPlugin'
import { EventEmitter } from 'events' import { EventEmitter } from 'events'
import { join } from 'path' import { join } from 'path'
import {parse} from 'url' import { parse } from 'url'
import fs from 'fs' import fs from 'fs'
import promisify from '../lib/promisify' import promisify from '../lib/promisify'
import globModule from 'glob' import globModule from 'glob'
import {pageNotFoundError} from 'next-server/dist/server/require' import { pageNotFoundError } from 'next-server/dist/server/require'
import {normalizePagePath} from 'next-server/dist/server/normalize-page-path' import { normalizePagePath } from 'next-server/dist/server/normalize-page-path'
import { ROUTE_NAME_REGEX, IS_BUNDLED_PAGE_REGEX } from 'next-server/constants' import { ROUTE_NAME_REGEX, IS_BUNDLED_PAGE_REGEX } from 'next-server/constants'
import {stringify} from 'querystring' import { stringify } from 'querystring'
const ADDED = Symbol('added') const ADDED = Symbol('added')
const BUILDING = Symbol('building') const BUILDING = Symbol('building')
...@@ -46,7 +46,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -46,7 +46,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
'X-Accel-Buffering': 'no', 'X-Accel-Buffering': 'no',
'Connection': 'keep-alive' 'Connection': 'keep-alive'
} }
const {compilers} = multiCompiler const { compilers } = multiCompiler
const invalidator = new Invalidator(devMiddleware, multiCompiler) const invalidator = new Invalidator(devMiddleware, multiCompiler)
let entries = {} let entries = {}
let lastAccessPages = [''] let lastAccessPages = ['']
...@@ -70,7 +70,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -70,7 +70,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
} }
entries[page].status = BUILDING entries[page].status = BUILDING
return addEntry(compilation, compiler.context, name, [compiler.name === 'client' ? `next-client-pages-loader?${stringify({page, absolutePagePath})}!` : absolutePagePath]) return addEntry(compilation, compiler.context, name, [compiler.name === 'client' ? `next-client-pages-loader?${stringify({ page, absolutePagePath })}!` : absolutePagePath])
}) })
return Promise.all(allEntries) return Promise.all(allEntries)
...@@ -223,7 +223,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, { ...@@ -223,7 +223,7 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
const extensions = pageExtensions.join('|') const extensions = pageExtensions.join('|')
const pagesDir = join(dir, 'pages') const pagesDir = join(dir, 'pages')
let paths = await glob(`{${normalizedPagePath.slice(1)}/index,${normalizedPagePath.slice(1)}}.+(${extensions})`, {cwd: pagesDir}) let paths = await glob(`{${normalizedPagePath.slice(1)}/index,${normalizedPagePath.slice(1)}}.+(${extensions})`, { cwd: pagesDir })
// Default the /_error route to the Next.js provided default page // Default the /_error route to the Next.js provided default page
if (page === '/_error' && paths.length === 0) { if (page === '/_error' && paths.length === 0) {
......
...@@ -6,7 +6,7 @@ try { ...@@ -6,7 +6,7 @@ try {
module.exports = function (task) { module.exports = function (task) {
task.plugin('typescript', { every: true }, function * (file, options) { task.plugin('typescript', { every: true }, function * (file, options) {
const {stripExtension} = options const { stripExtension } = options
const opts = { const opts = {
fileName: file.base, fileName: file.base,
compilerOptions: { compilerOptions: {
......
...@@ -23,38 +23,38 @@ export async function compile (task) { ...@@ -23,38 +23,38 @@ export async function compile (task) {
} }
export async function bin (task, opts) { export async function bin (task, opts) {
await task.source(opts.src || 'bin/*').typescript({module: 'commonjs', stripExtension: true}).target('dist/bin', {mode: '0755'}) await task.source(opts.src || 'bin/*').typescript({ module: 'commonjs', stripExtension: true }).target('dist/bin', { mode: '0755' })
notify('Compiled binaries') notify('Compiled binaries')
} }
export async function lib (task, opts) { export async function lib (task, opts) {
await task.source(opts.src || 'lib/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).target('dist/lib') await task.source(opts.src || 'lib/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/lib')
notify('Compiled lib files') notify('Compiled lib files')
} }
export async function server (task, opts) { export async function server (task, opts) {
await task.source(opts.src || 'server/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).target('dist/server') await task.source(opts.src || 'server/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/server')
notify('Compiled server files') notify('Compiled server files')
} }
export async function nextbuild (task, opts) { export async function nextbuild (task, opts) {
await task.source(opts.src || 'build/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).target('dist/build') await task.source(opts.src || 'build/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/build')
notify('Compiled build files') notify('Compiled build files')
} }
export async function client (task, opts) { export async function client (task, opts) {
await task.source(opts.src || 'client/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).babel(babelOpts).target('dist/client') await task.source(opts.src || 'client/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).babel(babelOpts).target('dist/client')
notify('Compiled client files') notify('Compiled client files')
} }
// export is a reserved keyword for functions // export is a reserved keyword for functions
export async function nextbuildstatic (task, opts) { export async function nextbuildstatic (task, opts) {
await task.source(opts.src || 'export/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).target('dist/export') await task.source(opts.src || 'export/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/export')
notify('Compiled export files') notify('Compiled export files')
} }
export async function pages (task, opts) { export async function pages (task, opts) {
await task.source(opts.src || 'pages/**/*.+(js|ts|tsx)').typescript({module: 'commonjs'}).babel(babelOpts).target('dist/pages') await task.source(opts.src || 'pages/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).babel(babelOpts).target('dist/pages')
} }
export async function build (task) { export async function build (task) {
......
import {useAmp} from 'next/amp' import { useAmp } from 'next/amp'
export default () => { export default () => {
const isAmp = useAmp() const isAmp = useAmp()
......
import React from 'react' import React from 'react'
import App, {Container} from 'next/app' import App, { Container } from 'next/app'
export default class MyApp extends App { export default class MyApp extends App {
// find this // find this
static async getInitialProps ({ ctx }) { static async getInitialProps ({ ctx }) {
const { query, pathname, asPath } = ctx const { query, pathname, asPath } = ctx
return {url: {query, pathname, asPath}} return { url: { query, pathname, asPath } }
} }
render () { render () {
const {Component, url} = this.props const { Component, url } = this.props
return <Container><Component url={url} /></Container> return <Container><Component url={url} /></Container>
} }
} }
import App, {Container} from 'next/app' import App, { Container } from 'next/app'
import React from 'react' import React from 'react'
import {setState} from '../shared-module' import { setState } from '../shared-module'
setState(typeof window === 'undefined' ? 'UPDATED' : 'UPDATED CLIENT') setState(typeof window === 'undefined' ? 'UPDATED' : 'UPDATED CLIENT')
...@@ -10,12 +10,12 @@ class Layout extends React.Component { ...@@ -10,12 +10,12 @@ class Layout extends React.Component {
} }
componentDidMount () { componentDidMount () {
this.setState({random: Math.random()}) this.setState({ random: Math.random() })
} }
render () { render () {
const {children} = this.props const { children } = this.props
const {random} = this.state const { random } = this.state
return <div> return <div>
<p id='hello-app'>Hello App</p> <p id='hello-app'>Hello App</p>
<p id='hello-hmr'>Hello HMR</p> <p id='hello-hmr'>Hello HMR</p>
...@@ -33,11 +33,11 @@ export default class MyApp extends App { ...@@ -33,11 +33,11 @@ export default class MyApp extends App {
pageProps = await Component.getInitialProps(ctx) pageProps = await Component.getInitialProps(ctx)
} }
return {pageProps} return { pageProps }
} }
render () { render () {
const {Component, pageProps} = this.props const { Component, pageProps } = this.props
return <Container> return <Container>
<Layout> <Layout>
<Component {...pageProps} /> <Component {...pageProps} />
......
import React, {Component} from 'react' import React, { Component } from 'react'
export default class extends Component { export default class extends Component {
constructor (props) { constructor (props) {
...@@ -10,7 +10,7 @@ export default class extends Component { ...@@ -10,7 +10,7 @@ export default class extends Component {
} }
componentDidMount () { componentDidMount () {
this.setState({mounted: true}) this.setState({ mounted: true })
} }
render () { render () {
......
import React from 'react' import React from 'react'
export default class extends React.Component { export default class extends React.Component {
static async getInitialProps ({res}) { static async getInitialProps ({ res }) {
if (res) { if (res) {
res.setHeader('Content-Type', 'text/html; charset=iso-8859-2') res.setHeader('Content-Type', 'text/html; charset=iso-8859-2')
} }
......
import {World} from '../components/world' import { World } from '../components/world'
import {Hello} from '../components/hello.jsx' import { Hello } from '../components/hello.jsx'
export default () => ( export default () => (
<div><Hello /> <World /></div> <div><Hello /> <World /></div>
......
...@@ -12,7 +12,7 @@ const Test = dynamic({ ...@@ -12,7 +12,7 @@ const Test = dynamic({
background-color: green; background-color: green;
height: 200px; height: 200px;
} }
`}} /> ` }} />
</Head> </Head>
test test
</div> </div>
......
import Link from 'next/link' import Link from 'next/link'
import {withRouter} from 'next/router' import { withRouter } from 'next/router'
export default withRouter(({router: {asPath, query}}) => { export default withRouter(({ router: { asPath, query } }) => {
return <div id={asPath.replace('/', '').replace('/', '-')}> return <div id={asPath.replace('/', '').replace('/', '-')}>
<div id='router-query'>{JSON.stringify(query)}</div> <div id='router-query'>{JSON.stringify(query)}</div>
<div> <div>
......
...@@ -31,10 +31,10 @@ export default class SelfReload extends Component { ...@@ -31,10 +31,10 @@ export default class SelfReload extends Component {
<a id='scroll-to-name-item-400'>Go to name item 400</a> <a id='scroll-to-name-item-400'>Go to name item 400</a>
</Link> </Link>
<p>COUNT: {this.props.count}</p> <p>COUNT: {this.props.count}</p>
{Array.from({length: 500}, (x, i) => i + 1).map(i => { {Array.from({ length: 500 }, (x, i) => i + 1).map(i => {
return <div key={`item-${i}`} id={`item-${i}`}>{i}</div> return <div key={`item-${i}`} id={`item-${i}`}>{i}</div>
})} })}
{Array.from({length: 500}, (x, i) => i + 1).map(i => { {Array.from({ length: 500 }, (x, i) => i + 1).map(i => {
return <div key={`item-${i}`} name={`name-item-${i}`}>{i}</div> return <div key={`item-${i}`} name={`name-item-${i}`}>{i}</div>
})} })}
</div> </div>
......
...@@ -2,7 +2,7 @@ import { Component } from 'react' ...@@ -2,7 +2,7 @@ import { Component } from 'react'
import Link from 'next/link' import Link from 'next/link'
export default class OnClick extends Component { export default class OnClick extends Component {
static getInitialProps ({ res, query: {count} }) { static getInitialProps ({ res, query: { count } }) {
return { count: count ? parseInt(count) : 0 } return { count: count ? parseInt(count) : 0 }
} }
...@@ -11,17 +11,17 @@ export default class OnClick extends Component { ...@@ -11,17 +11,17 @@ export default class OnClick extends Component {
} }
render () { render () {
const {stateCounter} = this.state const { stateCounter } = this.state
const {count} = this.props const { count } = this.props
return ( return (
<div id='on-click-page'> <div id='on-click-page'>
<Link href={`/nav/on-click?count=${count + 1}`} replace> <Link href={`/nav/on-click?count=${count + 1}`} replace>
<a id='on-click-link' onClick={() => this.setState({stateCounter: stateCounter + 1})}>Self Reload</a> <a id='on-click-link' onClick={() => this.setState({ stateCounter: stateCounter + 1 })}>Self Reload</a>
</Link> </Link>
<Link href='/nav/on-click'> <Link href='/nav/on-click'>
<a id='on-click-link-prevent-default' onClick={(e) => { <a id='on-click-link-prevent-default' onClick={(e) => {
e.preventDefault() e.preventDefault()
this.setState({stateCounter: stateCounter + 1}) this.setState({ stateCounter: stateCounter + 1 })
}}>Self Reload</a> }}>Self Reload</a>
</Link> </Link>
<p id='query-count'>QUERY COUNT: {count}</p> <p id='query-count'>QUERY COUNT: {count}</p>
......
...@@ -2,8 +2,8 @@ import Link from 'next/link' ...@@ -2,8 +2,8 @@ import Link from 'next/link'
const UnexpectedNestedA = () => { const UnexpectedNestedA = () => {
const UnexpectedWrapper = (props) => { const UnexpectedWrapper = (props) => {
const {href, id} = props const { href, id } = props
const safeProps = {href, id} const safeProps = { href, id }
return (<a {...safeProps}>{props.children}</a>) return (<a {...safeProps}>{props.children}</a>)
} }
......
...@@ -23,7 +23,7 @@ export default class UrlPropChange extends React.Component { ...@@ -23,7 +23,7 @@ export default class UrlPropChange extends React.Component {
} }
render () { render () {
const {previousUrl, url} = this.state const { previousUrl, url } = this.state
return <div> return <div>
Current: Current:
<div id='url-result'> <div id='url-result'>
......
import { withRouter } from 'next/router' import { withRouter } from 'next/router'
const Link = withRouter(({router, children, href}) => { const Link = withRouter(({ router, children, href }) => {
const handleClick = (e) => { const handleClick = (e) => {
e.preventDefault() e.preventDefault()
router.push(href) router.push(href)
......
...@@ -6,7 +6,7 @@ function ReadOnlyObjectError () { ...@@ -6,7 +6,7 @@ function ReadOnlyObjectError () {
ReadOnlyObjectError.getInitialProps = async () => { ReadOnlyObjectError.getInitialProps = async () => {
const result = await test() const result = await test()
return {result} return { result }
} }
export default ReadOnlyObjectError export default ReadOnlyObjectError
...@@ -6,7 +6,7 @@ export default class extends React.Component { ...@@ -6,7 +6,7 @@ export default class extends React.Component {
} }
} }
render () { render () {
const {url} = this.props const { url } = this.props
return <div> return <div>
<p id='pathname'>{url.pathname}</p> <p id='pathname'>{url.pathname}</p>
<p id='query'>{Object.keys(url.query).length}</p> <p id='query'>{Object.keys(url.query).length}</p>
......
export default ({url}) => { export default ({ url }) => {
return <div> return <div>
<p id='pathname'>{url.pathname}</p> <p id='pathname'>{url.pathname}</p>
<p id='query'>{Object.keys(url.query).length}</p> <p id='query'>{Object.keys(url.query).length}</p>
......
/* eslint-env jest */ /* eslint-env jest */
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import {waitFor, getReactErrorOverlayContent} from 'next-test-utils' import { waitFor, getReactErrorOverlayContent } from 'next-test-utils'
export default (context) => { export default (context) => {
describe('Client Navigation', () => { describe('Client Navigation', () => {
...@@ -40,8 +40,8 @@ export default (context) => { ...@@ -40,8 +40,8 @@ export default (context) => {
const urlResult = await browser.elementByCss('#url-result').text() const urlResult = await browser.elementByCss('#url-result').text()
const previousUrlResult = await browser.elementByCss('#previous-url-result').text() const previousUrlResult = await browser.elementByCss('#previous-url-result').text()
expect(JSON.parse(urlResult)).toMatchObject({'query': {'added': 'yes'}, 'pathname': '/nav/url-prop-change', 'asPath': '/nav/url-prop-change?added=yes'}) expect(JSON.parse(urlResult)).toMatchObject({ 'query': { 'added': 'yes' }, 'pathname': '/nav/url-prop-change', 'asPath': '/nav/url-prop-change?added=yes' })
expect(JSON.parse(previousUrlResult)).toMatchObject({'query': {}, 'pathname': '/nav/url-prop-change', 'asPath': '/nav/url-prop-change'}) expect(JSON.parse(previousUrlResult)).toMatchObject({ 'query': {}, 'pathname': '/nav/url-prop-change', 'asPath': '/nav/url-prop-change' })
browser.close() browser.close()
}) })
......
/* eslint-env jest */ /* eslint-env jest */
import cheerio from 'cheerio' import cheerio from 'cheerio'
import {BUILD_MANIFEST, REACT_LOADABLE_MANIFEST} from 'next-server/constants' import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST } from 'next-server/constants'
import { join } from 'path' import { join } from 'path'
export default function ({ app }, suiteName, render, fetch) { export default function ({ app }, suiteName, render, fetch) {
......
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
runNextCommandDev, runNextCommandDev,
findPort findPort
} from 'next-test-utils' } from 'next-test-utils'
import {join} from 'path' import { join } from 'path'
import pkg from 'next/package' import pkg from 'next/package'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
......
...@@ -17,7 +17,7 @@ module.exports = withCSS(withSass({ ...@@ -17,7 +17,7 @@ module.exports = withCSS(withSass({
env: { env: {
customVar: 'hello' customVar: 'hello'
}, },
webpack (config, {buildId}) { webpack (config, { buildId }) {
// When next-css is `npm link`ed we have to solve loaders from the project root // When next-css is `npm link`ed we have to solve loaders from the project root
const nextLocation = path.join(require.resolve('next/package.json'), '../') const nextLocation = path.join(require.resolve('next/package.json'), '../')
const nextCssNodeModulesLocation = path.join( const nextCssNodeModulesLocation = path.join(
......
import getConfig from 'next/config' import getConfig from 'next/config'
const {serverRuntimeConfig, publicRuntimeConfig} = getConfig() const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
export default () => <div> export default () => <div>
<p id='server-only'>{serverRuntimeConfig.mySecret}</p> <p id='server-only'>{serverRuntimeConfig.mySecret}</p>
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
/* global jasmine */ /* global jasmine */
import { join } from 'path' import { join } from 'path'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import {BUILD_ID_FILE} from 'next-server/constants' import { BUILD_ID_FILE } from 'next-server/constants'
import { import {
nextServer, nextServer,
nextBuild, nextBuild,
......
const {PHASE_DEVELOPMENT_SERVER} = require('next-server/constants') const { PHASE_DEVELOPMENT_SERVER } = require('next-server/constants')
module.exports = (phase) => { module.exports = (phase) => {
return { return {
......
...@@ -6,7 +6,7 @@ module.exports = { ...@@ -6,7 +6,7 @@ module.exports = {
useFileSystemPublicRoutes: false, useFileSystemPublicRoutes: false,
exportPathMap () { exportPathMap () {
return { return {
'/exportpathmap-route': {page: '/exportpathmap-route'} '/exportpathmap-route': { page: '/exportpathmap-route' }
} }
} }
} }
...@@ -48,7 +48,7 @@ function runNextCommand (argv, options = {}) { ...@@ -48,7 +48,7 @@ function runNextCommand (argv, options = {}) {
describe('Production Custom Build Directory', () => { describe('Production Custom Build Directory', () => {
describe('With basic usage', () => { describe('With basic usage', () => {
it('should render the page', async () => { it('should render the page', async () => {
const result = await runNextCommand(['build', 'build'], {stdout: true, stderr: true}) const result = await runNextCommand(['build', 'build'], { stdout: true, stderr: true })
expect(result.stderr).toBe('') expect(result.stderr).toBe('')
const app = nextServer({ const app = nextServer({
......
import React, {Component} from 'react' import React, { Component } from 'react'
export default class extends Component { export default class extends Component {
constructor (props) { constructor (props) {
...@@ -10,7 +10,7 @@ export default class extends Component { ...@@ -10,7 +10,7 @@ export default class extends Component {
} }
componentDidMount () { componentDidMount () {
this.setState({mounted: true}) this.setState({ mounted: true })
} }
render () { render () {
......
...@@ -41,27 +41,27 @@ describe('Production Config Usage', () => { ...@@ -41,27 +41,27 @@ describe('Production Config Usage', () => {
describe('env', () => { describe('env', () => {
it('should fail with __ in env key', async () => { it('should fail with __ in env key', async () => {
const result = await runNextCommand(['build', appDir], {spawnOptions: { const result = await runNextCommand(['build', appDir], { spawnOptions: {
env: { env: {
...process.env, ...process.env,
ENABLE_ENV_FAIL_UNDERSCORE: true ENABLE_ENV_FAIL_UNDERSCORE: true
} }
}, },
stdout: true, stdout: true,
stderr: true}) stderr: true })
expect(result.stderr).toMatch(/The key "__NEXT_MY_VAR" under/) expect(result.stderr).toMatch(/The key "__NEXT_MY_VAR" under/)
}) })
it('should fail with NODE_ in env key', async () => { it('should fail with NODE_ in env key', async () => {
const result = await runNextCommand(['build', appDir], {spawnOptions: { const result = await runNextCommand(['build', appDir], { spawnOptions: {
env: { env: {
...process.env, ...process.env,
ENABLE_ENV_FAIL_NODE: true ENABLE_ENV_FAIL_NODE: true
} }
}, },
stdout: true, stdout: true,
stderr: true}) stderr: true })
expect(result.stderr).toMatch(/The key "NODE_ENV" under/) expect(result.stderr).toMatch(/The key "NODE_ENV" under/)
}) })
......
...@@ -16,7 +16,7 @@ import fetch from 'node-fetch' ...@@ -16,7 +16,7 @@ import fetch from 'node-fetch'
import dynamicImportTests from './dynamic' import dynamicImportTests from './dynamic'
import processEnv from './process-env' import processEnv from './process-env'
import security from './security' import security from './security'
import {BUILD_MANIFEST, REACT_LOADABLE_MANIFEST, PAGES_MANIFEST} from 'next-server/constants' import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST, PAGES_MANIFEST } from 'next-server/constants'
import cheerio from 'cheerio' import cheerio from 'cheerio'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
let appPort let appPort
...@@ -81,7 +81,7 @@ describe('Production Usage', () => { ...@@ -81,7 +81,7 @@ describe('Production Usage', () => {
const url = `http://localhost:${appPort}/_next/abcdef` const url = `http://localhost:${appPort}/_next/abcdef`
const methods = ['POST', 'PUT', 'DELETE'] const methods = ['POST', 'PUT', 'DELETE']
for (const method of methods) { for (const method of methods) {
const res = await fetch(url, {method}) const res = await fetch(url, { method })
expect(res.status).toBe(501) expect(res.status).toBe(501)
} }
}) })
......
...@@ -7,17 +7,17 @@ export default class extends React.Component { ...@@ -7,17 +7,17 @@ export default class extends React.Component {
const res = await fetch('') const res = await fetch('')
const text = await res.text() const text = await res.text()
console.log(text) console.log(text)
return {text} return { text }
} catch (err) { } catch (err) {
if (err.message.includes('is not a function')) { if (err.message.includes('is not a function')) {
return {failed: true, error: err.toString()} return { failed: true, error: err.toString() }
} }
return {error: err.toString()} return { error: err.toString() }
} }
} }
render () { render () {
const {failed, error, text} = this.props const { failed, error, text } = this.props
return <div className='fetch-page'> return <div className='fetch-page'>
{failed ? 'failed' : ''} {failed ? 'failed' : ''}
{error} {error}
......
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer') const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
module.exports = { module.exports = {
webpack (config, {isServer}) { webpack (config, { isServer }) {
config.plugins.push(new BundleAnalyzerPlugin({ config.plugins.push(new BundleAnalyzerPlugin({
analyzerMode: 'static', analyzerMode: 'static',
reportFilename: `dist/${isServer ? 'server' : 'client'}.html`, reportFilename: `dist/${isServer ? 'server' : 'client'}.html`,
......
...@@ -10,7 +10,7 @@ export default class MyApp extends App { ...@@ -10,7 +10,7 @@ export default class MyApp extends App {
pageProps = await Component.getInitialProps(ctx) pageProps = await Component.getInitialProps(ctx)
} }
return {pageProps} return { pageProps }
} }
render () { render () {
......
module.exports = (phase, {defaultConfig}) => { module.exports = (phase, { defaultConfig }) => {
return { return {
phase, phase,
defaultConfig, defaultConfig,
......
/* eslint-env jest */ /* eslint-env jest */
import {join} from 'path' import { join } from 'path'
import loadConfig from 'next-server/next-config' import loadConfig from 'next-server/next-config'
import {PHASE_DEVELOPMENT_SERVER} from 'next-server/constants' import { PHASE_DEVELOPMENT_SERVER } from 'next-server/constants'
const pathToConfig = join(__dirname, '_resolvedata', 'without-function') const pathToConfig = join(__dirname, '_resolvedata', 'without-function')
const pathToConfigFn = join(__dirname, '_resolvedata', 'with-function') const pathToConfigFn = join(__dirname, '_resolvedata', 'with-function')
...@@ -24,7 +24,7 @@ describe('config', () => { ...@@ -24,7 +24,7 @@ describe('config', () => {
}) })
it('Should pass the customConfig correctly', () => { it('Should pass the customConfig correctly', () => {
const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, {customConfig: true}) const config = loadConfig(PHASE_DEVELOPMENT_SERVER, null, { customConfig: true })
expect(config.customConfig).toBe(true) expect(config.customConfig).toBe(true)
}) })
......
/* eslint-env jest */ /* eslint-env jest */
import { join } from 'path' import { join } from 'path'
import {SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH} from 'next-server/constants' import { SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH } from 'next-server/constants'
import {requirePage, getPagePath, pageNotFoundError} from 'next-server/dist/server/require' import { requirePage, getPagePath, pageNotFoundError } from 'next-server/dist/server/require'
import {normalizePagePath} from 'next-server/dist/server/normalize-page-path' import { normalizePagePath } from 'next-server/dist/server/normalize-page-path'
const sep = '/' const sep = '/'
const distDir = join(__dirname, '_resolvedata') const distDir = join(__dirname, '_resolvedata')
......
...@@ -140,7 +140,7 @@ export function nextBuild (dir, args = []) { ...@@ -140,7 +140,7 @@ export function nextBuild (dir, args = []) {
return runNextCommand(['build', dir, ...args]) return runNextCommand(['build', dir, ...args])
} }
export function nextExport (dir, {outdir}) { export function nextExport (dir, { outdir }) {
return runNextCommand(['export', dir, '--outdir', outdir]) return runNextCommand(['export', dir, '--outdir', outdir])
} }
...@@ -203,9 +203,9 @@ export async function check (contentFn, regex) { ...@@ -203,9 +203,9 @@ export async function check (contentFn, regex) {
try { try {
content = await contentFn() content = await contentFn()
} catch (err) { } catch (err) {
console.error('Error while getting content', {regex}) console.error('Error while getting content', { regex })
} }
console.error('TIMED OUT CHECK: ', {regex, content}) console.error('TIMED OUT CHECK: ', { regex, content })
throw new Error('TIMED OUT: ' + regex + '\n\n' + content) throw new Error('TIMED OUT: ' + regex + '\n\n' + content)
}, 1000 * 30) }, 1000 * 30)
while (!found) { while (!found) {
......
...@@ -37,7 +37,7 @@ function getBrowser (url, timeout) { ...@@ -37,7 +37,7 @@ function getBrowser (url, timeout) {
reject(error) reject(error)
}, timeout) }, timeout)
browser.init({browserName: 'chrome'}).get(url, err => { browser.init({ browserName: 'chrome' }).get(url, err => {
if (timeouted) { if (timeouted) {
try { try {
browser.close(() => { browser.close(() => {
......
/* eslint-env jest */ /* eslint-env jest */
// These tests are based on https://github.com/zertosh/htmlescape/blob/3e6cf0614dd0f778fd0131e69070b77282150c15/test/htmlescape-test.js // These tests are based on https://github.com/zertosh/htmlescape/blob/3e6cf0614dd0f778fd0131e69070b77282150c15/test/htmlescape-test.js
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE // License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
import {htmlEscapeJsonString} from 'next/dist/server/htmlescape' import { htmlEscapeJsonString } from 'next/dist/server/htmlescape'
import vm from 'vm' import vm from 'vm'
describe('htmlescape', () => { describe('htmlescape', () => {
test('with angle brackets should escape', () => { test('with angle brackets should escape', () => {
const evilObj = {evil: '<script></script>'} const evilObj = { evil: '<script></script>' }
expect(htmlEscapeJsonString(JSON.stringify(evilObj))).toBe('{"evil":"\\u003cscript\\u003e\\u003c/script\\u003e"}') expect(htmlEscapeJsonString(JSON.stringify(evilObj))).toBe('{"evil":"\\u003cscript\\u003e\\u003c/script\\u003e"}')
}) })
test('with angle brackets should parse back', () => { test('with angle brackets should parse back', () => {
const evilObj = {evil: '<script></script>'} const evilObj = { evil: '<script></script>' }
expect(JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj)))).toMatchObject(evilObj) expect(JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj)))).toMatchObject(evilObj)
}) })
test('with ampersands should escape', () => { test('with ampersands should escape', () => {
const evilObj = {evil: '&'} const evilObj = { evil: '&' }
expect(htmlEscapeJsonString(JSON.stringify(evilObj))).toBe('{"evil":"\\u0026"}') expect(htmlEscapeJsonString(JSON.stringify(evilObj))).toBe('{"evil":"\\u0026"}')
}) })
test('with ampersands should parse back', () => { test('with ampersands should parse back', () => {
const evilObj = {evil: '&'} const evilObj = { evil: '&' }
expect(JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj)))).toMatchObject(evilObj) expect(JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj)))).toMatchObject(evilObj)
}) })
test('with "LINE SEPARATOR" and "PARAGRAPH SEPARATOR" should escape', () => { test('with "LINE SEPARATOR" and "PARAGRAPH SEPARATOR" should escape', () => {
const evilObj = {evil: '\u2028\u2029'} const evilObj = { evil: '\u2028\u2029' }
expect(htmlEscapeJsonString(JSON.stringify(evilObj))).toBe('{"evil":"\\u2028\\u2029"}') expect(htmlEscapeJsonString(JSON.stringify(evilObj))).toBe('{"evil":"\\u2028\\u2029"}')
}) })
test('with "LINE SEPARATOR" and "PARAGRAPH SEPARATOR" should parse back', () => { test('with "LINE SEPARATOR" and "PARAGRAPH SEPARATOR" should parse back', () => {
const evilObj = {evil: '\u2028\u2029'} const evilObj = { evil: '\u2028\u2029' }
expect(JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj)))).toMatchObject(evilObj) expect(JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj)))).toMatchObject(evilObj)
}) })
test('escaped line terminators should work', () => { test('escaped line terminators should work', () => {
expect(() => { expect(() => {
vm.runInNewContext('(' + htmlEscapeJsonString(JSON.stringify({evil: '\u2028\u2029'})) + ')') vm.runInNewContext('(' + htmlEscapeJsonString(JSON.stringify({ evil: '\u2028\u2029' })) + ')')
}).not.toThrow() }).not.toThrow()
}) })
}) })
/* eslint-env jest */ /* eslint-env jest */
import {PHASE_EXPORT, PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER} from 'next/constants' import { PHASE_EXPORT, PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_SERVER, PHASE_DEVELOPMENT_SERVER } from 'next/constants'
describe('phaseConstants', () => { describe('phaseConstants', () => {
it('should set phases correctly', () => { it('should set phases correctly', () => {
......
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