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